lang
stringclasses
1 value
license
stringclasses
13 values
stderr
stringlengths
0
350
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
7
45.1k
new_contents
stringlengths
0
1.87M
new_file
stringlengths
6
292
old_contents
stringlengths
0
1.87M
message
stringlengths
6
9.26k
old_file
stringlengths
6
292
subject
stringlengths
0
4.45k
Java
apache-2.0
c48e1e603fc2b974df1dd5e85758d3ff8aa420b1
0
apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.shardingsphere.core.strategy.encrypt; import com.google.common.base.Function; import com.google.common.base.Optional; import com.google.common.collect.Maps; import org.apache.shardingsphere.api.config.encrypt.EncryptColumnRuleConfiguration; import org.apache.shardingsphere.api.config.encrypt.EncryptTableRuleConfiguration; import org.apache.shardingsphere.core.exception.ShardingException; import java.util.Collection; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.Map; import java.util.Map.Entry; /** * Encryptor strategy. * * @author panjuan */ public final class EncryptTable { private final Map<String, EncryptColumn> columns = new LinkedHashMap<>(); public EncryptTable(final EncryptTableRuleConfiguration config) { columns.putAll(Maps.transformValues(config.getColumns(), new Function<EncryptColumnRuleConfiguration, EncryptColumn>() { @Override public EncryptColumn apply(final EncryptColumnRuleConfiguration input) { return new EncryptColumn(input.getPlainColumn(), input.getCipherColumn(), input.getAssistedQueryColumn(), input.getEncryptor()); } })); } /** * Get sharding encryptor. * * @param logicColumn column name * @return optional of sharding encryptor */ public Optional<String> getShardingEncryptor(final String logicColumn) { return columns.containsKey(logicColumn) ? Optional.of(columns.get(logicColumn).getEncryptor()) : Optional.<String>absent(); } /** * Get logic column. * * @param cipherColumn cipher column * @return logic column */ public String getLogicColumn(final String cipherColumn) { for (Entry<String, EncryptColumn> entry : columns.entrySet()) { if (entry.getValue().getCipherColumn().equals(cipherColumn)) { return entry.getKey(); } } throw new ShardingException("Can not find logic column by %s.", cipherColumn); } /** * Get plain column. * * @param logicColumn logic column name * @return plain column */ public Optional<String> getPlainColumn(final String logicColumn) { return columns.get(logicColumn).getPlainColumn(); } /** * Get plain columns. * * @return plain columns */ public Collection<String> getPlainColumns() { Collection<String> result = new LinkedList<>(); for (EncryptColumn each : columns.values()) { if (each.getPlainColumn().isPresent()) { result.add(each.getPlainColumn().get()); } } return result; } /** * Is has plain column or not. * * @return has plain column or not */ public boolean isHasPlainColumn() { for (EncryptColumn each : columns.values()) { if (each.getPlainColumn().isPresent()) { return true; } } return false; } /** * Get cipher column. * * @param logicColumn logic column name * @return cipher column */ public String getCipherColumn(final String logicColumn) { return columns.get(logicColumn).getCipherColumn(); } /** * Get cipher columns. * * @return cipher columns */ public Collection<String> getCipherColumns() { Collection<String> result = new LinkedList<>(); for (EncryptColumn each : columns.values()) { if (each.getPlainColumn().isPresent()) { result.add(each.getCipherColumn()); } } return result; } /** * Get assisted query column. * * @param logicColumn column name * @return assisted query column */ public Optional<String> getAssistedQueryColumn(final String logicColumn) { if (!columns.containsKey(logicColumn)) { return Optional.absent(); } return columns.get(logicColumn).getAssistedQueryColumn(); } /** * Get assisted query columns. * * @return assisted query columns */ public Collection<String> getAssistedQueryColumns() { Collection<String> result = new LinkedList<>(); for (EncryptColumn each : columns.values()) { if (each.getAssistedQueryColumn().isPresent()) { result.add(each.getAssistedQueryColumn().get()); } } return result; } /** * Is has query assisted column or not. * * @return has query assisted column or not */ public boolean isHasQueryAssistedColumn() { for (EncryptColumn each : columns.values()) { if (each.getAssistedQueryColumn().isPresent()) { return true; } } return false; } }
sharding-core/sharding-core-common/src/main/java/org/apache/shardingsphere/core/strategy/encrypt/EncryptTable.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.shardingsphere.core.strategy.encrypt; import com.google.common.base.Function; import com.google.common.base.Optional; import com.google.common.collect.Maps; import org.apache.shardingsphere.api.config.encrypt.EncryptColumnRuleConfiguration; import org.apache.shardingsphere.api.config.encrypt.EncryptTableRuleConfiguration; import java.util.Collection; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.Map; /** * Encryptor strategy. * * @author panjuan */ public final class EncryptTable { private final Map<String, EncryptColumn> columns = new LinkedHashMap<>(); public EncryptTable(final EncryptTableRuleConfiguration config) { columns.putAll(Maps.transformValues(config.getColumns(), new Function<EncryptColumnRuleConfiguration, EncryptColumn>() { @Override public EncryptColumn apply(final EncryptColumnRuleConfiguration input) { return new EncryptColumn(input.getPlainColumn(), input.getCipherColumn(), input.getAssistedQueryColumn(), input.getEncryptor()); } })); } /** * Get sharding encryptor. * * @param logicColumn column name * @return optional of sharding encryptor */ public Optional<String> getShardingEncryptor(final String logicColumn) { return columns.containsKey(logicColumn) ? Optional.of(columns.get(logicColumn).getEncryptor()) : Optional.<String>absent(); } /** * Is has sharding query assisted encryptor or not. * * @return has sharding query assisted encryptor or not */ public boolean isHasShardingQueryAssistedEncryptor() { for (EncryptColumn each : columns.values()) { if (each.getAssistedQueryColumn().isPresent()) { return true; } } return false; } /** * Get assisted query column. * * @param logicColumn column name * @return assisted query column */ public Optional<String> getAssistedQueryColumn(final String logicColumn) { if (!columns.containsKey(logicColumn)) { return Optional.absent(); } return columns.get(logicColumn).getAssistedQueryColumn(); } /** * Get assisted query columns. * * @return assisted query columns */ public Collection<String> getAssistedQueryColumns() { Collection<String> result = new LinkedList<>(); for (EncryptColumn each : columns.values()) { if (each.getAssistedQueryColumn().isPresent()) { result.add(each.getAssistedQueryColumn().get()); } } return result; } /** * Get plain column. * * @param logicColumn logic column name * @return plain column */ public Optional<String> getPlainColumn(final String logicColumn) { return columns.get(logicColumn).getPlainColumn(); } /** * Get cipher column. * * @param logicColumn logic column name * @return cipher column */ public String getCipherColumn(final String logicColumn) { return columns.get(logicColumn).getCipherColumn(); } }
add getLogicColumn()
sharding-core/sharding-core-common/src/main/java/org/apache/shardingsphere/core/strategy/encrypt/EncryptTable.java
add getLogicColumn()
Java
bsd-3-clause
c638020b84ebf7288c02841334e2f411ac045b3b
0
stapelberg/android-davsync,breunigs/android-davsync
package net.zekjur.davsync; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import net.zekjur.davsync.CountingInputStreamEntity.UploadListener; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; import org.apache.http.auth.AuthenticationException; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpPut; import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.client.DefaultHttpClient; import android.app.IntentService; import android.app.NotificationManager; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.net.Uri; import android.os.ParcelFileDescriptor; import android.provider.MediaStore; import android.support.v4.app.NotificationCompat; import android.support.v4.app.NotificationCompat.Builder; import android.util.Log; public class UploadService extends IntentService { public UploadService() { super("UploadService"); } /* * Resolve a Uri like “content://media/external/images/media/9210” to an * actual filename, like “IMG_20130304_181119.jpg” */ private String filenameFromUri(Uri uri) { String[] projection = { MediaStore.Images.Media.DATA }; Cursor cursor = getContentResolver().query(uri, projection, null, null, null); if (cursor == null) return null; int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); Uri filePathUri = Uri.parse(cursor.getString(column_index)); return filePathUri.getLastPathSegment().toString(); } @Override protected void onHandleIntent(Intent intent) { final Uri uri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM); Log.d("davsyncs", "Uploading " + uri.toString()); SharedPreferences preferences = getSharedPreferences("net.zekjur.davsync_preferences", Context.MODE_PRIVATE); String webdavUrl = preferences.getString("webdav_url", null); String webdavUser = preferences.getString("webdav_user", null); String webdavPassword = preferences.getString("webdav_password", null); if (webdavUrl == null) { Log.d("davsyncs", "No WebDAV URL set up."); return; } ContentResolver cr = getContentResolver(); String filename = this.filenameFromUri(uri); if (filename == null) { Log.d("davsyncs", "filenameFromUri returned null"); return; } final Builder mBuilder = new NotificationCompat.Builder(this); mBuilder.setContentTitle("Uploading to WebDAV server"); mBuilder.setContentText(filename); mBuilder.setSmallIcon(android.R.drawable.ic_menu_upload); mBuilder.setOngoing(true); mBuilder.setProgress(100, 30, false); final NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); mNotificationManager.notify(uri.toString(), 0, mBuilder.build()); HttpPut httpPut = new HttpPut(webdavUrl + filename); ParcelFileDescriptor fd; InputStream stream; try { fd = cr.openFileDescriptor(uri, "r"); stream = cr.openInputStream(uri); } catch (FileNotFoundException e1) { e1.printStackTrace(); return; } CountingInputStreamEntity entity = new CountingInputStreamEntity(stream, fd.getStatSize()); entity.setUploadListener(new UploadListener() { @Override public void onChange(int percent) { mBuilder.setProgress(100, percent, false); mNotificationManager.notify(uri.toString(), 0, mBuilder.build()); } }); httpPut.setEntity(entity); DefaultHttpClient httpClient = new DefaultHttpClient(); if (webdavUser != null && webdavPassword != null) { AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(webdavUser, webdavPassword); httpClient.getCredentialsProvider().setCredentials(authScope, credentials); try { httpPut.addHeader(new BasicScheme().authenticate(credentials, httpPut)); } catch (AuthenticationException e1) { e1.printStackTrace(); return; } } try { HttpResponse response = httpClient.execute(httpPut); int status = response.getStatusLine().getStatusCode(); // 201 means the file was created, 200 means it was stored but // already existed. if (status == 201 || status == 200) { // The file was uploaded, so we remove the ongoing notification, // remove it from the queue and that’s it. mNotificationManager.cancel(uri.toString(), 0); DavSyncOpenHelper helper = new DavSyncOpenHelper(this); helper.removeUriFromQueue(uri.toString()); return; } Log.d("davsyncs", "" + response.getStatusLine()); mBuilder.setContentText(filename + ": " + response.getStatusLine()); } catch (ClientProtocolException e) { e.printStackTrace(); mBuilder.setContentText(filename + ": " + e.getLocalizedMessage()); } catch (IOException e) { e.printStackTrace(); mBuilder.setContentText(filename + ": " + e.getLocalizedMessage()); } // XXX: It would be good to provide an option to try again. // (or try it again automatically?) // XXX: possibly we should re-queue the images in the database mBuilder.setContentTitle("Error uploading to WebDAV server"); mBuilder.setProgress(0, 0, false); mBuilder.setOngoing(false); mNotificationManager.notify(uri.toString(), 0, mBuilder.build()); } }
src/net/zekjur/davsync/UploadService.java
package net.zekjur.davsync; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import net.zekjur.davsync.CountingInputStreamEntity.UploadListener; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; import org.apache.http.auth.AuthenticationException; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpPut; import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.client.DefaultHttpClient; import android.app.IntentService; import android.app.NotificationManager; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.net.Uri; import android.os.ParcelFileDescriptor; import android.provider.MediaStore; import android.support.v4.app.NotificationCompat; import android.support.v4.app.NotificationCompat.Builder; import android.util.Log; public class UploadService extends IntentService { public UploadService() { super("UploadService"); } /* * Resolve a Uri like “content://media/external/images/media/9210” to an * actual filename, like “IMG_20130304_181119.jpg” */ private String filenameFromUri(Uri uri) { String[] projection = { MediaStore.Images.Media.DATA }; Cursor cursor = getContentResolver().query(uri, projection, null, null, null); int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); Uri filePathUri = Uri.parse(cursor.getString(column_index)); return filePathUri.getLastPathSegment().toString(); } @Override protected void onHandleIntent(Intent intent) { final Uri uri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM); Log.d("davsyncs", "Uploading " + uri.toString()); SharedPreferences preferences = getSharedPreferences("net.zekjur.davsync_preferences", Context.MODE_PRIVATE); String webdavUrl = preferences.getString("webdav_url", null); String webdavUser = preferences.getString("webdav_user", null); String webdavPassword = preferences.getString("webdav_password", null); if (webdavUrl == null) { Log.d("davsyncs", "No WebDAV URL set up."); return; } ContentResolver cr = getContentResolver(); String filename = this.filenameFromUri(uri); final Builder mBuilder = new NotificationCompat.Builder(this); mBuilder.setContentTitle("Uploading to WebDAV server"); mBuilder.setContentText(filename); mBuilder.setSmallIcon(android.R.drawable.ic_menu_upload); mBuilder.setOngoing(true); mBuilder.setProgress(100, 30, false); final NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); mNotificationManager.notify(uri.toString(), 0, mBuilder.build()); HttpPut httpPut = new HttpPut(webdavUrl + filename); ParcelFileDescriptor fd; InputStream stream; try { fd = cr.openFileDescriptor(uri, "r"); stream = cr.openInputStream(uri); } catch (FileNotFoundException e1) { e1.printStackTrace(); return; } CountingInputStreamEntity entity = new CountingInputStreamEntity(stream, fd.getStatSize()); entity.setUploadListener(new UploadListener() { public void onChange(int percent) { mBuilder.setProgress(100, percent, false); mNotificationManager.notify(uri.toString(), 0, mBuilder.build()); } }); httpPut.setEntity(entity); DefaultHttpClient httpClient = new DefaultHttpClient(); if (webdavUser != null && webdavPassword != null) { AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(webdavUser, webdavPassword); httpClient.getCredentialsProvider().setCredentials(authScope, credentials); try { httpPut.addHeader(new BasicScheme().authenticate(credentials, httpPut)); } catch (AuthenticationException e1) { e1.printStackTrace(); return; } } try { HttpResponse response = httpClient.execute(httpPut); int status = response.getStatusLine().getStatusCode(); // 201 means the file was created, 200 means it was stored but // already existed. if (status == 201 || status == 200) { // The file was uploaded, so we remove the ongoing notification, // remove it from the queue and that’s it. mNotificationManager.cancel(uri.toString(), 0); DavSyncOpenHelper helper = new DavSyncOpenHelper(this); helper.removeUriFromQueue(uri.toString()); return; } Log.d("davsyncs", "" + response.getStatusLine()); mBuilder.setContentText(filename + ": " + response.getStatusLine()); } catch (ClientProtocolException e) { e.printStackTrace(); mBuilder.setContentText(filename + ": " + e.getLocalizedMessage()); } catch (IOException e) { e.printStackTrace(); mBuilder.setContentText(filename + ": " + e.getLocalizedMessage()); } // XXX: It would be good to provide an option to try again. // (or try it again automatically?) // XXX: possibly we should re-queue the images in the database mBuilder.setContentTitle("Error uploading to WebDAV server"); mBuilder.setProgress(0, 0, false); mBuilder.setOngoing(false); mNotificationManager.notify(uri.toString(), 0, mBuilder.build()); } }
uploadservice: check if cursor == null in filenameFromUri
src/net/zekjur/davsync/UploadService.java
uploadservice: check if cursor == null in filenameFromUri
Java
bsd-3-clause
d222cbb7d982b8405391ca8e81c7aeffe0877503
0
iamedu/dari,iamedu/dari,iamedu/dari,iamedu/dari
package com.psddev.dari.db; import com.psddev.dari.util.ClassEnhancer; import com.psddev.dari.util.StringUtils; import com.psddev.dari.util.asm.Label; import com.psddev.dari.util.asm.MethodVisitor; import com.psddev.dari.util.asm.Opcodes; import com.psddev.dari.util.asm.Type; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class QueryCommentEnhancer extends ClassEnhancer { private static final String CLASS_INTERNAL_NAME; private static final String COMMENT_METHOD_NAME; private static final String COMMENT_METHOD_DESC; private static final List<FactoryMethod> FACTORY_METHODS; static { Class<?> queryClass = Query.class; CLASS_INTERNAL_NAME = Type.getInternalName(queryClass); Method commentMethod; try { commentMethod = queryClass.getMethod("comment", String.class); } catch (NoSuchMethodException error) { throw new IllegalStateException(error); } COMMENT_METHOD_NAME = commentMethod.getName(); COMMENT_METHOD_DESC = Type.getMethodDescriptor(commentMethod); FACTORY_METHODS = Arrays.stream(queryClass.getMethods()) .filter(method -> Modifier.isStatic(method.getModifiers()) && queryClass.isAssignableFrom(method.getReturnType())) .map(FactoryMethod::new) .collect(Collectors.toList()); } private String currentSource; @Override public void visitSource(String source, String debug) { super.visitSource(source, debug); currentSource = StringUtils.removeEnd(source, ".java"); } @Override public MethodVisitor visitMethod( int access, String name, String desc, String signature, String[] exceptions) { MethodVisitor visitor = super.visitMethod(access, name, desc, signature, exceptions); return new MethodVisitor(Opcodes.ASM5, visitor) { private int currentLine; @Override public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) { super.visitMethodInsn(opcode, owner, name, desc, itf); if (opcode == Opcodes.INVOKESTATIC && CLASS_INTERNAL_NAME.equals(owner) && FACTORY_METHODS.stream().anyMatch(method -> method.matches(name, desc))) { super.visitLdcInsn(currentSource + ":" + currentLine); super.visitMethodInsn(Opcodes.INVOKEVIRTUAL, CLASS_INTERNAL_NAME, COMMENT_METHOD_NAME, COMMENT_METHOD_DESC, false); } } @Override public void visitLineNumber(int line, Label start) { super.visitLineNumber(line, start); currentLine = line; } }; } private static class FactoryMethod { private final String name; private final String desc; public FactoryMethod(Method method) { this.name = method.getName(); this.desc = Type.getMethodDescriptor(method); } public String getName() { return name; } public String getDesc() { return desc; } public boolean matches(String name, String desc) { return this.name.equals(name) && this.desc.equals(desc); } } }
db/src/main/java/com/psddev/dari/db/QueryCommentEnhancer.java
package com.psddev.dari.db; import com.psddev.dari.util.ClassEnhancer; import com.psddev.dari.util.StringUtils; import com.psddev.dari.util.asm.Label; import com.psddev.dari.util.asm.MethodVisitor; import com.psddev.dari.util.asm.Opcodes; import com.psddev.dari.util.asm.Type; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class QueryCommentEnhancer extends ClassEnhancer { private static final String CLASS_INTERNAL_NAME; private static final String COMMENT_METHOD_NAME; private static final String COMMENT_METHOD_DESC; private static final List<FactoryMethod> FACTORY_METHODS; static { Class<?> queryClass = Query.class; CLASS_INTERNAL_NAME = Type.getInternalName(queryClass); Method commentMethod; try { commentMethod = queryClass.getMethod("comment", String.class); } catch (NoSuchMethodException error) { throw new IllegalStateException(error); } COMMENT_METHOD_NAME = commentMethod.getName(); COMMENT_METHOD_DESC = Type.getMethodDescriptor(commentMethod); FACTORY_METHODS = Arrays.stream(queryClass.getMethods()) .filter(method -> Modifier.isStatic(method.getModifiers()) && queryClass.isAssignableFrom(method.getReturnType())) .map(FactoryMethod::new) .collect(Collectors.toList()); } private String currentSource; @Override public void visitSource(String source, String debug) { currentSource = StringUtils.removeEnd(source, ".java"); } @Override public MethodVisitor visitMethod( int access, String name, String desc, String signature, String[] exceptions) { MethodVisitor visitor = super.visitMethod(access, name, desc, signature, exceptions); return new MethodVisitor(Opcodes.ASM5, visitor) { private int currentLine; @Override public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) { super.visitMethodInsn(opcode, owner, name, desc, itf); if (opcode == Opcodes.INVOKESTATIC && CLASS_INTERNAL_NAME.equals(owner) && FACTORY_METHODS.stream().anyMatch(method -> method.matches(name, desc))) { super.visitLdcInsn(currentSource + ":" + currentLine); super.visitMethodInsn(Opcodes.INVOKEVIRTUAL, CLASS_INTERNAL_NAME, COMMENT_METHOD_NAME, COMMENT_METHOD_DESC, false); } } @Override public void visitLineNumber(int line, Label start) { super.visitLineNumber(line, start); currentLine = line; } }; } private static class FactoryMethod { private final String name; private final String desc; public FactoryMethod(Method method) { this.name = method.getName(); this.desc = Type.getMethodDescriptor(method); } public String getName() { return name; } public String getDesc() { return desc; } public boolean matches(String name, String desc) { return this.name.equals(name) && this.desc.equals(desc); } } }
Fixes QueryCommentEnhancer to propagate the visitSource call correctly up the chain.
db/src/main/java/com/psddev/dari/db/QueryCommentEnhancer.java
Fixes QueryCommentEnhancer to propagate the visitSource call correctly up the chain.
Java
mit
039721c4872f954a021cb9635b7b0b3150764a98
0
InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service
package org.innovateuk.ifs.application.forms.yourprojectcosts.form; import java.math.BigDecimal; import java.util.LinkedHashMap; import java.util.Map; import java.util.Objects; import java.util.Optional; public class YourProjectCostsForm { private LabourForm labour; private OverheadForm overhead; private Map<String, MaterialRowForm> materialRows = new LinkedHashMap<>(); private Map<String, CapitalUsageRowForm> capitalUsageRows = new LinkedHashMap<>(); private Map<String, SubcontractingRowForm> subcontractingRows = new LinkedHashMap<>(); private Map<String, TravelRowForm> travelRows = new LinkedHashMap<>(); private Map<String, OtherCostRowForm> otherRows = new LinkedHashMap<>(); private Boolean eligibleAgreement; public OverheadForm getOverhead() { return overhead; } public void setOverhead(OverheadForm overhead) { this.overhead = overhead; } public Map<String, MaterialRowForm> getMaterialRows() { return materialRows; } public void setMaterialRows(Map<String, MaterialRowForm> materialRows) { this.materialRows = materialRows; } public Map<String, CapitalUsageRowForm> getCapitalUsageRows() { return capitalUsageRows; } public void setCapitalUsageRows(Map<String, CapitalUsageRowForm> capitalUsageRows) { this.capitalUsageRows = capitalUsageRows; } public Map<String, SubcontractingRowForm> getSubcontractingRows() { return subcontractingRows; } public void setSubcontractingRows(Map<String, SubcontractingRowForm> subcontractingRows) { this.subcontractingRows = subcontractingRows; } public Map<String, TravelRowForm> getTravelRows() { return travelRows; } public void setTravelRows(Map<String, TravelRowForm> travelRows) { this.travelRows = travelRows; } public Map<String, OtherCostRowForm> getOtherRows() { return otherRows; } public void setOtherRows(Map<String, OtherCostRowForm> otherRows) { this.otherRows = otherRows; } public Boolean getEligibleAgreement() { return eligibleAgreement; } public void setEligibleAgreement(Boolean eligibleAgreement) { this.eligibleAgreement = eligibleAgreement; } public LabourForm getLabour() { return labour; } public void setLabour(LabourForm labour) { this.labour = labour; } /* View methods. */ public BigDecimal getTotalLabourCosts() { return labour.getRows().values().stream().map(LabourRowForm::getTotal).filter(Objects::nonNull).reduce(BigDecimal::add).orElse(BigDecimal.ZERO); } public BigDecimal getTotalOverheadCosts() { switch (overhead.getRateType()) { case NONE: return BigDecimal.ZERO; case DEFAULT_PERCENTAGE: return getTotalLabourCosts().multiply(new BigDecimal("0.2")); case TOTAL: return Optional.ofNullable(getOverhead().getTotalSpreadsheet()).map(BigDecimal::valueOf).orElse(BigDecimal.ZERO); } return BigDecimal.ZERO; } public BigDecimal getTotalMaterialCosts() { return materialRows.values().stream().map(MaterialRowForm::getTotal).filter(Objects::nonNull).reduce(BigDecimal::add).orElse(BigDecimal.ZERO); } public BigDecimal getTotalCapitalUsageCosts() { return capitalUsageRows.values().stream().map(CapitalUsageRowForm::getTotal).filter(Objects::nonNull).reduce(BigDecimal::add).orElse(BigDecimal.ZERO); } public BigDecimal getTotalSubcontractingCosts() { return subcontractingRows.values().stream().map(SubcontractingRowForm::getTotal).filter(Objects::nonNull).reduce(BigDecimal::add).orElse(BigDecimal.ZERO); } public BigDecimal getTotalTravelCosts() { return travelRows.values().stream().map(TravelRowForm::getTotal).filter(Objects::nonNull).reduce(BigDecimal::add).orElse(BigDecimal.ZERO); } public BigDecimal getTotalOtherCosts() { return otherRows.values().stream().map(OtherCostRowForm::getTotal).filter(Objects::nonNull).reduce(BigDecimal::add).orElse(BigDecimal.ZERO); } public BigDecimal getOrganisationFinanceTotal() { return getTotalLabourCosts() .add(getTotalOverheadCosts()) .add(getTotalMaterialCosts()) .add(getTotalCapitalUsageCosts()) .add(getTotalSubcontractingCosts()) .add(getTotalTravelCosts()) .add(getTotalOtherCosts()); } }
ifs-web-service/ifs-application-commons/src/main/java/org/innovateuk/ifs/application/forms/yourprojectcosts/form/YourProjectCostsForm.java
package org.innovateuk.ifs.application.forms.yourprojectcosts.form; import java.math.BigDecimal; import java.util.LinkedHashMap; import java.util.Map; import java.util.Objects; public class YourProjectCostsForm { private LabourForm labour; private OverheadForm overhead; private Map<String, MaterialRowForm> materialRows = new LinkedHashMap<>(); private Map<String, CapitalUsageRowForm> capitalUsageRows = new LinkedHashMap<>(); private Map<String, SubcontractingRowForm> subcontractingRows = new LinkedHashMap<>(); private Map<String, TravelRowForm> travelRows = new LinkedHashMap<>(); private Map<String, OtherCostRowForm> otherRows = new LinkedHashMap<>(); private Boolean eligibleAgreement; public OverheadForm getOverhead() { return overhead; } public void setOverhead(OverheadForm overhead) { this.overhead = overhead; } public Map<String, MaterialRowForm> getMaterialRows() { return materialRows; } public void setMaterialRows(Map<String, MaterialRowForm> materialRows) { this.materialRows = materialRows; } public Map<String, CapitalUsageRowForm> getCapitalUsageRows() { return capitalUsageRows; } public void setCapitalUsageRows(Map<String, CapitalUsageRowForm> capitalUsageRows) { this.capitalUsageRows = capitalUsageRows; } public Map<String, SubcontractingRowForm> getSubcontractingRows() { return subcontractingRows; } public void setSubcontractingRows(Map<String, SubcontractingRowForm> subcontractingRows) { this.subcontractingRows = subcontractingRows; } public Map<String, TravelRowForm> getTravelRows() { return travelRows; } public void setTravelRows(Map<String, TravelRowForm> travelRows) { this.travelRows = travelRows; } public Map<String, OtherCostRowForm> getOtherRows() { return otherRows; } public void setOtherRows(Map<String, OtherCostRowForm> otherRows) { this.otherRows = otherRows; } public Boolean getEligibleAgreement() { return eligibleAgreement; } public void setEligibleAgreement(Boolean eligibleAgreement) { this.eligibleAgreement = eligibleAgreement; } public LabourForm getLabour() { return labour; } public void setLabour(LabourForm labour) { this.labour = labour; } /* View methods. */ public BigDecimal getTotalLabourCosts() { return labour.getRows().values().stream().map(LabourRowForm::getTotal).filter(Objects::nonNull).reduce(BigDecimal::add).orElse(BigDecimal.ZERO); } public BigDecimal getTotalOverheadCosts() { switch (overhead.getRateType()) { case NONE: return BigDecimal.ZERO; case DEFAULT_PERCENTAGE: return getTotalLabourCosts().multiply(new BigDecimal("0.2")); case TOTAL: return BigDecimal.valueOf(getOverhead().getTotalSpreadsheet()); } return BigDecimal.ZERO; } public BigDecimal getTotalMaterialCosts() { return materialRows.values().stream().map(MaterialRowForm::getTotal).filter(Objects::nonNull).reduce(BigDecimal::add).orElse(BigDecimal.ZERO); } public BigDecimal getTotalCapitalUsageCosts() { return capitalUsageRows.values().stream().map(CapitalUsageRowForm::getTotal).filter(Objects::nonNull).reduce(BigDecimal::add).orElse(BigDecimal.ZERO); } public BigDecimal getTotalSubcontractingCosts() { return subcontractingRows.values().stream().map(SubcontractingRowForm::getTotal).filter(Objects::nonNull).reduce(BigDecimal::add).orElse(BigDecimal.ZERO); } public BigDecimal getTotalTravelCosts() { return travelRows.values().stream().map(TravelRowForm::getTotal).filter(Objects::nonNull).reduce(BigDecimal::add).orElse(BigDecimal.ZERO); } public BigDecimal getTotalOtherCosts() { return otherRows.values().stream().map(OtherCostRowForm::getTotal).filter(Objects::nonNull).reduce(BigDecimal::add).orElse(BigDecimal.ZERO); } public BigDecimal getOrganisationFinanceTotal() { return getTotalLabourCosts() .add(getTotalOverheadCosts()) .add(getTotalMaterialCosts()) .add(getTotalCapitalUsageCosts()) .add(getTotalSubcontractingCosts()) .add(getTotalTravelCosts()) .add(getTotalOtherCosts()); } }
IFS-3486 fixing upload bug
ifs-web-service/ifs-application-commons/src/main/java/org/innovateuk/ifs/application/forms/yourprojectcosts/form/YourProjectCostsForm.java
IFS-3486 fixing upload bug
Java
mit
2c3dcd3cbf052637f62c100c85403e266911756a
0
alexycruz1/ED2_Proyecto1
package elcaro; import java.util.ArrayList; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.table.DefaultTableModel; public class ARLV { String Direccion; char manejo; ArrayList<String> borrados = new ArrayList(); public ARLV(String Direccion, char manejo) { this.Direccion = Direccion; this.manejo = manejo; } public ArrayList<String> getBorrados() { return borrados; } public void setBorrados(ArrayList<String> borrados) { this.borrados = borrados; } public ARLV() { } public String getDireccion() { return Direccion; } public void setDireccion(String Direccion) { this.Direccion = Direccion; } public char getManejo() { return manejo; } public void setManejo(char manejo) { this.manejo = manejo; } public int GetTamañoCampo(int indice) { int LongitudCampo = 0; if (manejo == 'D') {//Delimitador& File Archivo = null; Archivo = new File(Direccion); RandomAccessFile RAF = null; int PosicionInicial = GetPosInicial(); int ContadorCampo = 0; try { RAF = new RandomAccessFile(Archivo, "rw"); for (int i = PosicionInicial; i < RAF.length(); i++) { RAF.seek(i); if (ContadorCampo == indice) { char Revisar = (char) RAF.readByte(); if (Revisar != '&') { LongitudCampo++; } else { ContadorCampo++; } } } } catch (FileNotFoundException ex) { Logger.getLogger(ARLV.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ARLV.class.getName()).log(Level.SEVERE, null, ex); } } else if (manejo == 'K') {//KeyValue File Archivo = null; Archivo = new File(Direccion); RandomAccessFile RAF = null; int PosicionInicial = GetPosInicial(); int ContadorCampo = -1; try { RAF = new RandomAccessFile(Archivo, "rw"); for (int i = PosicionInicial; i < RAF.length(); i++) { RAF.seek(i); if (ContadorCampo == indice) { char Revisar = (char) RAF.readByte(); if (Revisar != '=') { LongitudCampo++; } else { ContadorCampo++; } } } } catch (FileNotFoundException ex) { Logger.getLogger(ARLV.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ARLV.class.getName()).log(Level.SEVERE, null, ex); } } else if (manejo == 'I') {//Indicador File Archivo = null; Archivo = new File(Direccion); RandomAccessFile RAF = null; int PosicionInicial = GetPosInicial(); int ContadorCampo = 0; String Temp = ""; try { RAF = new RandomAccessFile(Archivo, "rw"); for (int i = PosicionInicial; i < RAF.length(); i++) { if (ContadorCampo == indice) { for (int j = 0; j < 3; j++) { RAF.seek(i); char ConcatNumber = (char) RAF.readByte(); Temp += ConcatNumber; i++; } LongitudCampo = Integer.parseInt(Temp); } else { for (int j = 0; j < 3; j++) { RAF.seek(i); char ConcatNumber = (char) RAF.readByte(); Temp += ConcatNumber; i++; } i = i + Integer.parseInt(Temp); ContadorCampo++; Temp = ""; } } } catch (FileNotFoundException ex) { Logger.getLogger(ARLV.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ARLV.class.getName()).log(Level.SEVERE, null, ex); } } return LongitudCampo; } public int GetNumCampo() { File Archivo = null; Archivo = new File(Direccion); RandomAccessFile RAF = null; int NumeroCampos = 0; try { RAF = new RandomAccessFile(Archivo, "rw"); RAF.seek(0); char Temp = (char) RAF.readByte(); String Temp2 = ""; Temp2 += Temp; NumeroCampos = Integer.parseInt(Temp2); } catch (FileNotFoundException ex) { Logger.getLogger(ARLV.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ARLV.class.getName()).log(Level.SEVERE, null, ex); } return NumeroCampos; } public int GetPosInicial() { File Archivo = null; Archivo = new File(Direccion); RandomAccessFile RAF = null; int PosicionInicial = 0; try { RAF = new RandomAccessFile(Archivo, "rw"); for (int i = 0; i < RAF.length(); i++) { RAF.seek(i); char Revisar = (char) RAF.readByte(); if (Revisar == ':') { PosicionInicial = i + 1; } } } catch (FileNotFoundException ex) { Logger.getLogger(ARLV.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ARLV.class.getName()).log(Level.SEVERE, null, ex); } return PosicionInicial; } public String GetNombreColumna(int indice) { File Archivo = null; Archivo = new File(Direccion); RandomAccessFile RAF = null; int PosicionInicial = 0; int NumeroCampo = 0; int ContadorDelimitador = 0; String NombreColumna = ""; try { RAF = new RandomAccessFile(Archivo, "rw"); for (int i = 0; i < RAF.length(); i++) { RAF.seek(i); char Revisar = (char) RAF.readByte(); if (Revisar == ':') { ContadorDelimitador++; } if (ContadorDelimitador == 2) { PosicionInicial = i + 1; } } ContadorDelimitador = 0; for (int i = PosicionInicial - 1; i < RAF.length(); i++) { RAF.seek(i); char CharCampo = (char) RAF.readByte(); if (CharCampo != ':') { if (ContadorDelimitador == indice) { NombreColumna += CharCampo; } } else { ContadorDelimitador++; } } } catch (FileNotFoundException ex) { Logger.getLogger(ARLV.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ARLV.class.getName()).log(Level.SEVERE, null, ex); } return NombreColumna; } public ArrayList<String> GetNombresCampos(int Registro) { ArrayList<String> Nombres = new ArrayList(); if (manejo == 'D') {//Delimitador& File Archivo = null; Archivo = new File(Direccion); RandomAccessFile RAF = null; int PosicionInicial = GetPosInicial(); int ContadorRegistro = 0; int ContadorCampo = 0; String Campo = ""; try { RAF = new RandomAccessFile(Archivo, "rw"); for (int i = PosicionInicial; i < RAF.length(); i++) { RAF.seek(i); if (ContadorRegistro == Registro) { char Revisar = (char) RAF.readByte(); if (Revisar != '&') { } else { ContadorCampo++; } } } } catch (FileNotFoundException ex) { Logger.getLogger(ARLV.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ARLV.class.getName()).log(Level.SEVERE, null, ex); } } else if (manejo == 'K') {//KeyValue File Archivo = null; Archivo = new File(Direccion); RandomAccessFile RAF = null; int PosicionInicial = GetPosInicial(); int ContadorCampo = -1; try { RAF = new RandomAccessFile(Archivo, "rw"); for (int i = PosicionInicial; i < RAF.length(); i++) { RAF.seek(i); if (ContadorCampo == Registro) { char Revisar = (char) RAF.readByte(); if (Revisar != '=') { LongitudCampo++; } else { ContadorCampo++; } } } } catch (FileNotFoundException ex) { Logger.getLogger(ARLV.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ARLV.class.getName()).log(Level.SEVERE, null, ex); } } else if (manejo == 'I') {//Indicador File Archivo = null; Archivo = new File(Direccion); RandomAccessFile RAF = null; int PosicionInicial = GetPosInicial(); int ContadorCampo = 0; String Temp = ""; try { RAF = new RandomAccessFile(Archivo, "rw"); for (int i = PosicionInicial; i < RAF.length(); i++) { if (ContadorCampo == Registro) { for (int j = 0; j < 3; j++) { RAF.seek(i); char ConcatNumber = (char) RAF.readByte(); Temp += ConcatNumber; i++; } LongitudCampo = Integer.parseInt(Temp); } else { for (int j = 0; j < 3; j++) { RAF.seek(i); char ConcatNumber = (char) RAF.readByte(); Temp += ConcatNumber; i++; } i = i + Integer.parseInt(Temp); ContadorCampo++; Temp = ""; } } } catch (FileNotFoundException ex) { Logger.getLogger(ARLV.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ARLV.class.getName()).log(Level.SEVERE, null, ex); } } return Nombres; } public void CargarManejo() { File Archivo = null; Archivo = new File(Direccion); RandomAccessFile RAF = null; int ContadorDelimitador = 0; char Manejo = 'D'; try { RAF = new RandomAccessFile(Archivo, "rw"); for (int i = 0; i < RAF.length(); i++) { RAF.seek(i); char Revisar = (char) RAF.readByte(); if (ContadorDelimitador == 1) { i++; RAF.seek(i); Manejo = (char) RAF.readByte(); } if (Revisar == ':') { ContadorDelimitador++; } } } catch (FileNotFoundException ex) { Logger.getLogger(ARLV.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ARLV.class.getName()).log(Level.SEVERE, null, ex); } this.setManejo(Manejo); } public boolean IsVariable(File Archivo) { boolean IsVariable = true; Archivo = null; Archivo = new File(Direccion); RandomAccessFile RAF = null; try { RAF = new RandomAccessFile(Archivo, "rw"); for (int i = 0; i < RAF.length(); i++) { RAF.seek(i); char Revisar = (char) RAF.readByte(); if (Revisar == ';') { IsVariable = false; } } } catch (FileNotFoundException ex) { Logger.getLogger(ARLF.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ARLF.class.getName()).log(Level.SEVERE, null, ex); } return IsVariable; } public DefaultTableModel CargarArchivoVariable(String DireccionArchivo, String DireccionPila, DefaultTableModel Modelo) { return Modelo; } public void Agregar(String Registro, long Lenght) { if (manejo == 'D') { File Archivo = null; Archivo = new File(Direccion); RandomAccessFile RAF = null; try { RAF = new RandomAccessFile(Archivo, "rw"); RAF.seek(Lenght); RAF.writeBytes(Registro + "&"); } catch (FileNotFoundException ex) { Logger.getLogger(ElCaro.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ElCaro.class.getName()).log(Level.SEVERE, null, ex); } } else if (manejo == 'K') { } else if (manejo == 'I') { } } }
ElCaro/src/elcaro/ARLV.java
package elcaro; import java.util.ArrayList; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.table.DefaultTableModel; public class ARLV { String Direccion; char manejo; ArrayList<String> borrados = new ArrayList(); public ARLV(String Direccion, char manejo) { this.Direccion = Direccion; this.manejo = manejo; } public ArrayList<String> getBorrados() { return borrados; } public void setBorrados(ArrayList<String> borrados) { this.borrados = borrados; } public ARLV() { } public String getDireccion() { return Direccion; } public void setDireccion(String Direccion) { this.Direccion = Direccion; } public char getManejo() { return manejo; } public void setManejo(char manejo) { this.manejo = manejo; } public int GetTamañoCampo(int indice) { int LongitudCampo = 0; if (manejo == 'D') {//Delimitador& File Archivo = null; Archivo = new File(Direccion); RandomAccessFile RAF = null; int PosicionInicial = GetPosInicial(); int ContadorCampo = 0; try { RAF = new RandomAccessFile(Archivo, "rw"); for (int i = PosicionInicial; i < RAF.length(); i++) { RAF.seek(i); if (ContadorCampo == indice) { char Revisar = (char) RAF.readByte(); if (Revisar != '&') { LongitudCampo++; } else { ContadorCampo++; } } } } catch (FileNotFoundException ex) { Logger.getLogger(ARLV.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ARLV.class.getName()).log(Level.SEVERE, null, ex); } } else if (manejo == 'K') {//KeyValue File Archivo = null; Archivo = new File(Direccion); RandomAccessFile RAF = null; int PosicionInicial = GetPosInicial(); int ContadorCampo = -1; try { RAF = new RandomAccessFile(Archivo, "rw"); for (int i = PosicionInicial; i < RAF.length(); i++) { RAF.seek(i); if (ContadorCampo == indice) { char Revisar = (char) RAF.readByte(); if (Revisar != '=') { LongitudCampo++; } else { ContadorCampo++; } } } } catch (FileNotFoundException ex) { Logger.getLogger(ARLV.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ARLV.class.getName()).log(Level.SEVERE, null, ex); } } else if (manejo == 'I') {//Indicador File Archivo = null; Archivo = new File(Direccion); RandomAccessFile RAF = null; int PosicionInicial = GetPosInicial(); int ContadorCampo = 0; String Temp = ""; try { RAF = new RandomAccessFile(Archivo, "rw"); for (int i = PosicionInicial; i < RAF.length(); i++) { if (ContadorCampo == indice) { for (int j = 0; j < 3; j++) { RAF.seek(i); char ConcatNumber = (char) RAF.readByte(); Temp += ConcatNumber; i++; } LongitudCampo = Integer.parseInt(Temp); } else { for (int j = 0; j < 3; j++) { RAF.seek(i); char ConcatNumber = (char) RAF.readByte(); Temp += ConcatNumber; i++; } i = i + Integer.parseInt(Temp); ContadorCampo++; Temp = ""; } } } catch (FileNotFoundException ex) { Logger.getLogger(ARLV.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ARLV.class.getName()).log(Level.SEVERE, null, ex); } } return LongitudCampo; } public int GetNumCampo() { File Archivo = null; Archivo = new File(Direccion); RandomAccessFile RAF = null; int NumeroCampos = 0; try { RAF = new RandomAccessFile(Archivo, "rw"); RAF.seek(0); char Temp = (char) RAF.readByte(); String Temp2 = ""; Temp2 += Temp; NumeroCampos = Integer.parseInt(Temp2); } catch (FileNotFoundException ex) { Logger.getLogger(ARLV.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ARLV.class.getName()).log(Level.SEVERE, null, ex); } return NumeroCampos; } public int GetPosInicial() { File Archivo = null; Archivo = new File(Direccion); RandomAccessFile RAF = null; int PosicionInicial = 0; try { RAF = new RandomAccessFile(Archivo, "rw"); for (int i = 0; i < RAF.length(); i++) { RAF.seek(i); char Revisar = (char) RAF.readByte(); if (Revisar == ':') { PosicionInicial = i + 1; } } } catch (FileNotFoundException ex) { Logger.getLogger(ARLV.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ARLV.class.getName()).log(Level.SEVERE, null, ex); } return PosicionInicial; } public String GetNombreColumna(int indice) { File Archivo = null; Archivo = new File(Direccion); RandomAccessFile RAF = null; int PosicionInicial = 0; int NumeroCampo = 0; int ContadorDelimitador = 0; String NombreColumna = ""; try { RAF = new RandomAccessFile(Archivo, "rw"); for (int i = 0; i < RAF.length(); i++) { RAF.seek(i); char Revisar = (char) RAF.readByte(); if (Revisar == ':') { ContadorDelimitador++; } if (ContadorDelimitador == 2) { PosicionInicial = i + 1; } } ContadorDelimitador = 0; for (int i = PosicionInicial - 1; i < RAF.length(); i++) { RAF.seek(i); char CharCampo = (char) RAF.readByte(); if (CharCampo != ':') { if (ContadorDelimitador == indice) { NombreColumna += CharCampo; } } else { ContadorDelimitador++; } } } catch (FileNotFoundException ex) { Logger.getLogger(ARLV.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ARLV.class.getName()).log(Level.SEVERE, null, ex); } return NombreColumna; } public ArrayList<String> GetNombresCampos(int Registro) { ArrayList<String> Nombres = new ArrayList(); int LongitudCampo = 0; if (manejo == 'D') {//Delimitador& File Archivo = null; Archivo = new File(Direccion); RandomAccessFile RAF = null; int PosicionInicial = GetPosInicial(); int ContadorCampo = 0; try { RAF = new RandomAccessFile(Archivo, "rw"); for (int i = PosicionInicial; i < RAF.length(); i++) { RAF.seek(i); if (ContadorCampo == Registro) { char Revisar = (char) RAF.readByte(); if (Revisar != '&') { LongitudCampo++; } else { ContadorCampo++; } } } } catch (FileNotFoundException ex) { Logger.getLogger(ARLV.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ARLV.class.getName()).log(Level.SEVERE, null, ex); } } else if (manejo == 'K') {//KeyValue File Archivo = null; Archivo = new File(Direccion); RandomAccessFile RAF = null; int PosicionInicial = GetPosInicial(); int ContadorCampo = -1; try { RAF = new RandomAccessFile(Archivo, "rw"); for (int i = PosicionInicial; i < RAF.length(); i++) { RAF.seek(i); if (ContadorCampo == Registro) { char Revisar = (char) RAF.readByte(); if (Revisar != '=') { LongitudCampo++; } else { ContadorCampo++; } } } } catch (FileNotFoundException ex) { Logger.getLogger(ARLV.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ARLV.class.getName()).log(Level.SEVERE, null, ex); } } else if (manejo == 'I') {//Indicador File Archivo = null; Archivo = new File(Direccion); RandomAccessFile RAF = null; int PosicionInicial = GetPosInicial(); int ContadorCampo = 0; String Temp = ""; try { RAF = new RandomAccessFile(Archivo, "rw"); for (int i = PosicionInicial; i < RAF.length(); i++) { if (ContadorCampo == Registro) { for (int j = 0; j < 3; j++) { RAF.seek(i); char ConcatNumber = (char) RAF.readByte(); Temp += ConcatNumber; i++; } LongitudCampo = Integer.parseInt(Temp); } else { for (int j = 0; j < 3; j++) { RAF.seek(i); char ConcatNumber = (char) RAF.readByte(); Temp += ConcatNumber; i++; } i = i + Integer.parseInt(Temp); ContadorCampo++; Temp = ""; } } } catch (FileNotFoundException ex) { Logger.getLogger(ARLV.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ARLV.class.getName()).log(Level.SEVERE, null, ex); } } return Nombres; } public void CargarManejo() { File Archivo = null; Archivo = new File(Direccion); RandomAccessFile RAF = null; int ContadorDelimitador = 0; char Manejo = 'D'; try { RAF = new RandomAccessFile(Archivo, "rw"); for (int i = 0; i < RAF.length(); i++) { RAF.seek(i); char Revisar = (char) RAF.readByte(); if (ContadorDelimitador == 1) { i++; RAF.seek(i); Manejo = (char) RAF.readByte(); } if (Revisar == ':') { ContadorDelimitador++; } } } catch (FileNotFoundException ex) { Logger.getLogger(ARLV.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ARLV.class.getName()).log(Level.SEVERE, null, ex); } this.setManejo(Manejo); } public boolean IsVariable(File Archivo) { boolean IsVariable = true; Archivo = null; Archivo = new File(Direccion); RandomAccessFile RAF = null; try { RAF = new RandomAccessFile(Archivo, "rw"); for (int i = 0; i < RAF.length(); i++) { RAF.seek(i); char Revisar = (char) RAF.readByte(); if (Revisar == ';') { IsVariable = false; } } } catch (FileNotFoundException ex) { Logger.getLogger(ARLF.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ARLF.class.getName()).log(Level.SEVERE, null, ex); } return IsVariable; } public DefaultTableModel CargarArchivoVariable(String DireccionArchivo, String DireccionPila, DefaultTableModel Modelo) { return Modelo; } public void Agregar(String Registro, long Lenght) { if (manejo == 'D') { File Archivo = null; Archivo = new File(Direccion); RandomAccessFile RAF = null; try { RAF = new RandomAccessFile(Archivo, "rw"); RAF.seek(Lenght); RAF.writeBytes(Registro + "&"); } catch (FileNotFoundException ex) { Logger.getLogger(ElCaro.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ElCaro.class.getName()).log(Level.SEVERE, null, ex); } } else if (manejo == 'K') { } else if (manejo == 'I') { } } }
cambios
ElCaro/src/elcaro/ARLV.java
cambios
Java
mit
fce48a71665965aaa384a9ffc3e2bd5f85b36a7d
0
MAXDeliveryNG/slideview
package ng.max.slideview; import android.content.Context; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.GradientDrawable; import android.graphics.drawable.ShapeDrawable; import android.util.TypedValue; /** * @author Kizito Nwose */ class Util { static void setDrawableColor(Drawable drawable, int color) { drawable.mutate(); if (drawable instanceof ShapeDrawable) { ShapeDrawable shapeDrawable = (ShapeDrawable) drawable; shapeDrawable.getPaint().setColor(color); } else if (drawable instanceof GradientDrawable) { GradientDrawable gradientDrawable = (GradientDrawable) drawable; gradientDrawable.setColor(color); } else if (drawable instanceof ColorDrawable) { ColorDrawable colorDrawable = (ColorDrawable) drawable; colorDrawable.setColor(color); } } static void setDrawableStroke(Drawable drawable, int color) { if (drawable instanceof GradientDrawable) { GradientDrawable gradientDrawable = (GradientDrawable) drawable; gradientDrawable.mutate(); gradientDrawable.setStroke(4, color); } } static float spToPx(int sp, Context context) { return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, context.getResources().getDisplayMetrics()); } }
slideview/src/main/java/ng/max/slideview/Util.java
package ng.max.slideview; import android.content.Context; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.GradientDrawable; import android.graphics.drawable.ShapeDrawable; import android.util.TypedValue; /** * @author Kizito Nwose */ public class Util { public static void setDrawableColor(Drawable drawable, int color) { drawable.mutate(); if (drawable instanceof ShapeDrawable) { ShapeDrawable shapeDrawable = (ShapeDrawable) drawable; shapeDrawable.getPaint().setColor(color); } else if (drawable instanceof GradientDrawable) { GradientDrawable gradientDrawable = (GradientDrawable) drawable; gradientDrawable.setColor(color); } else if (drawable instanceof ColorDrawable) { ColorDrawable colorDrawable = (ColorDrawable) drawable; colorDrawable.setColor(color); } } public static void setDrawableStroke(Drawable drawable, int color) { if (drawable instanceof GradientDrawable) { GradientDrawable gradientDrawable = (GradientDrawable) drawable; gradientDrawable.mutate(); gradientDrawable.setStroke(4, color); } } public static float spToPx(int sp, Context context) { return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, context.getResources().getDisplayMetrics()); } }
Change visibility of Util class.
slideview/src/main/java/ng/max/slideview/Util.java
Change visibility of Util class.
Java
mit
c89c47304e99668f7e95948affa6f1a6ffed206f
0
fvasquezjatar/fermat-unused,fvasquezjatar/fermat-unused
package com.bitdubai.fermat_api.layer.pip_actor.developer; import com.bitdubai.fermat_api.layer.osa_android.logger_system.LogLevel; import com.bitdubai.fermat_api.layer.all_definition.enums.Addons; import com.bitdubai.fermat_api.layer.all_definition.enums.Plugins; import java.util.List; /** * Created by ciencias on 6/25/15. */ public interface LogTool { public List<Plugins> getAvailablePluginList (); public List<Addons> getAvailableAddonList (); public LogLevel getLogLevel(Plugins plugin); public LogLevel getLogLevel(Addons addon); public void setLogLevel(Plugins plugin, LogLevel newLogLevel); public void setLogLevel(Addons addon, LogLevel newLogLevel); public List<ClassHierarchy> getClassesHierarchy(Plugins plugin); }
fermat-api/src/main/java/com/bitdubai/fermat_api/layer/pip_actor/developer/LogTool.java
package com.bitdubai.fermat_api.layer.pip_actor.developer; import com.bitdubai.fermat_api.layer.osa_android.logger_system.LogLevel; import com.bitdubai.fermat_api.layer.all_definition.enums.Addons; import com.bitdubai.fermat_api.layer.all_definition.enums.Plugins; import java.util.List; /** * Created by ciencias on 6/25/15. */ public interface LogTool { public List<Plugins> getAvailablePluginList (); public List<Addons> getAvailableAddonList (); public LogLevel getLogLevel(Plugins plugin); public LogLevel getLogLevel(Addons addon); public void setLogLevel(Plugins plugin, LogLevel newLogLevel); public void setLogLevel(Addons addon, LogLevel newLogLevel); }
Added getClassesHierarchy method in Log Manager interface
fermat-api/src/main/java/com/bitdubai/fermat_api/layer/pip_actor/developer/LogTool.java
Added getClassesHierarchy method in Log Manager interface
Java
mit
d09a0d7555fd656e91a73709c0b6e81031067a0a
0
thiagotoledo/factory-method
package pintura; /** * * Interface cor * Do pacote de exemplo Pintura que demonstra o * Padrão de Projeto GOF - Factory Method * * @author Thiago Toledo <[email protected]> * */ /** * * @author Thiago */ public interface Cor { void colorir(); }
pintura/Cor.java
package pintura; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author Thiago */ public interface Cor { void colorir(); }
Acertado o comentário do arquivo
pintura/Cor.java
Acertado o comentário do arquivo
Java
mit
fdd57f35b55e73501df18ba0e5a58ac7aa10349d
0
gye-tgm/schat
package com.activities; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.view.*; import android.widget.*; import com.data.AddContact; import com.data.AndroidSQLManager; import com.data.ApplicationUser; import com.security.PRNGFixes; import com.services.MessageService; import data.User; import networking.SChatServer; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; /** * The main activity of the S/Chat-Application. It displays and manages the list of all available contacts. * * @author Elias Frantar * @version 15.12.2013 */ public class Activity_ContactList extends Activity implements AddContact { private ListView contactList; // the GUI element private ArrayList<String> contacts = new ArrayList<>(); // the stored contacts private ArrayAdapter<String> contactsAdapter; // to automatically update the ListView with onDataSetChanged private Intent start_chat; private Context context; private Handler handler; private Intent service; private AndroidSQLManager dbManager; private ApplicationUser me; /** * Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { PRNGFixes.apply(); // apply all PRG security fixes handler = new Handler(); super.onCreate(savedInstanceState); setContentView(R.layout.layout_contactlist); context = this; service = new Intent(getApplicationContext(), MessageService.class); startService(service); /* make all GUI-elements available */ contactList = (ListView) findViewById(R.id.view_contactlist); registerForContextMenu(contactList); // register all list items for the context menu dbManager = new AndroidSQLManager(); dbManager.connect(this); try { me = ApplicationUser.getInstance(); me.initialize(this); me.setActivity_contactList(this); } catch (IOException e) { e.printStackTrace(); } contacts = new ArrayList<String>(); contactsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, contacts); // simple_List_item_1 is the android default contactList.setAdapter(contactsAdapter); // set the data of the list contactList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { dbManager.disconnect(); start_chat = new Intent(context, Activity_Chat.class); User tmp = new User(contacts.get(arg2)); start_chat.putExtra("notyou", tmp); startActivity(start_chat); } }); dbManager = new AndroidSQLManager(); dbManager.connect(); loadContacts(); // load all contacts into the list } /** * Handels the ContextMenu actions. */ @Override public boolean onContextItemSelected(MenuItem item) { AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); // the item whose context menu was called switch (item.getItemId()) { case R.id.option_deleteContact: String username = contacts.get(info.position); dbManager.removeUser(username); dbManager.deleteChat(username); deleteContact(info.position); // delete the selected contact return true; case R.id.option_editContact: // edit the selected contact /* todo: implement contact editing */ return true; default: return super.onContextItemSelected(item); } } /** * Creates the OptionsMenu of this Activity */ @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.menu_contactlist, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_addContact: add(); return true; default: return super.onOptionsItemSelected(item); } } /** * Deletes the contact at given index. * * @param contactIndex the index of the contact in the list */ private void deleteContact(int contactIndex) { contacts.remove(contactIndex); contactsAdapter.notifyDataSetChanged(); } /** * Adds a contact to the List */ public void add() { final EditText txt = new EditText(this); new AlertDialog.Builder(this) .setTitle("Add Contact") .setView(txt) .setPositiveButton("Add", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { @SuppressWarnings("unchecked") String newUser = txt.getText().toString(); if (!newUser.equals("")) { if (!dbManager.userExists(newUser)) { me.requestPublicKey(newUser); } else { Toast.makeText(context, "Contact already exists", Toast.LENGTH_SHORT).show(); } } } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // Do nothing. (Closes Dialog) } }).show(); } /** * Loads all saved contacts into the contact-menu-list. */ private void loadContacts() { ArrayList<User> users = new ArrayList<>(); users = dbManager.loadUsers(); for (User u : users) if (!u.getId().equals(SChatServer.SERVER_ID)) contacts.add(u.getId()); } /** * Updates the GUI with newly loaded Content. * Uses a Handler and a Runnable to be allowed to do so. */ public void addContact(final String name) { handler.post(new Runnable() { public void run() { contacts.add(name); Collections.sort(contacts); contactsAdapter.notifyDataSetChanged(); } }); } @Override public void onDestroy() { dbManager.disconnect(); stopService(service); super.onDestroy(); } /** * Creates the ContextMenu of an individual List item */ @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); /* set the name of the selected item as the header title */ AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo; menu.setHeaderTitle(contacts.get(info.position)); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_contact, menu); } }
androidapp/src/com/activities/Activity_ContactList.java
package com.activities; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.view.*; import android.widget.*; import com.data.AddContact; import com.data.AndroidSQLManager; import com.data.ApplicationUser; import com.security.PRNGFixes; import com.services.MessageService; import data.User; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; /** * The main activity of the S/Chat-Application. It displays and manages the list of all available contacts. * * @author Elias Frantar * @version 15.12.2013 */ public class Activity_ContactList extends Activity implements AddContact { private ListView contactList; // the GUI element private ArrayList<String> contacts = new ArrayList<>(); // the stored contacts private ArrayAdapter<String> contactsAdapter; // to automatically update the ListView with onDataSetChanged private Intent start_chat; private Context context; private Handler handler; private Intent service; private AndroidSQLManager dbManager; private ApplicationUser me; /** * Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { PRNGFixes.apply(); // apply all PRG security fixes handler = new Handler(); super.onCreate(savedInstanceState); setContentView(R.layout.layout_contactlist); context = this; service = new Intent(getApplicationContext(), MessageService.class); startService(service); /* make all GUI-elements available */ contactList = (ListView) findViewById(R.id.view_contactlist); registerForContextMenu(contactList); // register all list items for the context menu dbManager = new AndroidSQLManager(); dbManager.connect(this); try { me = ApplicationUser.getInstance(); me.initialize(this); me.setActivity_contactList(this); } catch (IOException e) { e.printStackTrace(); } contacts = new ArrayList<String>(); contactsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, contacts); // simple_List_item_1 is the android default contactList.setAdapter(contactsAdapter); // set the data of the list contactList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { dbManager.disconnect(); start_chat = new Intent(context, Activity_Chat.class); User tmp = new User(contacts.get(arg2)); start_chat.putExtra("notyou", tmp); startActivity(start_chat); } }); dbManager = new AndroidSQLManager(); dbManager.connect(); loadContacts(); // load all contacts into the list } /** * Handels the ContextMenu actions. */ @Override public boolean onContextItemSelected(MenuItem item) { AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); // the item whose context menu was called switch (item.getItemId()) { case R.id.option_deleteContact: String username = contacts.get(info.position); dbManager.removeUser(username); dbManager.deleteChat(username); deleteContact(info.position); // delete the selected contact return true; case R.id.option_editContact: // edit the selected contact /* todo: implement contact editing */ return true; default: return super.onContextItemSelected(item); } } /** * Creates the OptionsMenu of this Activity */ @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.menu_contactlist, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_addContact: add(); return true; default: return super.onOptionsItemSelected(item); } } /** * Deletes the contact at given index. * * @param contactIndex the index of the contact in the list */ private void deleteContact(int contactIndex) { contacts.remove(contactIndex); contactsAdapter.notifyDataSetChanged(); } /** * Adds a contact to the List */ public void add() { final EditText txt = new EditText(this); new AlertDialog.Builder(this) .setTitle("Add Contact") .setView(txt) .setPositiveButton("Add", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { @SuppressWarnings("unchecked") String newUser = txt.getText().toString(); if (!newUser.equals("")) { if (!dbManager.userExists(newUser)) { me.requestPublicKey(newUser); } else { Toast.makeText(context, "Contact already exists", Toast.LENGTH_SHORT).show(); } } } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // Do nothing. (Closes Dialog) } }).show(); } /** * Loads all saved contacts into the contact-menu-list. */ private void loadContacts() { ArrayList<User> users = new ArrayList<>(); users = dbManager.loadUsers(); for (User u : users) contacts.add(u.getId()); } /** * Updates the GUI with newly loaded Content. * Uses a Handler and a Runnable to be allowed to do so. */ public void addContact(final String name) { handler.post(new Runnable() { public void run() { contacts.add(name); Collections.sort(contacts); contactsAdapter.notifyDataSetChanged(); } }); } @Override public void onDestroy() { dbManager.disconnect(); stopService(service); super.onDestroy(); } /** * Creates the ContextMenu of an individual List item */ @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); /* set the name of the selected item as the header title */ AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo; menu.setHeaderTitle(contacts.get(info.position)); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_contact, menu); } }
server not longer shown as user
androidapp/src/com/activities/Activity_ContactList.java
server not longer shown as user
Java
mit
586e4d6c81da192da057fcdc70a582fd1b4b2d17
0
ZorgeR/Noizer
package com.zlab.noizer.app; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.*; import java.util.List; public class ListViewCustomAdaptor extends ArrayAdapter<ListViewItem> { private Context c; private int id; private List<ListViewItem> items; public ListViewCustomAdaptor(Context context, int resource, List<ListViewItem> objects) { super(context, resource, objects); c = context; id = resource; items = objects; } @Override public View getView(final int position, View view, final ViewGroup parent) { LayoutInflater vi = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View v = vi.inflate(id, parent, false); final ListViewItem o = items.get(position); if (o != null) { final LinearLayout textLayout = (LinearLayout) v.findViewById(R.id.textLayout); final ImageView Image = (ImageView) v.findViewById(R.id.imageView); Image.setImageResource(o.getImageResID()); final TextView Title = (TextView) v.findViewById(R.id.textViewTitle); Title.setText(o.getTitle()); final TextView Description = (TextView) v.findViewById(R.id.textViewDescription); Description.setText(o.getDescription()); final SeekBar volumeBar = (SeekBar) v.findViewById(R.id.VolumeSeekBar); volumeBar.setProgress(o.getVolume()); final ToggleButton OnOff = (ToggleButton) v.findViewById(R.id.toggleButton); OnOff.setText(R.string.off); if(o.getIsPlaying()){ volumeBar.setVisibility(View.VISIBLE); textLayout.setVisibility(View.GONE); OnOff.setText(R.string.on); OnOff.setChecked(true); } OnOff.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(OnOff.isChecked()){ volumeBar.setVisibility(View.VISIBLE); textLayout.setVisibility(View.GONE); OnOff.setText(R.string.on); o.startPlaying(); } else { volumeBar.setVisibility(View.GONE); textLayout.setVisibility(View.VISIBLE); OnOff.setText(R.string.off); o.stopPlaying(); } } }); volumeBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { o.setVolume(progress); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); } return v; } }
app/src/main/java/com/zlab/noizer/app/ListViewCustomAdaptor.java
package com.zlab.noizer.app; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.*; import java.util.List; public class ListViewCustomAdaptor extends ArrayAdapter<ListViewItem> { private Context c; private int id; private List<ListViewItem> items; public ListViewCustomAdaptor(Context context, int resource, List<ListViewItem> objects) { super(context, resource, objects); c = context; id = resource; items = objects; } @Override public View getView(final int position, View view, final ViewGroup parent) { LayoutInflater vi = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View v = vi.inflate(id, parent, false); final ListViewItem o = items.get(position); if (o != null) { final LinearLayout textLayout = (LinearLayout) v.findViewById(R.id.textLayout); final ImageView Image = (ImageView) v.findViewById(R.id.imageView); Image.setImageResource(o.getImageResID()); final TextView Title = (TextView) v.findViewById(R.id.textViewTitle); Title.setText(o.getTitle()); final TextView Description = (TextView) v.findViewById(R.id.textViewDescription); Description.setText(o.getDescription()); final SeekBar volumeBar = (SeekBar) v.findViewById(R.id.VolumeSeekBar); volumeBar.setProgress(o.getVolume()); final ToggleButton OnOff = (ToggleButton) v.findViewById(R.id.toggleButton); OnOff.setText(R.string.off); if(o.getIsPlaying()){ volumeBar.setVisibility(View.VISIBLE); textLayout.setVisibility(View.GONE); OnOff.setText(R.string.on); OnOff.setChecked(true); } OnOff.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(OnOff.isChecked()){ volumeBar.setVisibility(View.VISIBLE); textLayout.setVisibility(View.GONE); OnOff.setText(R.string.on); o.startPlaying(); } else { volumeBar.setVisibility(View.GONE); textLayout.setVisibility(View.VISIBLE); OnOff.setText(R.string.off); o.stopPlaying(); } } }); volumeBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { o.setVolume(progress); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); } return v; } }
r120 - Резил в Google Play
app/src/main/java/com/zlab/noizer/app/ListViewCustomAdaptor.java
r120 - Резил в Google Play
Java
mit
2a94ada6b7257d8a51715b3a8260728d0c5915aa
0
open-keychain/spongycastle,isghe/bc-java,sergeypayu/bc-java,Skywalker-11/spongycastle,bcgit/bc-java,onessimofalconi/bc-java,onessimofalconi/bc-java,lesstif/spongycastle,open-keychain/spongycastle,sonork/spongycastle,onessimofalconi/bc-java,sergeypayu/bc-java,Skywalker-11/spongycastle,open-keychain/spongycastle,savichris/spongycastle,lesstif/spongycastle,bcgit/bc-java,isghe/bc-java,FAU-Inf2/spongycastle,lesstif/spongycastle,bcgit/bc-java,sonork/spongycastle,savichris/spongycastle,sergeypayu/bc-java,sonork/spongycastle,FAU-Inf2/spongycastle,savichris/spongycastle,Skywalker-11/spongycastle,FAU-Inf2/spongycastle,isghe/bc-java
package org.bouncycastle.cms.test; import java.io.ByteArrayInputStream; import java.io.IOException; import java.security.KeyFactory; import java.security.KeyPair; import java.security.MessageDigest; import java.security.Security; import java.security.Signature; import java.security.cert.X509CRL; import java.security.cert.X509Certificate; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.DEROctetString; import org.bouncycastle.asn1.DERSet; import org.bouncycastle.asn1.cms.Attribute; import org.bouncycastle.asn1.cms.AttributeTable; import org.bouncycastle.asn1.cms.CMSAttributes; import org.bouncycastle.asn1.cms.CMSObjectIdentifiers; import org.bouncycastle.asn1.cms.ContentInfo; import org.bouncycastle.asn1.ocsp.OCSPResponse; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.cert.X509AttributeCertificateHolder; import org.bouncycastle.cert.X509CertificateHolder; import org.bouncycastle.cert.jcajce.JcaCRLStore; import org.bouncycastle.cert.jcajce.JcaCertStore; import org.bouncycastle.cert.jcajce.JcaX509CRLHolder; import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder; import org.bouncycastle.cert.ocsp.OCSPResp; import org.bouncycastle.cms.CMSAbsentContent; import org.bouncycastle.cms.CMSAlgorithm; import org.bouncycastle.cms.CMSProcessableByteArray; import org.bouncycastle.cms.CMSSignedData; import org.bouncycastle.cms.CMSSignedDataGenerator; import org.bouncycastle.cms.CMSSignedDataParser; import org.bouncycastle.cms.CMSTypedData; import org.bouncycastle.cms.DefaultCMSSignatureAlgorithmNameGenerator; import org.bouncycastle.cms.DefaultSignedAttributeTableGenerator; import org.bouncycastle.cms.SignerId; import org.bouncycastle.cms.SignerInfoGeneratorBuilder; import org.bouncycastle.cms.SignerInformation; import org.bouncycastle.cms.SignerInformationStore; import org.bouncycastle.cms.SignerInformationVerifier; import org.bouncycastle.cms.SignerInformationVerifierProvider; import org.bouncycastle.cms.bc.BcRSASignerInfoVerifierBuilder; import org.bouncycastle.cms.jcajce.JcaSignerId; import org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder; import org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoGeneratorBuilder; import org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder; import org.bouncycastle.crypto.Signer; import org.bouncycastle.crypto.params.AsymmetricKeyParameter; import org.bouncycastle.crypto.tls.SignatureAndHashAlgorithm; import org.bouncycastle.crypto.util.PrivateKeyFactory; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.operator.ContentSigner; import org.bouncycastle.operator.DefaultDigestAlgorithmIdentifierFinder; import org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder; import org.bouncycastle.operator.DigestCalculatorProvider; import org.bouncycastle.operator.OperatorCreationException; import org.bouncycastle.operator.bc.BcContentSignerBuilder; import org.bouncycastle.operator.bc.BcDigestCalculatorProvider; import org.bouncycastle.operator.bc.BcRSAContentSignerBuilder; import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder; import org.bouncycastle.util.CollectionStore; import org.bouncycastle.util.Store; import org.bouncycastle.util.encoders.Base64; import org.bouncycastle.util.io.Streams; public class NewSignedDataTest extends TestCase { private static final String BC = BouncyCastleProvider.PROVIDER_NAME; boolean DEBUG = true; private static String _origDN; private static KeyPair _origKP; private static X509Certificate _origCert; private static String _signDN; private static KeyPair _signKP; private static X509Certificate _signCert; private static KeyPair _signGostKP; private static X509Certificate _signGostCert; private static KeyPair _signEcDsaKP; private static X509Certificate _signEcDsaCert; private static KeyPair _signEcGostKP; private static X509Certificate _signEcGostCert; private static KeyPair _signDsaKP; private static X509Certificate _signDsaCert; private static String _reciDN; private static KeyPair _reciKP; private static X509Certificate _reciCert; private static X509CRL _signCrl; private static boolean _initialised = false; private byte[] disorderedMessage = Base64.decode( "SU9fc3RkaW5fdXNlZABfX2xpYmNfc3RhcnRfbWFpbgBnZXRob3N0aWQAX19n" + "bW9uX3M="); private byte[] disorderedSet = Base64.decode( "MIIYXQYJKoZIhvcNAQcCoIIYTjCCGEoCAQExCzAJBgUrDgMCGgUAMAsGCSqG" + "SIb3DQEHAaCCFqswggJUMIIBwKADAgECAgMMg6wwCgYGKyQDAwECBQAwbzEL" + "MAkGA1UEBhMCREUxPTA7BgNVBAoUNFJlZ3VsaWVydW5nc2JlaMhvcmRlIGbI" + "dXIgVGVsZWtvbW11bmlrYXRpb24gdW5kIFBvc3QxITAMBgcCggYBCgcUEwEx" + "MBEGA1UEAxQKNFItQ0EgMTpQTjAiGA8yMDAwMDMyMjA5NDM1MFoYDzIwMDQw" + "MTIxMTYwNDUzWjBvMQswCQYDVQQGEwJERTE9MDsGA1UEChQ0UmVndWxpZXJ1" + "bmdzYmVoyG9yZGUgZsh1ciBUZWxla29tbXVuaWthdGlvbiB1bmQgUG9zdDEh" + "MAwGBwKCBgEKBxQTATEwEQYDVQQDFAo1Ui1DQSAxOlBOMIGhMA0GCSqGSIb3" + "DQEBAQUAA4GPADCBiwKBgQCKHkFTJx8GmoqFTxEOxpK9XkC3NZ5dBEKiUv0I" + "fe3QMqeGMoCUnyJxwW0k2/53duHxtv2yHSZpFKjrjvE/uGwdOMqBMTjMzkFg" + "19e9JPv061wyADOucOIaNAgha/zFt9XUyrHF21knKCvDNExv2MYIAagkTKaj" + "LMAw0bu1J0FadQIFAMAAAAEwCgYGKyQDAwECBQADgYEAgFauXpoTLh3Z3pT/" + "3bhgrxO/2gKGZopWGSWSJPNwq/U3x2EuctOJurj+y2inTcJjespThflpN+7Q" + "nvsUhXU+jL2MtPlObU0GmLvWbi47cBShJ7KElcZAaxgWMBzdRGqTOdtMv+ev" + "2t4igGF/q71xf6J2c3pTLWr6P8s6tzLfOCMwggJDMIIBr6ADAgECAgQAuzyu" + "MAoGBiskAwMBAgUAMG8xCzAJBgNVBAYTAkRFMT0wOwYDVQQKFDRSZWd1bGll" + "cnVuZ3NiZWjIb3JkZSBmyHVyIFRlbGVrb21tdW5pa2F0aW9uIHVuZCBQb3N0" + "MSEwDAYHAoIGAQoHFBMBMTARBgNVBAMUCjVSLUNBIDE6UE4wIhgPMjAwMTA4" + "MjAwODA4MjBaGA8yMDA1MDgyMDA4MDgyMFowSzELMAkGA1UEBhMCREUxEjAQ" + "BgNVBAoUCVNpZ250cnVzdDEoMAwGBwKCBgEKBxQTATEwGAYDVQQDFBFDQSBT" + "SUdOVFJVU1QgMTpQTjCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAhV12" + "N2WhlR6f+3CXP57GrBM9la5Vnsu2b92zv5MZqQOPeEsYbZqDCFkYg1bSwsDE" + "XsGVQqXdQNAGUaapr/EUVVN+hNZ07GcmC1sPeQECgUkxDYjGi4ihbvzxlahj" + "L4nX+UTzJVBfJwXoIvJ+lMHOSpnOLIuEL3SRhBItvRECxN0CAwEAAaMSMBAw" + "DgYDVR0PAQH/BAQDAgEGMAoGBiskAwMBAgUAA4GBACDc9Pc6X8sK1cerphiV" + "LfFv4kpZb9ev4WPy/C6987Qw1SOTElhZAmxaJQBqmDHWlQ63wj1DEqswk7hG" + "LrvQk/iX6KXIn8e64uit7kx6DHGRKNvNGofPjr1WelGeGW/T2ZJKgmPDjCkf" + "sIKt2c3gwa2pDn4mmCz/DStUIqcPDbqLMIICVTCCAcGgAwIBAgIEAJ16STAK" + "BgYrJAMDAQIFADBvMQswCQYDVQQGEwJERTE9MDsGA1UEChQ0UmVndWxpZXJ1" + "bmdzYmVoyG9yZGUgZsh1ciBUZWxla29tbXVuaWthdGlvbiB1bmQgUG9zdDEh" + "MAwGBwKCBgEKBxQTATEwEQYDVQQDFAo1Ui1DQSAxOlBOMCIYDzIwMDEwMjAx" + "MTM0NDI1WhgPMjAwNTAzMjIwODU1NTFaMG8xCzAJBgNVBAYTAkRFMT0wOwYD" + "VQQKFDRSZWd1bGllcnVuZ3NiZWjIb3JkZSBmyHVyIFRlbGVrb21tdW5pa2F0" + "aW9uIHVuZCBQb3N0MSEwDAYHAoIGAQoHFBMBMTARBgNVBAMUCjZSLUNhIDE6" + "UE4wgaEwDQYJKoZIhvcNAQEBBQADgY8AMIGLAoGBAIOiqxUkzVyqnvthihnl" + "tsE5m1Xn5TZKeR/2MQPStc5hJ+V4yptEtIx+Fn5rOoqT5VEVWhcE35wdbPvg" + "JyQFn5msmhPQT/6XSGOlrWRoFummXN9lQzAjCj1sgTcmoLCVQ5s5WpCAOXFw" + "VWu16qndz3sPItn3jJ0F3Kh3w79NglvPAgUAwAAAATAKBgYrJAMDAQIFAAOB" + "gQBpSRdnDb6AcNVaXSmGo6+kVPIBhot1LzJOGaPyDNpGXxd7LV4tMBF1U7gr" + "4k1g9BO6YiMWvw9uiTZmn0CfV8+k4fWEuG/nmafRoGIuay2f+ILuT+C0rnp1" + "4FgMsEhuVNJJAmb12QV0PZII+UneyhAneZuQQzVUkTcVgYxogxdSOzCCAlUw" + "ggHBoAMCAQICBACdekowCgYGKyQDAwECBQAwbzELMAkGA1UEBhMCREUxPTA7" + "BgNVBAoUNFJlZ3VsaWVydW5nc2JlaMhvcmRlIGbIdXIgVGVsZWtvbW11bmlr" + "YXRpb24gdW5kIFBvc3QxITAMBgcCggYBCgcUEwExMBEGA1UEAxQKNlItQ2Eg" + "MTpQTjAiGA8yMDAxMDIwMTEzNDcwN1oYDzIwMDUwMzIyMDg1NTUxWjBvMQsw" + "CQYDVQQGEwJERTE9MDsGA1UEChQ0UmVndWxpZXJ1bmdzYmVoyG9yZGUgZsh1" + "ciBUZWxla29tbXVuaWthdGlvbiB1bmQgUG9zdDEhMAwGBwKCBgEKBxQTATEw" + "EQYDVQQDFAo1Ui1DQSAxOlBOMIGhMA0GCSqGSIb3DQEBAQUAA4GPADCBiwKB" + "gQCKHkFTJx8GmoqFTxEOxpK9XkC3NZ5dBEKiUv0Ife3QMqeGMoCUnyJxwW0k" + "2/53duHxtv2yHSZpFKjrjvE/uGwdOMqBMTjMzkFg19e9JPv061wyADOucOIa" + "NAgha/zFt9XUyrHF21knKCvDNExv2MYIAagkTKajLMAw0bu1J0FadQIFAMAA" + "AAEwCgYGKyQDAwECBQADgYEAV1yTi+2gyB7sUhn4PXmi/tmBxAfe5oBjDW8m" + "gxtfudxKGZ6l/FUPNcrSc5oqBYxKWtLmf3XX87LcblYsch617jtNTkMzhx9e" + "qxiD02ufcrxz2EVt0Akdqiz8mdVeqp3oLcNU/IttpSrcA91CAnoUXtDZYwb/" + "gdQ4FI9l3+qo/0UwggJVMIIBwaADAgECAgQAxIymMAoGBiskAwMBAgUAMG8x" + "CzAJBgNVBAYTAkRFMT0wOwYDVQQKFDRSZWd1bGllcnVuZ3NiZWjIb3JkZSBm" + "yHVyIFRlbGVrb21tdW5pa2F0aW9uIHVuZCBQb3N0MSEwDAYHAoIGAQoHFBMB" + "MTARBgNVBAMUCjZSLUNhIDE6UE4wIhgPMjAwMTEwMTUxMzMxNThaGA8yMDA1" + "MDYwMTA5NTIxN1owbzELMAkGA1UEBhMCREUxPTA7BgNVBAoUNFJlZ3VsaWVy" + "dW5nc2JlaMhvcmRlIGbIdXIgVGVsZWtvbW11bmlrYXRpb24gdW5kIFBvc3Qx" + "ITAMBgcCggYBCgcUEwExMBEGA1UEAxQKN1ItQ0EgMTpQTjCBoTANBgkqhkiG" + "9w0BAQEFAAOBjwAwgYsCgYEAiokD/j6lEP4FexF356OpU5teUpGGfUKjIrFX" + "BHc79G0TUzgVxqMoN1PWnWktQvKo8ETaugxLkP9/zfX3aAQzDW4Zki6x6GDq" + "fy09Agk+RJvhfbbIzRkV4sBBco0n73x7TfG/9NTgVr/96U+I+z/1j30aboM6" + "9OkLEhjxAr0/GbsCBQDAAAABMAoGBiskAwMBAgUAA4GBAHWRqRixt+EuqHhR" + "K1kIxKGZL2vZuakYV0R24Gv/0ZR52FE4ECr+I49o8FP1qiGSwnXB0SwjuH2S" + "iGiSJi+iH/MeY85IHwW1P5e+bOMvEOFhZhQXQixOD7totIoFtdyaj1XGYRef" + "0f2cPOjNJorXHGV8wuBk+/j++sxbd/Net3FtMIICVTCCAcGgAwIBAgIEAMSM" + "pzAKBgYrJAMDAQIFADBvMQswCQYDVQQGEwJERTE9MDsGA1UEChQ0UmVndWxp" + "ZXJ1bmdzYmVoyG9yZGUgZsh1ciBUZWxla29tbXVuaWthdGlvbiB1bmQgUG9z" + "dDEhMAwGBwKCBgEKBxQTATEwEQYDVQQDFAo3Ui1DQSAxOlBOMCIYDzIwMDEx" + "MDE1MTMzNDE0WhgPMjAwNTA2MDEwOTUyMTdaMG8xCzAJBgNVBAYTAkRFMT0w" + "OwYDVQQKFDRSZWd1bGllcnVuZ3NiZWjIb3JkZSBmyHVyIFRlbGVrb21tdW5p" + "a2F0aW9uIHVuZCBQb3N0MSEwDAYHAoIGAQoHFBMBMTARBgNVBAMUCjZSLUNh" + "IDE6UE4wgaEwDQYJKoZIhvcNAQEBBQADgY8AMIGLAoGBAIOiqxUkzVyqnvth" + "ihnltsE5m1Xn5TZKeR/2MQPStc5hJ+V4yptEtIx+Fn5rOoqT5VEVWhcE35wd" + "bPvgJyQFn5msmhPQT/6XSGOlrWRoFummXN9lQzAjCj1sgTcmoLCVQ5s5WpCA" + "OXFwVWu16qndz3sPItn3jJ0F3Kh3w79NglvPAgUAwAAAATAKBgYrJAMDAQIF" + "AAOBgQBi5W96UVDoNIRkCncqr1LLG9vF9SGBIkvFpLDIIbcvp+CXhlvsdCJl" + "0pt2QEPSDl4cmpOet+CxJTdTuMeBNXxhb7Dvualog69w/+K2JbPhZYxuVFZs" + "Zh5BkPn2FnbNu3YbJhE60aIkikr72J4XZsI5DxpZCGh6xyV/YPRdKSljFjCC" + "AlQwggHAoAMCAQICAwyDqzAKBgYrJAMDAQIFADBvMQswCQYDVQQGEwJERTE9" + "MDsGA1UEChQ0UmVndWxpZXJ1bmdzYmVoyG9yZGUgZsh1ciBUZWxla29tbXVu" + "aWthdGlvbiB1bmQgUG9zdDEhMAwGBwKCBgEKBxQTATEwEQYDVQQDFAo1Ui1D" + "QSAxOlBOMCIYDzIwMDAwMzIyMDk0MTI3WhgPMjAwNDAxMjExNjA0NTNaMG8x" + "CzAJBgNVBAYTAkRFMT0wOwYDVQQKFDRSZWd1bGllcnVuZ3NiZWjIb3JkZSBm" + "yHVyIFRlbGVrb21tdW5pa2F0aW9uIHVuZCBQb3N0MSEwDAYHAoIGAQoHFBMB" + "MTARBgNVBAMUCjRSLUNBIDE6UE4wgaEwDQYJKoZIhvcNAQEBBQADgY8AMIGL" + "AoGBAI8x26tmrFJanlm100B7KGlRemCD1R93PwdnG7svRyf5ZxOsdGrDszNg" + "xg6ouO8ZHQMT3NC2dH8TvO65Js+8bIyTm51azF6clEg0qeWNMKiiXbBXa+ph" + "hTkGbXiLYvACZ6/MTJMJ1lcrjpRF7BXtYeYMcEF6znD4pxOqrtbf9z5hAgUA" + "wAAAATAKBgYrJAMDAQIFAAOBgQB99BjSKlGPbMLQAgXlvA9jUsDNhpnVm3a1" + "YkfxSqS/dbQlYkbOKvCxkPGA9NBxisBM8l1zFynVjJoy++aysRmcnLY/sHaz" + "23BF2iU7WERy18H3lMBfYB6sXkfYiZtvQZcWaO48m73ZBySuiV3iXpb2wgs/" + "Cs20iqroAWxwq/W/9jCCAlMwggG/oAMCAQICBDsFZ9UwCgYGKyQDAwECBQAw" + "bzELMAkGA1UEBhMCREUxITAMBgcCggYBCgcUEwExMBEGA1UEAxQKNFItQ0Eg" + "MTpQTjE9MDsGA1UEChQ0UmVndWxpZXJ1bmdzYmVoyG9yZGUgZsh1ciBUZWxl" + "a29tbXVuaWthdGlvbiB1bmQgUG9zdDAiGA8xOTk5MDEyMTE3MzUzNFoYDzIw" + "MDQwMTIxMTYwMDAyWjBvMQswCQYDVQQGEwJERTE9MDsGA1UEChQ0UmVndWxp" + "ZXJ1bmdzYmVoyG9yZGUgZsh1ciBUZWxla29tbXVuaWthdGlvbiB1bmQgUG9z" + "dDEhMAwGBwKCBgEKBxQTATEwEQYDVQQDFAozUi1DQSAxOlBOMIGfMA0GCSqG" + "SIb3DQEBAQUAA4GNADCBiQKBgI4B557mbKQg/AqWBXNJhaT/6lwV93HUl4U8" + "u35udLq2+u9phns1WZkdM3gDfEpL002PeLfHr1ID/96dDYf04lAXQfombils" + "of1C1k32xOvxjlcrDOuPEMxz9/HDAQZA5MjmmYHAIulGI8Qg4Tc7ERRtg/hd" + "0QX0/zoOeXoDSEOBAgTAAAABMAoGBiskAwMBAgUAA4GBAIyzwfT3keHI/n2P" + "LrarRJv96mCohmDZNpUQdZTVjGu5VQjVJwk3hpagU0o/t/FkdzAjOdfEw8Ql" + "3WXhfIbNLv1YafMm2eWSdeYbLcbB5yJ1od+SYyf9+tm7cwfDAcr22jNRBqx8" + "wkWKtKDjWKkevaSdy99sAI8jebHtWz7jzydKMIID9TCCA16gAwIBAgICbMcw" + "DQYJKoZIhvcNAQEFBQAwSzELMAkGA1UEBhMCREUxEjAQBgNVBAoUCVNpZ250" + "cnVzdDEoMAwGBwKCBgEKBxQTATEwGAYDVQQDFBFDQSBTSUdOVFJVU1QgMTpQ" + "TjAeFw0wNDA3MzAxMzAyNDZaFw0wNzA3MzAxMzAyNDZaMDwxETAPBgNVBAMM" + "CFlhY29tOlBOMQ4wDAYDVQRBDAVZYWNvbTELMAkGA1UEBhMCREUxCjAIBgNV" + "BAUTATEwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAIWzLlYLQApocXIp" + "pgCCpkkOUVLgcLYKeOd6/bXAnI2dTHQqT2bv7qzfUnYvOqiNgYdF13pOYtKg" + "XwXMTNFL4ZOI6GoBdNs9TQiZ7KEWnqnr2945HYx7UpgTBclbOK/wGHuCdcwO" + "x7juZs1ZQPFG0Lv8RoiV9s6HP7POqh1sO0P/AgMBAAGjggH1MIIB8TCBnAYD" + "VR0jBIGUMIGRgBQcZzNghfnXoXRm8h1+VITC5caNRqFzpHEwbzELMAkGA1UE" + "BhMCREUxPTA7BgNVBAoUNFJlZ3VsaWVydW5nc2JlaMhvcmRlIGbIdXIgVGVs" + "ZWtvbW11bmlrYXRpb24gdW5kIFBvc3QxITAMBgcCggYBCgcUEwExMBEGA1UE" + "AxQKNVItQ0EgMTpQToIEALs8rjAdBgNVHQ4EFgQU2e5KAzkVuKaM9I5heXkz" + "bcAIuR8wDgYDVR0PAQH/BAQDAgZAMBIGA1UdIAQLMAkwBwYFKyQIAQEwfwYD" + "VR0fBHgwdjB0oCygKoYobGRhcDovL2Rpci5zaWdudHJ1c3QuZGUvbz1TaWdu" + "dHJ1c3QsYz1kZaJEpEIwQDEdMBsGA1UEAxMUQ1JMU2lnblNpZ250cnVzdDE6" + "UE4xEjAQBgNVBAoTCVNpZ250cnVzdDELMAkGA1UEBhMCREUwYgYIKwYBBQUH" + "AQEEVjBUMFIGCCsGAQUFBzABhkZodHRwOi8vZGlyLnNpZ250cnVzdC5kZS9T" + "aWdudHJ1c3QvT0NTUC9zZXJ2bGV0L2h0dHBHYXRld2F5LlBvc3RIYW5kbGVy" + "MBgGCCsGAQUFBwEDBAwwCjAIBgYEAI5GAQEwDgYHAoIGAQoMAAQDAQH/MA0G" + "CSqGSIb3DQEBBQUAA4GBAHn1m3GcoyD5GBkKUY/OdtD6Sj38LYqYCF+qDbJR" + "6pqUBjY2wsvXepUppEler+stH8mwpDDSJXrJyuzf7xroDs4dkLl+Rs2x+2tg" + "BjU+ABkBDMsym2WpwgA8LCdymmXmjdv9tULxY+ec2pjSEzql6nEZNEfrU8nt" + "ZCSCavgqW4TtMYIBejCCAXYCAQEwUTBLMQswCQYDVQQGEwJERTESMBAGA1UE" + "ChQJU2lnbnRydXN0MSgwDAYHAoIGAQoHFBMBMTAYBgNVBAMUEUNBIFNJR05U" + "UlVTVCAxOlBOAgJsxzAJBgUrDgMCGgUAoIGAMBgGCSqGSIb3DQEJAzELBgkq" + "hkiG9w0BBwEwIwYJKoZIhvcNAQkEMRYEFIYfhPoyfGzkLWWSSLjaHb4HQmaK" + "MBwGCSqGSIb3DQEJBTEPFw0wNTAzMjQwNzM4MzVaMCEGBSskCAYFMRgWFi92" + "YXIvZmlsZXMvdG1wXzEvdGVzdDEwDQYJKoZIhvcNAQEFBQAEgYA2IvA8lhVz" + "VD5e/itUxbFboKxeKnqJ5n/KuO/uBCl1N14+7Z2vtw1sfkIG+bJdp3OY2Cmn" + "mrQcwsN99Vjal4cXVj8t+DJzFG9tK9dSLvD3q9zT/GQ0kJXfimLVwCa4NaSf" + "Qsu4xtG0Rav6bCcnzabAkKuNNvKtH8amSRzk870DBg=="); public static byte[] xtraCounterSig = Base64.decode( "MIIR/AYJKoZIhvcNAQcCoIIR7TCCEekCAQExCzAJBgUrDgMCGgUAMBoGCSqG" + "SIb3DQEHAaANBAtIZWxsbyB3b3JsZKCCDnkwggTPMIIDt6ADAgECAgRDnYD3" + "MA0GCSqGSIb3DQEBBQUAMFgxCzAJBgNVBAYTAklUMRowGAYDVQQKExFJbi5U" + "ZS5TLkEuIFMucC5BLjEtMCsGA1UEAxMkSW4uVGUuUy5BLiAtIENlcnRpZmlj" + "YXRpb24gQXV0aG9yaXR5MB4XDTA4MDkxMjExNDMxMloXDTEwMDkxMjExNDMx" + "MlowgdgxCzAJBgNVBAYTAklUMSIwIAYDVQQKDBlJbnRlc2EgUy5wLkEuLzA1" + "MjYyODkwMDE0MSowKAYDVQQLDCFCdXNpbmVzcyBDb2xsYWJvcmF0aW9uICYg" + "U2VjdXJpdHkxHjAcBgNVBAMMFU1BU1NJTUlMSUFOTyBaSUNDQVJESTERMA8G" + "A1UEBAwIWklDQ0FSREkxFTATBgNVBCoMDE1BU1NJTUlMSUFOTzEcMBoGA1UE" + "BRMTSVQ6WkNDTVNNNzZIMTRMMjE5WTERMA8GA1UELhMIMDAwMDI1ODUwgaAw" + "DQYJKoZIhvcNAQEBBQADgY4AMIGKAoGBALeJTjmyFgx1SIP6c2AuB/kuyHo5" + "j/prKELTALsFDimre/Hxr3wOSet1TdQfFzU8Lu+EJqgfV9cV+cI1yeH1rZs7" + "lei7L3tX/VR565IywnguX5xwvteASgWZr537Fkws50bvTEMyYOj1Tf3FZvZU" + "z4n4OD39KI4mfR9i1eEVIxR3AgQAizpNo4IBoTCCAZ0wHQYDVR0RBBYwFIES" + "emljY2FyZGlAaW50ZXNhLml0MC8GCCsGAQUFBwEDBCMwITAIBgYEAI5GAQEw" + "CwYGBACORgEDAgEUMAgGBgQAjkYBBDBZBgNVHSAEUjBQME4GBgQAizABATBE" + "MEIGCCsGAQUFBwIBFjZodHRwOi8vZS10cnVzdGNvbS5pbnRlc2EuaXQvY2Ff" + "cHViYmxpY2EvQ1BTX0lOVEVTQS5odG0wDgYDVR0PAQH/BAQDAgZAMIGDBgNV" + "HSMEfDB6gBQZCQOW0bjFWBt+EORuxPagEgkQqKFcpFowWDELMAkGA1UEBhMC" + "SVQxGjAYBgNVBAoTEUluLlRlLlMuQS4gUy5wLkEuMS0wKwYDVQQDEyRJbi5U" + "ZS5TLkEuIC0gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHmCBDzRARMwOwYDVR0f" + "BDQwMjAwoC6gLIYqaHR0cDovL2UtdHJ1c3Rjb20uaW50ZXNhLml0L0NSTC9J" + "TlRFU0EuY3JsMB0GA1UdDgQWBBTf5ItL8KmQh541Dxt7YxcWI1254TANBgkq" + "hkiG9w0BAQUFAAOCAQEAgW+uL1CVWQepbC/wfCmR6PN37Sueb4xiKQj2mTD5" + "UZ5KQjpivy/Hbuf0NrfKNiDEhAvoHSPC31ebGiKuTMFNyZPHfPEUnyYGSxea" + "2w837aXJFr6utPNQGBRi89kH90sZDlXtOSrZI+AzJJn5QK3F9gjcayU2NZXQ" + "MJgRwYmFyn2w4jtox+CwXPQ9E5XgxiMZ4WDL03cWVXDLX00EOJwnDDMUNTRI" + "m9Zv+4SKTNlfFbi9UTBqWBySkDzAelsfB2U61oqc2h1xKmCtkGMmN9iZT+Qz" + "ZC/vaaT+hLEBFGAH2gwFrYc4/jTBKyBYeU1vsAxsibIoTs1Apgl6MH75qPDL" + "BzCCBM8wggO3oAMCAQICBEOdgPcwDQYJKoZIhvcNAQEFBQAwWDELMAkGA1UE" + "BhMCSVQxGjAYBgNVBAoTEUluLlRlLlMuQS4gUy5wLkEuMS0wKwYDVQQDEyRJ" + "bi5UZS5TLkEuIC0gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDgwOTEy" + "MTE0MzEyWhcNMTAwOTEyMTE0MzEyWjCB2DELMAkGA1UEBhMCSVQxIjAgBgNV" + "BAoMGUludGVzYSBTLnAuQS4vMDUyNjI4OTAwMTQxKjAoBgNVBAsMIUJ1c2lu" + "ZXNzIENvbGxhYm9yYXRpb24gJiBTZWN1cml0eTEeMBwGA1UEAwwVTUFTU0lN" + "SUxJQU5PIFpJQ0NBUkRJMREwDwYDVQQEDAhaSUNDQVJESTEVMBMGA1UEKgwM" + "TUFTU0lNSUxJQU5PMRwwGgYDVQQFExNJVDpaQ0NNU003NkgxNEwyMTlZMREw" + "DwYDVQQuEwgwMDAwMjU4NTCBoDANBgkqhkiG9w0BAQEFAAOBjgAwgYoCgYEA" + "t4lOObIWDHVIg/pzYC4H+S7IejmP+msoQtMAuwUOKat78fGvfA5J63VN1B8X" + "NTwu74QmqB9X1xX5wjXJ4fWtmzuV6Lsve1f9VHnrkjLCeC5fnHC+14BKBZmv" + "nfsWTCznRu9MQzJg6PVN/cVm9lTPifg4Pf0ojiZ9H2LV4RUjFHcCBACLOk2j" + "ggGhMIIBnTAdBgNVHREEFjAUgRJ6aWNjYXJkaUBpbnRlc2EuaXQwLwYIKwYB" + "BQUHAQMEIzAhMAgGBgQAjkYBATALBgYEAI5GAQMCARQwCAYGBACORgEEMFkG" + "A1UdIARSMFAwTgYGBACLMAEBMEQwQgYIKwYBBQUHAgEWNmh0dHA6Ly9lLXRy" + "dXN0Y29tLmludGVzYS5pdC9jYV9wdWJibGljYS9DUFNfSU5URVNBLmh0bTAO" + "BgNVHQ8BAf8EBAMCBkAwgYMGA1UdIwR8MHqAFBkJA5bRuMVYG34Q5G7E9qAS" + "CRCooVykWjBYMQswCQYDVQQGEwJJVDEaMBgGA1UEChMRSW4uVGUuUy5BLiBT" + "LnAuQS4xLTArBgNVBAMTJEluLlRlLlMuQS4gLSBDZXJ0aWZpY2F0aW9uIEF1" + "dGhvcml0eYIEPNEBEzA7BgNVHR8ENDAyMDCgLqAshipodHRwOi8vZS10cnVz" + "dGNvbS5pbnRlc2EuaXQvQ1JML0lOVEVTQS5jcmwwHQYDVR0OBBYEFN/ki0vw" + "qZCHnjUPG3tjFxYjXbnhMA0GCSqGSIb3DQEBBQUAA4IBAQCBb64vUJVZB6ls" + "L/B8KZHo83ftK55vjGIpCPaZMPlRnkpCOmK/L8du5/Q2t8o2IMSEC+gdI8Lf" + "V5saIq5MwU3Jk8d88RSfJgZLF5rbDzftpckWvq6081AYFGLz2Qf3SxkOVe05" + "Ktkj4DMkmflArcX2CNxrJTY1ldAwmBHBiYXKfbDiO2jH4LBc9D0TleDGIxnh" + "YMvTdxZVcMtfTQQ4nCcMMxQ1NEib1m/7hIpM2V8VuL1RMGpYHJKQPMB6Wx8H" + "ZTrWipzaHXEqYK2QYyY32JlP5DNkL+9ppP6EsQEUYAfaDAWthzj+NMErIFh5" + "TW+wDGyJsihOzUCmCXowfvmo8MsHMIIEzzCCA7egAwIBAgIEQ52A9zANBgkq" + "hkiG9w0BAQUFADBYMQswCQYDVQQGEwJJVDEaMBgGA1UEChMRSW4uVGUuUy5B" + "LiBTLnAuQS4xLTArBgNVBAMTJEluLlRlLlMuQS4gLSBDZXJ0aWZpY2F0aW9u" + "IEF1dGhvcml0eTAeFw0wODA5MTIxMTQzMTJaFw0xMDA5MTIxMTQzMTJaMIHY" + "MQswCQYDVQQGEwJJVDEiMCAGA1UECgwZSW50ZXNhIFMucC5BLi8wNTI2Mjg5" + "MDAxNDEqMCgGA1UECwwhQnVzaW5lc3MgQ29sbGFib3JhdGlvbiAmIFNlY3Vy" + "aXR5MR4wHAYDVQQDDBVNQVNTSU1JTElBTk8gWklDQ0FSREkxETAPBgNVBAQM" + "CFpJQ0NBUkRJMRUwEwYDVQQqDAxNQVNTSU1JTElBTk8xHDAaBgNVBAUTE0lU" + "OlpDQ01TTTc2SDE0TDIxOVkxETAPBgNVBC4TCDAwMDAyNTg1MIGgMA0GCSqG" + "SIb3DQEBAQUAA4GOADCBigKBgQC3iU45shYMdUiD+nNgLgf5Lsh6OY/6ayhC" + "0wC7BQ4pq3vx8a98DknrdU3UHxc1PC7vhCaoH1fXFfnCNcnh9a2bO5Xouy97" + "V/1UeeuSMsJ4Ll+ccL7XgEoFma+d+xZMLOdG70xDMmDo9U39xWb2VM+J+Dg9" + "/SiOJn0fYtXhFSMUdwIEAIs6TaOCAaEwggGdMB0GA1UdEQQWMBSBEnppY2Nh" + "cmRpQGludGVzYS5pdDAvBggrBgEFBQcBAwQjMCEwCAYGBACORgEBMAsGBgQA" + "jkYBAwIBFDAIBgYEAI5GAQQwWQYDVR0gBFIwUDBOBgYEAIswAQEwRDBCBggr" + "BgEFBQcCARY2aHR0cDovL2UtdHJ1c3Rjb20uaW50ZXNhLml0L2NhX3B1YmJs" + "aWNhL0NQU19JTlRFU0EuaHRtMA4GA1UdDwEB/wQEAwIGQDCBgwYDVR0jBHww" + "eoAUGQkDltG4xVgbfhDkbsT2oBIJEKihXKRaMFgxCzAJBgNVBAYTAklUMRow" + "GAYDVQQKExFJbi5UZS5TLkEuIFMucC5BLjEtMCsGA1UEAxMkSW4uVGUuUy5B" + "LiAtIENlcnRpZmljYXRpb24gQXV0aG9yaXR5ggQ80QETMDsGA1UdHwQ0MDIw" + "MKAuoCyGKmh0dHA6Ly9lLXRydXN0Y29tLmludGVzYS5pdC9DUkwvSU5URVNB" + "LmNybDAdBgNVHQ4EFgQU3+SLS/CpkIeeNQ8be2MXFiNdueEwDQYJKoZIhvcN" + "AQEFBQADggEBAIFvri9QlVkHqWwv8Hwpkejzd+0rnm+MYikI9pkw+VGeSkI6" + "Yr8vx27n9Da3yjYgxIQL6B0jwt9XmxoirkzBTcmTx3zxFJ8mBksXmtsPN+2l" + "yRa+rrTzUBgUYvPZB/dLGQ5V7Tkq2SPgMySZ+UCtxfYI3GslNjWV0DCYEcGJ" + "hcp9sOI7aMfgsFz0PROV4MYjGeFgy9N3FlVwy19NBDicJwwzFDU0SJvWb/uE" + "ikzZXxW4vVEwalgckpA8wHpbHwdlOtaKnNodcSpgrZBjJjfYmU/kM2Qv72mk" + "/oSxARRgB9oMBa2HOP40wSsgWHlNb7AMbImyKE7NQKYJejB++ajwywcxggM8" + "MIIDOAIBATBgMFgxCzAJBgNVBAYTAklUMRowGAYDVQQKExFJbi5UZS5TLkEu" + "IFMucC5BLjEtMCsGA1UEAxMkSW4uVGUuUy5BLiAtIENlcnRpZmljYXRpb24g" + "QXV0aG9yaXR5AgRDnYD3MAkGBSsOAwIaBQAwDQYJKoZIhvcNAQEBBQAEgYB+" + "lH2cwLqc91mP8prvgSV+RRzk13dJdZvdoVjgQoFrPhBiZCNIEoHvIhMMA/sM" + "X6euSRZk7EjD24FasCEGYyd0mJVLEy6TSPmuW+wWz/28w3a6IWXBGrbb/ild" + "/CJMkPgLPGgOVD1WDwiNKwfasiQSFtySf5DPn3jFevdLeMmEY6GCAjIwggEV" + "BgkqhkiG9w0BCQYxggEGMIIBAgIBATBgMFgxCzAJBgNVBAYTAklUMRowGAYD" + "VQQKExFJbi5UZS5TLkEuIFMucC5BLjEtMCsGA1UEAxMkSW4uVGUuUy5BLiAt" + "IENlcnRpZmljYXRpb24gQXV0aG9yaXR5AgRDnYD3MAkGBSsOAwIaBQAwDQYJ" + "KoZIhvcNAQEBBQAEgYBHlOULfT5GDigIvxP0qZOy8VbpntmzaPF55VV4buKV" + "35J+uHp98gXKp0LrHM69V5IRKuyuQzHHFBqsXxsRI9o6KoOfgliD9Xc+BeMg" + "dKzQhBhBYoFREq8hQM0nSbqDNHYAQyNHMzUA/ZQUO5dlFuH8Dw3iDYAhNtfd" + "PrlchKJthDCCARUGCSqGSIb3DQEJBjGCAQYwggECAgEBMGAwWDELMAkGA1UE" + "BhMCSVQxGjAYBgNVBAoTEUluLlRlLlMuQS4gUy5wLkEuMS0wKwYDVQQDEyRJ" + "bi5UZS5TLkEuIC0gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkCBEOdgPcwCQYF" + "Kw4DAhoFADANBgkqhkiG9w0BAQEFAASBgEeU5Qt9PkYOKAi/E/Spk7LxVume" + "2bNo8XnlVXhu4pXfkn64en3yBcqnQusczr1XkhEq7K5DMccUGqxfGxEj2joq" + "g5+CWIP1dz4F4yB0rNCEGEFigVESryFAzSdJuoM0dgBDI0czNQD9lBQ7l2UW" + "4fwPDeINgCE2190+uVyEom2E"); byte[] noSignedAttrSample2 = Base64.decode( "MIIIlAYJKoZIhvcNAQcCoIIIhTCCCIECAQExCzAJBgUrDgMCGgUAMAsGCSqG" + "SIb3DQEHAaCCB3UwggOtMIIDa6ADAgECAgEzMAsGByqGSM44BAMFADCBkDEL" + "MAkGA1UEBhMCVVMxCzAJBgNVBAgTAkNBMRIwEAYDVQQHEwlQYWxvIEFsdG8x" + "HTAbBgNVBAoTFFN1biBNaWNyb3N5c3RlbXMgSW5jMSMwIQYDVQQLExpKYXZh" + "IFNvZnR3YXJlIENvZGUgU2lnbmluZzEcMBoGA1UEAxMTSkNFIENvZGUgU2ln" + "bmluZyBDQTAeFw0wMTA1MjkxNjQ3MTFaFw0wNjA1MjgxNjQ3MTFaMG4xHTAb" + "BgNVBAoTFFN1biBNaWNyb3N5c3RlbXMgSW5jMSMwIQYDVQQLExpKYXZhIFNv" + "ZnR3YXJlIENvZGUgU2lnbmluZzEoMCYGA1UEAxMfVGhlIExlZ2lvbiBvZiB0" + "aGUgQm91bmN5IENhc3RsZTCCAbcwggEsBgcqhkjOOAQBMIIBHwKBgQD9f1OB" + "HXUSKVLfSpwu7OTn9hG3UjzvRADDHj+AtlEmaUVdQCJR+1k9jVj6v8X1ujD2" + "y5tVbNeBO4AdNG/yZmC3a5lQpaSfn+gEexAiwk+7qdf+t8Yb+DtX58aophUP" + "BPuD9tPFHsMCNVQTWhaRMvZ1864rYdcq7/IiAxmd0UgBxwIVAJdgUI8VIwvM" + "spK5gqLrhAvwWBz1AoGBAPfhoIXWmz3ey7yrXDa4V7l5lK+7+jrqgvlXTAs9" + "B4JnUVlXjrrUWU/mcQcQgYC0SRZxI+hMKBYTt88JMozIpuE8FnqLVHyNKOCj" + "rh4rs6Z1kW6jfwv6ITVi8ftiegEkO8yk8b6oUZCJqIPf4VrlnwaSi2ZegHtV" + "JWQBTDv+z0kqA4GEAAKBgBWry/FCAZ6miyy39+ftsa+h9lxoL+JtV0MJcUyQ" + "E4VAhpAwWb8vyjba9AwOylYQTktHX5sAkFvjBiU0LOYDbFSTVZSHMRJgfjxB" + "SHtICjOEvr1BJrrOrdzqdxcOUge5n7El124BCrv91x5Ol8UTwtiO9LrRXF/d" + "SyK+RT5n1klRo3YwdDARBglghkgBhvhCAQEEBAMCAIcwDgYDVR0PAQH/BAQD" + "AgHGMB0GA1UdDgQWBBQwMY4NRcco1AO3w1YsokfDLVseEjAPBgNVHRMBAf8E" + "BTADAQH/MB8GA1UdIwQYMBaAFGXi9IbJ007wkU5Yomr12HhamsGmMAsGByqG" + "SM44BAMFAAMvADAsAhRmigTu6QV0sTfEkVljgij/hhdVfAIUQZvMxAnIHc30" + "y/u0C1T5UEG9glUwggPAMIIDfqADAgECAgEQMAsGByqGSM44BAMFADCBkDEL" + "MAkGA1UEBhMCVVMxCzAJBgNVBAgTAkNBMRIwEAYDVQQHEwlQYWxvIEFsdG8x" + "HTAbBgNVBAoTFFN1biBNaWNyb3N5c3RlbXMgSW5jMSMwIQYDVQQLExpKYXZh" + "IFNvZnR3YXJlIENvZGUgU2lnbmluZzEcMBoGA1UEAxMTSkNFIENvZGUgU2ln" + "bmluZyBDQTAeFw0wMTA0MjUwNzAwMDBaFw0yMDA0MjUwNzAwMDBaMIGQMQsw" + "CQYDVQQGEwJVUzELMAkGA1UECBMCQ0ExEjAQBgNVBAcTCVBhbG8gQWx0bzEd" + "MBsGA1UEChMUU3VuIE1pY3Jvc3lzdGVtcyBJbmMxIzAhBgNVBAsTGkphdmEg" + "U29mdHdhcmUgQ29kZSBTaWduaW5nMRwwGgYDVQQDExNKQ0UgQ29kZSBTaWdu" + "aW5nIENBMIIBtzCCASwGByqGSM44BAEwggEfAoGBAOuvNwQeylEeaV2w8o/2" + "tUkfxqSZBdcpv3S3avUZ2B7kG/gKAZqY/3Cr4kpWhmxTs/zhyIGMMfDE87CL" + "5nAG7PdpaNuDTHIpiSk2F1w7SgegIAIqRpdRHXDICBgLzgxum3b3BePn+9Nh" + "eeFgmiSNBpWDPFEg4TDPOFeCphpyDc7TAhUAhCVF4bq5qWKreehbMLiJaxv/" + "e3UCgYEAq8l0e3Tv7kK1alNNO92QBnJokQ8LpCl2LlU71a5NZVx+KjoEpmem" + "0HGqpde34sFyDaTRqh6SVEwgAAmisAlBGTMAssNcrkL4sYvKfJbYEH83RFuq" + "zHjI13J2N2tAmahVZvqoAx6LShECactMuCUGHKB30sms0j3pChD6dnC3+9wD" + "gYQAAoGALQmYXKy4nMeZfu4gGSo0kPnXq6uu3WtylQ1m+O8nj0Sy7ShEx/6v" + "sKYnbwBnRYJbB6hWVjvSKVFhXmk51y50dxLPGUr1LcjLcmHETm/6R0M/FLv6" + "vBhmKMLZZot6LS/CYJJLFP5YPiF/aGK+bEhJ+aBLXoWdGRD5FUVRG3HU9wuj" + "ZjBkMBEGCWCGSAGG+EIBAQQEAwIABzAPBgNVHRMBAf8EBTADAQH/MB8GA1Ud" + "IwQYMBaAFGXi9IbJ007wkU5Yomr12HhamsGmMB0GA1UdDgQWBBRl4vSGydNO" + "8JFOWKJq9dh4WprBpjALBgcqhkjOOAQDBQADLwAwLAIUKvfPPJdd+Xi2CNdB" + "tNkNRUzktJwCFEXNdWkOIfod1rMpsun3Mx0z/fxJMYHoMIHlAgEBMIGWMIGQ" + "MQswCQYDVQQGEwJVUzELMAkGA1UECBMCQ0ExEjAQBgNVBAcTCVBhbG8gQWx0" + "bzEdMBsGA1UEChMUU3VuIE1pY3Jvc3lzdGVtcyBJbmMxIzAhBgNVBAsTGkph" + "dmEgU29mdHdhcmUgQ29kZSBTaWduaW5nMRwwGgYDVQQDExNKQ0UgQ29kZSBT" + "aWduaW5nIENBAgEzMAkGBSsOAwIaBQAwCwYHKoZIzjgEAQUABC8wLQIVAIGV" + "khm+kbV4a/+EP45PHcq0hIViAhR4M9os6IrJnoEDS3Y3l7O6zrSosA=="); private static final byte[] rawGost = Base64.decode( "MIIEBwYJKoZIhvcNAQcCoIID+DCCA/QCAQExDDAKBgYqhQMCAgkFADAfBgkq" + "hkiG9w0BBwGgEgQQU29tZSBEYXRhIEhFUkUhIaCCAuYwggLiMIICkaADAgEC" + "AgopoLG9AAIAArWeMAgGBiqFAwICAzBlMSAwHgYJKoZIhvcNAQkBFhFpbmZv" + "QGNyeXB0b3Byby5ydTELMAkGA1UEBhMCUlUxEzARBgNVBAoTCkNSWVBUTy1Q" + "Uk8xHzAdBgNVBAMTFlRlc3QgQ2VudGVyIENSWVBUTy1QUk8wHhcNMTIxMDE1" + "MTEwNDIzWhcNMTQxMDA0MDcwOTQxWjAhMRIwEAYDVQQDDAl0ZXN0IGdvc3Qx" + "CzAJBgNVBAYTAlJVMGMwHAYGKoUDAgITMBIGByqFAwICJAAGByqFAwICHgED" + "QwAEQPz/F99AG8wyMQz5uK3vJ3MdHk7ZyFzM4Ofnq8nAmDgI5/Nuzcu791/0" + "hRd+1i+fArRsiPMdQXOF0E7bEMHwWfWjggFjMIIBXzAOBgNVHQ8BAf8EBAMC" + "BPAwEwYDVR0lBAwwCgYIKwYBBQUHAwIwHQYDVR0OBBYEFO353ZD7sLCx6rVR" + "2o/IsSxuE1gAMB8GA1UdIwQYMBaAFG2PXgXZX6yRF5QelZoFMDg3ehAqMFUG" + "A1UdHwROMEwwSqBIoEaGRGh0dHA6Ly93d3cuY3J5cHRvcHJvLnJ1L0NlcnRF" + "bnJvbGwvVGVzdCUyMENlbnRlciUyMENSWVBUTy1QUk8oMikuY3JsMIGgBggr" + "BgEFBQcBAQSBkzCBkDAzBggrBgEFBQcwAYYnaHR0cDovL3d3dy5jcnlwdG9w" + "cm8ucnUvb2NzcG5jL29jc3Auc3JmMFkGCCsGAQUFBzAChk1odHRwOi8vd3d3" + "LmNyeXB0b3Byby5ydS9DZXJ0RW5yb2xsL3BraS1zaXRlX1Rlc3QlMjBDZW50" + "ZXIlMjBDUllQVE8tUFJPKDIpLmNydDAIBgYqhQMCAgMDQQBAR4mr69a62d3l" + "yK/UZ4Yz/Yi3jqURtbnJR2gugdzkG5pYHRwC41BbDaa1ItP+1gDp4s78+EiK" + "AJc17CHGZTz3MYHVMIHSAgEBMHMwZTEgMB4GCSqGSIb3DQEJARYRaW5mb0Bj" + "cnlwdG9wcm8ucnUxCzAJBgNVBAYTAlJVMRMwEQYDVQQKEwpDUllQVE8tUFJP" + "MR8wHQYDVQQDExZUZXN0IENlbnRlciBDUllQVE8tUFJPAgopoLG9AAIAArWe" + "MAoGBiqFAwICCQUAMAoGBiqFAwICEwUABED0Gs9zP9lSz/2/e3BUSpzCI3dx" + "39gfl/pFVkx4p5N/GW5o4gHIST9OhDSmdxwpMSK+39YSRD4R0Ue0faOqWEsj" + "AAAAAAAAAAAAAAAAAAAAAA=="); private static final byte[] noAttrEncData = Base64.decode( "MIIFjwYJKoZIhvcNAQcCoIIFgDCCBXwCAQExDTALBglghkgBZQMEAgEwgdAG" + "CSqGSIb3DQEHAaCBwgSBv01JTUUtVmVyc2lvbjogMS4wCkNvbnRlbnQtVHlw" + "ZTogYXBwbGljYXRpb24vb2N0ZXQtc3RyZWFtCkNvbnRlbnQtVHJhbnNmZXIt" + "RW5jb2Rpbmc6IGJpbmFyeQpDb250ZW50LURpc3Bvc2l0aW9uOiBhdHRhY2ht" + "ZW50OyBmaWxlbmFtZT1kb2MuYmluCgpUaGlzIGlzIGEgdmVyeSBodWdlIHNl" + "Y3JldCwgbWFkZSB3aXRoIG9wZW5zc2wKCgoKoIIDNDCCAzAwggKZoAMCAQIC" + "AQEwDQYJKoZIhvcNAQEFBQAwgawxCzAJBgNVBAYTAkFUMRAwDgYDVQQIEwdB" + "dXN0cmlhMQ8wDQYDVQQHEwZWaWVubmExFTATBgNVBAoTDFRpYW5pIFNwaXJp" + "dDEUMBIGA1UECxMLSlVuaXQgdGVzdHMxGjAYBgNVBAMTEU1hc3NpbWlsaWFu" + "byBNYXNpMTEwLwYJKoZIhvcNAQkBFiJtYXNzaW1pbGlhbm8ubWFzaUB0aWFu" + "aS1zcGlyaXQuY29tMCAXDTEyMDEwMjA5MDAzNVoYDzIxOTEwNjA4MDkwMDM1" + "WjCBjzELMAkGA1UEBhMCQVQxEDAOBgNVBAgTB0F1c3RyaWExFTATBgNVBAoT" + "DFRpYW5pIFNwaXJpdDEUMBIGA1UECxMLSlVuaXQgVGVzdHMxDjAMBgNVBAMT" + "BWNlcnQxMTEwLwYJKoZIhvcNAQkBFiJtYXNzaW1pbGlhbm8ubWFzaUB0aWFu" + "aS1zcGlyaXQuY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDYHz8n" + "soeWpILn+5tK8XgJc3k5n0h0MOlRXLbZZVB7yuxKMBIZwl8kqqnehfqxX+hr" + "b2MXSCgKEstnVunJVPUGuNxnQ8Z0R9p1o/9gR0KTXmoJ+Epx5wdEofk4Phsi" + "MxjC8FVvt3sSnzal1/m0/9KntrPWksefumGm5XD3W43e5wIDAQABo3sweTAJ" + "BgNVHRMEAjAAMCwGCWCGSAGG+EIBDQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBD" + "ZXJ0aWZpY2F0ZTAdBgNVHQ4EFgQU8mTZGl0EFv6aHo3bup144d6wYW8wHwYD" + "VR0jBBgwFoAUdHG2RdrchT0PFcUBiIiYcy5hAA4wDQYJKoZIhvcNAQEFBQAD" + "gYEATcc52eo73zEA4wmbyPv0lRrmyAxrHvZGIHiKpM8bP38WUB39lgmS8J0S" + "1ioj21bosiakGj/gXnxlk8M8O+mm4zzpYjy8gqGXiUt20+j3bm7MJYM8ePcq" + "dG/kReNuLUbRgIA6b0T4o+0WCELhrd9IlTk5IBKjHIjsP/GR1h0t//kxggFb" + "MIIBVwIBATCBsjCBrDELMAkGA1UEBhMCQVQxEDAOBgNVBAgTB0F1c3RyaWEx" + "DzANBgNVBAcTBlZpZW5uYTEVMBMGA1UEChMMVGlhbmkgU3Bpcml0MRQwEgYD" + "VQQLEwtKVW5pdCB0ZXN0czEaMBgGA1UEAxMRTWFzc2ltaWxpYW5vIE1hc2kx" + "MTAvBgkqhkiG9w0BCQEWIm1hc3NpbWlsaWFuby5tYXNpQHRpYW5pLXNwaXJp" + "dC5jb20CAQEwCwYJYIZIAWUDBAIBMA0GCSqGSIb3DQEBAQUABIGAEthqA7FK" + "V1i+MzzS4zz4DxT4lwUYkWfHaDtZADUyTD5lnP3Pf+t/ScpBEGkEtI7hDqOO" + "zE0WfkBshTx5B/uxDibc/jqjQpSYSz5cvBTgpocIalbqsErOkDYF1QP6UgaV" + "ZoVGwvGYIuIrFgWqgk08NsPHVVjYseTEhUDwkI1KSxU="); byte[] successResp = Base64.decode( "MIIFnAoBAKCCBZUwggWRBgkrBgEFBQcwAQEEggWCMIIFfjCCARehgZ8wgZwx" + "CzAJBgNVBAYTAklOMRcwFQYDVQQIEw5BbmRocmEgcHJhZGVzaDESMBAGA1UE" + "BxMJSHlkZXJhYmFkMQwwCgYDVQQKEwNUQ1MxDDAKBgNVBAsTA0FUQzEeMBwG" + "A1UEAxMVVENTLUNBIE9DU1AgUmVzcG9uZGVyMSQwIgYJKoZIhvcNAQkBFhVv" + "Y3NwQHRjcy1jYS50Y3MuY28uaW4YDzIwMDMwNDAyMTIzNDU4WjBiMGAwOjAJ" + "BgUrDgMCGgUABBRs07IuoCWNmcEl1oHwIak1BPnX8QQUtGyl/iL9WJ1VxjxF" + "j0hAwJ/s1AcCAQKhERgPMjAwMjA4MjkwNzA5MjZaGA8yMDAzMDQwMjEyMzQ1" + "OFowDQYJKoZIhvcNAQEFBQADgYEAfbN0TCRFKdhsmvOdUoiJ+qvygGBzDxD/" + "VWhXYA+16AphHLIWNABR3CgHB3zWtdy2j7DJmQ/R7qKj7dUhWLSqclAiPgFt" + "QQ1YvSJAYfEIdyHkxv4NP0LSogxrumANcDyC9yt/W9yHjD2ICPBIqCsZLuLk" + "OHYi5DlwWe9Zm9VFwCGgggPMMIIDyDCCA8QwggKsoAMCAQICAQYwDQYJKoZI" + "hvcNAQEFBQAwgZQxFDASBgNVBAMTC1RDUy1DQSBPQ1NQMSYwJAYJKoZIhvcN" + "AQkBFhd0Y3MtY2FAdGNzLWNhLnRjcy5jby5pbjEMMAoGA1UEChMDVENTMQww" + "CgYDVQQLEwNBVEMxEjAQBgNVBAcTCUh5ZGVyYWJhZDEXMBUGA1UECBMOQW5k" + "aHJhIHByYWRlc2gxCzAJBgNVBAYTAklOMB4XDTAyMDgyOTA3MTE0M1oXDTAz" + "MDgyOTA3MTE0M1owgZwxCzAJBgNVBAYTAklOMRcwFQYDVQQIEw5BbmRocmEg" + "cHJhZGVzaDESMBAGA1UEBxMJSHlkZXJhYmFkMQwwCgYDVQQKEwNUQ1MxDDAK" + "BgNVBAsTA0FUQzEeMBwGA1UEAxMVVENTLUNBIE9DU1AgUmVzcG9uZGVyMSQw" + "IgYJKoZIhvcNAQkBFhVvY3NwQHRjcy1jYS50Y3MuY28uaW4wgZ8wDQYJKoZI" + "hvcNAQEBBQADgY0AMIGJAoGBAM+XWW4caMRv46D7L6Bv8iwtKgmQu0SAybmF" + "RJiz12qXzdvTLt8C75OdgmUomxp0+gW/4XlTPUqOMQWv463aZRv9Ust4f8MH" + "EJh4ekP/NS9+d8vEO3P40ntQkmSMcFmtA9E1koUtQ3MSJlcs441JjbgUaVnm" + "jDmmniQnZY4bU3tVAgMBAAGjgZowgZcwDAYDVR0TAQH/BAIwADALBgNVHQ8E" + "BAMCB4AwEwYDVR0lBAwwCgYIKwYBBQUHAwkwNgYIKwYBBQUHAQEEKjAoMCYG" + "CCsGAQUFBzABhhpodHRwOi8vMTcyLjE5LjQwLjExMDo3NzAwLzAtBgNVHR8E" + "JjAkMCKgIKAehhxodHRwOi8vMTcyLjE5LjQwLjExMC9jcmwuY3JsMA0GCSqG" + "SIb3DQEBBQUAA4IBAQB6FovM3B4VDDZ15o12gnADZsIk9fTAczLlcrmXLNN4" + "PgmqgnwF0Ymj3bD5SavDOXxbA65AZJ7rBNAguLUo+xVkgxmoBH7R2sBxjTCc" + "r07NEadxM3HQkt0aX5XYEl8eRoifwqYAI9h0ziZfTNes8elNfb3DoPPjqq6V" + "mMg0f0iMS4W8LjNPorjRB+kIosa1deAGPhq0eJ8yr0/s2QR2/WFD5P4aXc8I" + "KWleklnIImS3zqiPrq6tl2Bm8DZj7vXlTOwmraSQxUwzCKwYob1yGvNOUQTq" + "pG6jxn7jgDawHU1+WjWQe4Q34/pWeGLysxTraMa+Ug9kPe+jy/qRX2xwvKBZ"); public NewSignedDataTest(String name) { super(name); } public static void main(String args[]) throws Exception { if (Security.getProvider("BC") == null) { Security.addProvider(new BouncyCastleProvider()); } init(); junit.textui.TestRunner.run(NewSignedDataTest.class); } public static Test suite() throws Exception { init(); return new CMSTestSetup(new TestSuite(NewSignedDataTest.class)); } private static void init() throws Exception { if (!_initialised) { _initialised = true; if (Security.getProvider(BC) == null) { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); } _origDN = "O=Bouncy Castle, C=AU"; _origKP = CMSTestUtil.makeKeyPair(); _origCert = CMSTestUtil.makeCertificate(_origKP, _origDN, _origKP, _origDN); _signDN = "CN=Bob, OU=Sales, O=Bouncy Castle, C=AU"; _signKP = CMSTestUtil.makeKeyPair(); _signCert = CMSTestUtil.makeCertificate(_signKP, _signDN, _origKP, _origDN); _signGostKP = CMSTestUtil.makeGostKeyPair(); _signGostCert = CMSTestUtil.makeCertificate(_signGostKP, _signDN, _origKP, _origDN); _signDsaKP = CMSTestUtil.makeDsaKeyPair(); _signDsaCert = CMSTestUtil.makeCertificate(_signDsaKP, _signDN, _origKP, _origDN); _signEcDsaKP = CMSTestUtil.makeEcDsaKeyPair(); _signEcDsaCert = CMSTestUtil.makeCertificate(_signEcDsaKP, _signDN, _origKP, _origDN); _signEcGostKP = CMSTestUtil.makeEcGostKeyPair(); _signEcGostCert = CMSTestUtil.makeCertificate(_signEcGostKP, _signDN, _origKP, _origDN); _reciDN = "CN=Doug, OU=Sales, O=Bouncy Castle, C=AU"; _reciKP = CMSTestUtil.makeKeyPair(); _reciCert = CMSTestUtil.makeCertificate(_reciKP, _reciDN, _signKP, _signDN); _signCrl = CMSTestUtil.makeCrl(_signKP); } } private void verifyRSASignatures(CMSSignedData s, byte[] contentDigest) throws Exception { Store certStore = s.getCertificates(); SignerInformationStore signers = s.getSignerInfos(); Collection c = signers.getSigners(); Iterator it = c.iterator(); while (it.hasNext()) { SignerInformation signer = (SignerInformation)it.next(); Collection certCollection = certStore.getMatches(signer.getSID()); Iterator certIt = certCollection.iterator(); X509CertificateHolder cert = (X509CertificateHolder)certIt.next(); assertEquals(true, signer.verify(new BcRSASignerInfoVerifierBuilder(new DefaultCMSSignatureAlgorithmNameGenerator(), new DefaultSignatureAlgorithmIdentifierFinder(), new DefaultDigestAlgorithmIdentifierFinder(), new BcDigestCalculatorProvider()).build(cert))); if (contentDigest != null) { assertTrue(MessageDigest.isEqual(contentDigest, signer.getContentDigest())); } } } private void verifySignatures(CMSSignedData s, byte[] contentDigest) throws Exception { Store certStore = s.getCertificates(); Store crlStore = s.getCRLs(); SignerInformationStore signers = s.getSignerInfos(); Collection c = signers.getSigners(); Iterator it = c.iterator(); while (it.hasNext()) { SignerInformation signer = (SignerInformation)it.next(); Collection certCollection = certStore.getMatches(signer.getSID()); Iterator certIt = certCollection.iterator(); X509CertificateHolder cert = (X509CertificateHolder)certIt.next(); assertEquals(true, signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC).build(cert))); if (contentDigest != null) { assertTrue(MessageDigest.isEqual(contentDigest, signer.getContentDigest())); } } Collection certColl = certStore.getMatches(null); Collection crlColl = crlStore.getMatches(null); assertEquals(certColl.size(), s.getCertificates().getMatches(null).size()); assertEquals(crlColl.size(), s.getCRLs().getMatches(null).size()); } private void verifySignatures(CMSSignedData s) throws Exception { verifySignatures(s, null); } public void testDetachedVerification() throws Exception { byte[] data = "Hello World!".getBytes(); List certList = new ArrayList(); CMSTypedData msg = new CMSProcessableByteArray(data); certList.add(_origCert); certList.add(_signCert); Store certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); DigestCalculatorProvider digProvider = new JcaDigestCalculatorProviderBuilder().setProvider(BC).build(); JcaSignerInfoGeneratorBuilder signerInfoGeneratorBuilder = new JcaSignerInfoGeneratorBuilder(digProvider); ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(BC).build(_origKP.getPrivate()); ContentSigner md5Signer = new JcaContentSignerBuilder("MD5withRSA").setProvider(BC).build(_origKP.getPrivate()); gen.addSignerInfoGenerator(signerInfoGeneratorBuilder.build(sha1Signer, _origCert)); gen.addSignerInfoGenerator(signerInfoGeneratorBuilder.build(md5Signer, _origCert)); gen.addCertificates(certs); CMSSignedData s = gen.generate(msg); MessageDigest sha1 = MessageDigest.getInstance("SHA1", BC); MessageDigest md5 = MessageDigest.getInstance("MD5", BC); Map hashes = new HashMap(); byte[] sha1Hash = sha1.digest(data); byte[] md5Hash = md5.digest(data); hashes.put(CMSAlgorithm.SHA1, sha1Hash); hashes.put(CMSAlgorithm.MD5, md5Hash); s = new CMSSignedData(hashes, s.getEncoded()); verifySignatures(s, null); } public void testSHA1AndMD5WithRSAEncapsulatedRepeated() throws Exception { List certList = new ArrayList(); CMSTypedData msg = new CMSProcessableByteArray("Hello World!".getBytes()); certList.add(_origCert); certList.add(_signCert); Store certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder().setProvider(BC).build(); gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(digCalcProv).build(new JcaContentSignerBuilder("SHA1withRSA").setProvider(BC).build(_origKP.getPrivate()), _origCert)); gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(digCalcProv).build(new JcaContentSignerBuilder("MD5withRSA").setProvider(BC).build(_origKP.getPrivate()), _origCert)); gen.addCertificates(certs); CMSSignedData s = gen.generate(msg, true); ByteArrayInputStream bIn = new ByteArrayInputStream(s.getEncoded()); ASN1InputStream aIn = new ASN1InputStream(bIn); s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject())); certs = s.getCertificates(); SignerInformationStore signers = s.getSignerInfos(); assertEquals(2, signers.size()); Collection c = signers.getSigners(); Iterator it = c.iterator(); SignerId sid = null; while (it.hasNext()) { SignerInformation signer = (SignerInformation)it.next(); Collection certCollection = certs.getMatches(signer.getSID()); Iterator certIt = certCollection.iterator(); X509CertificateHolder cert = (X509CertificateHolder)certIt.next(); sid = signer.getSID(); assertEquals(true, signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC).build(cert))); // // check content digest // byte[] contentDigest = (byte[])gen.getGeneratedDigests().get(signer.getDigestAlgOID()); AttributeTable table = signer.getSignedAttributes(); Attribute hash = table.get(CMSAttributes.messageDigest); assertTrue(MessageDigest.isEqual(contentDigest, ((ASN1OctetString)hash.getAttrValues().getObjectAt(0)).getOctets())); } c = signers.getSigners(sid); assertEquals(2, c.size()); // // try using existing signer // gen = new CMSSignedDataGenerator(); gen.addSigners(s.getSignerInfos()); gen.addCertificates(s.getCertificates()); s = gen.generate(msg, true); bIn = new ByteArrayInputStream(s.getEncoded()); aIn = new ASN1InputStream(bIn); s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject())); certs = s.getCertificates(); signers = s.getSignerInfos(); c = signers.getSigners(); it = c.iterator(); assertEquals(2, c.size()); while (it.hasNext()) { SignerInformation signer = (SignerInformation)it.next(); Collection certCollection = certs.getMatches(signer.getSID()); Iterator certIt = certCollection.iterator(); X509CertificateHolder cert = (X509CertificateHolder)certIt.next(); assertEquals(true, signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC).build(cert))); } checkSignerStoreReplacement(s, signers); } public void testSHA1WithRSANoAttributes() throws Exception { List certList = new ArrayList(); CMSTypedData msg = new CMSProcessableByteArray("Hello world!".getBytes()); certList.add(_origCert); certList.add(_signCert); Store certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(BC).build(_origKP.getPrivate()); JcaSignerInfoGeneratorBuilder builder = new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider(BC).build()); builder.setDirectSignature(true); gen.addSignerInfoGenerator(builder.build(sha1Signer, _origCert)); gen.addCertificates(certs); CMSSignedData s = gen.generate(msg, false); // // compute expected content digest // MessageDigest md = MessageDigest.getInstance("SHA1", BC); verifySignatures(s, md.digest("Hello world!".getBytes())); } public void testSHA1WithRSANoAttributesSimple() throws Exception { List certList = new ArrayList(); CMSTypedData msg = new CMSProcessableByteArray("Hello world!".getBytes()); certList.add(_origCert); certList.add(_signCert); Store certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); JcaSimpleSignerInfoGeneratorBuilder builder = new JcaSimpleSignerInfoGeneratorBuilder().setProvider(BC).setDirectSignature(true); gen.addSignerInfoGenerator(builder.build("SHA1withRSA", _origKP.getPrivate(), _origCert)); gen.addCertificates(certs); CMSSignedData s = gen.generate(msg, false); // // compute expected content digest // MessageDigest md = MessageDigest.getInstance("SHA1", BC); verifySignatures(s, md.digest("Hello world!".getBytes())); } public void testSHA1WithRSAAndOtherRevocation() throws Exception { List certList = new ArrayList(); CMSTypedData msg = new CMSProcessableByteArray("Hello world!".getBytes()); certList.add(_origCert); certList.add(_signCert); Store certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(BC).build(_origKP.getPrivate()); gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider(BC).build()).build(sha1Signer, _origCert)); gen.addCertificates(certs); List otherInfo = new ArrayList(); OCSPResp response = new OCSPResp(successResp); otherInfo.add(response.toASN1Structure()); gen.addOtherRevocationInfo(CMSObjectIdentifiers.id_ri_ocsp_response, new CollectionStore(otherInfo)); CMSSignedData s; s = gen.generate(msg, false); // // check version // assertEquals(5, s.getVersion()); // // compute expected content digest // MessageDigest md = MessageDigest.getInstance("SHA1", BC); verifySignatures(s, md.digest("Hello world!".getBytes())); Store dataOtherInfo = s.getOtherRevocationInfo(CMSObjectIdentifiers.id_ri_ocsp_response); assertEquals(1, dataOtherInfo.getMatches(null).size()); OCSPResp dataResponse = new OCSPResp(OCSPResponse.getInstance(dataOtherInfo.getMatches(null).iterator().next())); assertEquals(response, dataResponse); } public void testSHA1WithRSAAndAttributeTableSimple() throws Exception { MessageDigest md = MessageDigest.getInstance("SHA1", BC); List certList = new ArrayList(); CMSTypedData msg = new CMSProcessableByteArray("Hello world!".getBytes()); certList.add(_origCert); certList.add(_signCert); Store certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); Attribute attr = new Attribute(CMSAttributes.messageDigest, new DERSet( new DEROctetString( md.digest("Hello world!".getBytes())))); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(attr); JcaSimpleSignerInfoGeneratorBuilder builder = new JcaSimpleSignerInfoGeneratorBuilder().setProvider(BC).setSignedAttributeGenerator(new DefaultSignedAttributeTableGenerator(new AttributeTable(v))); gen.addSignerInfoGenerator(builder.build("SHA1withRSA", _origKP.getPrivate(), _origCert)); gen.addCertificates(certs); CMSSignedData s = gen.generate(new CMSAbsentContent(), false); // // the signature is detached, so need to add msg before passing on // s = new CMSSignedData(msg, s.getEncoded()); // // compute expected content digest // verifySignatures(s, md.digest("Hello world!".getBytes())); verifyRSASignatures(s, md.digest("Hello world!".getBytes())); } public void testSHA1WithRSAAndAttributeTable() throws Exception { MessageDigest md = MessageDigest.getInstance("SHA1", BC); List certList = new ArrayList(); CMSTypedData msg = new CMSProcessableByteArray("Hello world!".getBytes()); certList.add(_origCert); certList.add(_signCert); Store certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); Attribute attr = new Attribute(CMSAttributes.messageDigest, new DERSet( new DEROctetString( md.digest("Hello world!".getBytes())))); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(attr); JcaSignerInfoGeneratorBuilder builder = new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider(BC).build()); builder.setSignedAttributeGenerator(new DefaultSignedAttributeTableGenerator(new AttributeTable(v))); ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(BC).build(_origKP.getPrivate()); gen.addSignerInfoGenerator(builder.build(sha1Signer, _origCert)); gen.addCertificates(certs); CMSSignedData s = gen.generate(new CMSAbsentContent(), false); // // the signature is detached, so need to add msg before passing on // s = new CMSSignedData(msg, s.getEncoded()); // // compute expected content digest // verifySignatures(s, md.digest("Hello world!".getBytes())); verifyRSASignatures(s, md.digest("Hello world!".getBytes())); } public void testLwSHA1WithRSAAndAttributeTable() throws Exception { MessageDigest md = MessageDigest.getInstance("SHA1", BC); List certList = new ArrayList(); CMSTypedData msg = new CMSProcessableByteArray("Hello world!".getBytes()); certList.add(_origCert); certList.add(_signCert); Store certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); Attribute attr = new Attribute(CMSAttributes.messageDigest, new DERSet( new DEROctetString( md.digest("Hello world!".getBytes())))); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(attr); AsymmetricKeyParameter privKey = PrivateKeyFactory.createKey(_origKP.getPrivate().getEncoded()); AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withRSA"); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); BcContentSignerBuilder contentSignerBuilder = new BcRSAContentSignerBuilder(sigAlgId, digAlgId); gen.addSignerInfoGenerator( new SignerInfoGeneratorBuilder(new BcDigestCalculatorProvider()) .setSignedAttributeGenerator(new DefaultSignedAttributeTableGenerator(new AttributeTable(v))) .build(contentSignerBuilder.build(privKey), new JcaX509CertificateHolder(_origCert))); gen.addCertificates(certs); CMSSignedData s = gen.generate(new CMSAbsentContent(), false); // // the signature is detached, so need to add msg before passing on // s = new CMSSignedData(msg, s.getEncoded()); // // compute expected content digest // verifySignatures(s, md.digest("Hello world!".getBytes())); verifyRSASignatures(s, md.digest("Hello world!".getBytes())); } public void testSHA1WithRSAEncapsulated() throws Exception { encapsulatedTest(_signKP, _signCert, "SHA1withRSA"); } public void testSHA1WithRSAEncapsulatedSubjectKeyID() throws Exception { subjectKeyIDTest(_signKP, _signCert, "SHA1withRSA"); } public void testSHA1WithRSAPSS() throws Exception { rsaPSSTest("SHA1withRSAandMGF1"); } public void testSHA224WithRSAPSS() throws Exception { rsaPSSTest("SHA224withRSAandMGF1"); } public void testSHA256WithRSAPSS() throws Exception { rsaPSSTest("SHA256withRSAandMGF1"); } public void testSHA384WithRSAPSS() throws Exception { rsaPSSTest("SHA384withRSAandMGF1"); } public void testSHA224WithRSAEncapsulated() throws Exception { encapsulatedTest(_signKP, _signCert, "SHA224withRSA"); } public void testSHA256WithRSAEncapsulated() throws Exception { encapsulatedTest(_signKP, _signCert, "SHA256withRSA"); } public void testRIPEMD128WithRSAEncapsulated() throws Exception { encapsulatedTest(_signKP, _signCert, "RIPEMD128withRSA"); } public void testRIPEMD160WithRSAEncapsulated() throws Exception { encapsulatedTest(_signKP, _signCert, "RIPEMD160withRSA"); } public void testRIPEMD256WithRSAEncapsulated() throws Exception { encapsulatedTest(_signKP, _signCert, "RIPEMD256withRSA"); } public void testECDSAEncapsulated() throws Exception { encapsulatedTest(_signEcDsaKP, _signEcDsaCert, "SHA1withECDSA"); } public void testECDSAEncapsulatedSubjectKeyID() throws Exception { subjectKeyIDTest(_signEcDsaKP, _signEcDsaCert, "SHA1withECDSA"); } public void testECDSASHA224Encapsulated() throws Exception { encapsulatedTest(_signEcDsaKP, _signEcDsaCert, "SHA224withECDSA"); } public void testECDSASHA256Encapsulated() throws Exception { encapsulatedTest(_signEcDsaKP, _signEcDsaCert, "SHA256withECDSA"); } public void testECDSASHA384Encapsulated() throws Exception { encapsulatedTest(_signEcDsaKP, _signEcDsaCert, "SHA384withECDSA"); } public void testECDSASHA512Encapsulated() throws Exception { encapsulatedTest(_signEcDsaKP, _signEcDsaCert, "SHA512withECDSA"); } public void testECDSASHA512EncapsulatedWithKeyFactoryAsEC() throws Exception { X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(_signEcDsaKP.getPublic().getEncoded()); PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(_signEcDsaKP.getPrivate().getEncoded()); KeyFactory keyFact = KeyFactory.getInstance("EC", BC); KeyPair kp = new KeyPair(keyFact.generatePublic(pubSpec), keyFact.generatePrivate(privSpec)); encapsulatedTest(kp, _signEcDsaCert, "SHA512withECDSA"); } public void testDSAEncapsulated() throws Exception { encapsulatedTest(_signDsaKP, _signDsaCert, "SHA1withDSA"); } public void testDSAEncapsulatedSubjectKeyID() throws Exception { subjectKeyIDTest(_signDsaKP, _signDsaCert, "SHA1withDSA"); } public void testGOST3411WithGOST3410Encapsulated() throws Exception { encapsulatedTest(_signGostKP, _signGostCert, "GOST3411withGOST3410"); } public void testGOST3411WithECGOST3410Encapsulated() throws Exception { encapsulatedTest(_signEcGostKP, _signEcGostCert, "GOST3411withECGOST3410"); } public void testGostNoAttributesEncapsulated() throws Exception { CMSSignedData data = new CMSSignedData(rawGost); Store certStore = data.getCertificates(); SignerInformationStore signers = data.getSignerInfos(); Collection c = signers.getSigners(); Iterator it = c.iterator(); while (it.hasNext()) { SignerInformation signer = (SignerInformation)it.next(); Collection certCollection = certStore.getMatches(signer.getSID()); Iterator certIt = certCollection.iterator(); X509CertificateHolder cert = (X509CertificateHolder)certIt.next(); assertEquals(true, signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert))); } } public void testSHA1WithRSACounterSignature() throws Exception { List certList = new ArrayList(); List crlList = new ArrayList(); CMSTypedData msg = new CMSProcessableByteArray("Hello World!".getBytes()); certList.add(_signCert); certList.add(_origCert); crlList.add(_signCrl); Store certStore = new JcaCertStore(certList); Store crlStore = new JcaCRLStore(crlList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(BC).build(_signKP.getPrivate()); gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider(BC).build()).build(sha1Signer, _signCert)); gen.addCertificates(certStore); gen.addCRLs(crlStore); CMSSignedData s = gen.generate(msg, true); SignerInformation origSigner = (SignerInformation)s.getSignerInfos().getSigners().toArray()[0]; SignerInformationStore counterSigners1 = gen.generateCounterSigners(origSigner); SignerInformationStore counterSigners2 = gen.generateCounterSigners(origSigner); SignerInformation signer1 = SignerInformation.addCounterSigners(origSigner, counterSigners1); SignerInformation signer2 = SignerInformation.addCounterSigners(signer1, counterSigners2); SignerInformationStore cs = signer2.getCounterSignatures(); Collection csSigners = cs.getSigners(); assertEquals(2, csSigners.size()); Iterator it = csSigners.iterator(); while (it.hasNext()) { SignerInformation cSigner = (SignerInformation)it.next(); Collection certCollection = certStore.getMatches(cSigner.getSID()); Iterator certIt = certCollection.iterator(); X509CertificateHolder cert = (X509CertificateHolder)certIt.next(); assertTrue(cSigner.isCounterSignature()); assertNull(cSigner.getSignedAttributes().get(PKCSObjectIdentifiers.pkcs_9_at_contentType)); assertEquals(true, cSigner.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC).build(cert))); } } public void testSHA1WithRSACounterSignatureAndVerifierProvider() throws Exception { List certList = new ArrayList(); List crlList = new ArrayList(); CMSTypedData msg = new CMSProcessableByteArray("Hello World!".getBytes()); certList.add(_signCert); certList.add(_origCert); crlList.add(_signCrl); Store certStore = new JcaCertStore(certList); Store crlStore = new JcaCRLStore(crlList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(BC).build(_signKP.getPrivate()); gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider(BC).build()).build(sha1Signer, _signCert)); gen.addCertificates(certStore); gen.addCRLs(crlStore); CMSSignedData s = gen.generate(msg, true); SignerInformationVerifierProvider vProv = new SignerInformationVerifierProvider() { public SignerInformationVerifier get(SignerId signerId) throws OperatorCreationException { return new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC).build(_signCert); } }; assertTrue(s.verifySignatures(vProv)); SignerInformation origSigner = (SignerInformation)s.getSignerInfos().getSigners().toArray()[0]; gen = new CMSSignedDataGenerator(); sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(BC).build(_origKP.getPrivate()); gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider(BC).build()).build(sha1Signer, _origCert)); SignerInformationStore counterSigners = gen.generateCounterSigners(origSigner); final SignerInformation signer1 = SignerInformation.addCounterSigners(origSigner, counterSigners); List signers = new ArrayList(); signers.add(signer1); s = CMSSignedData.replaceSigners(s, new SignerInformationStore(signers)); assertTrue(s.verifySignatures(vProv, true)); // provider can't handle counter sig assertFalse(s.verifySignatures(vProv, false)); vProv = new SignerInformationVerifierProvider() { public SignerInformationVerifier get(SignerId signerId) throws OperatorCreationException { if (_signCert.getSerialNumber().equals(signerId.getSerialNumber())) { return new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC).build(_signCert); } else if (_origCert.getSerialNumber().equals(signerId.getSerialNumber())) { return new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC).build(_origCert); } else { throw new IllegalStateException("no signerID matched"); } } }; // verify sig and counter sig. assertTrue(s.verifySignatures(vProv, false)); } private void rsaPSSTest(String signatureAlgorithmName) throws Exception { List certList = new ArrayList(); CMSTypedData msg = new CMSProcessableByteArray("Hello world!".getBytes()); certList.add(_origCert); certList.add(_signCert); Store certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithmName).setProvider(BC).build(_origKP.getPrivate()); JcaSignerInfoGeneratorBuilder siBuilder = new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider(BC).build()); siBuilder.setDirectSignature(true); gen.addSignerInfoGenerator(siBuilder.build(contentSigner, _origCert)); gen.addCertificates(certs); CMSSignedData s = gen.generate(msg, false); // // compute expected content digest // String digestName = signatureAlgorithmName.substring(0, signatureAlgorithmName.indexOf('w')); MessageDigest md = MessageDigest.getInstance(digestName, BC); verifySignatures(s, md.digest("Hello world!".getBytes())); } private void subjectKeyIDTest( KeyPair signaturePair, X509Certificate signatureCert, String signatureAlgorithm) throws Exception { List certList = new ArrayList(); List crlList = new ArrayList(); CMSTypedData msg = new CMSProcessableByteArray("Hello World!".getBytes()); certList.add(signatureCert); certList.add(_origCert); crlList.add(_signCrl); Store certStore = new JcaCertStore(certList); Store crlStore = new JcaCRLStore(crlList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithm).setProvider(BC).build(signaturePair.getPrivate()); gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider(BC).build()).build(contentSigner, CMSTestUtil.createSubjectKeyId(signatureCert.getPublicKey()).getKeyIdentifier())); gen.addCertificates(certStore); gen.addCRLs(crlStore); CMSSignedData s = gen.generate(msg, true); assertEquals(3, s.getVersion()); ByteArrayInputStream bIn = new ByteArrayInputStream(s.getEncoded()); ASN1InputStream aIn = new ASN1InputStream(bIn); s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject())); certStore = s.getCertificates(); SignerInformationStore signers = s.getSignerInfos(); Collection c = signers.getSigners(); Iterator it = c.iterator(); while (it.hasNext()) { SignerInformation signer = (SignerInformation)it.next(); Collection certCollection = certStore.getMatches(signer.getSID()); Iterator certIt = certCollection.iterator(); X509CertificateHolder cert = (X509CertificateHolder)certIt.next(); assertEquals(true, signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC).build(cert))); } // // check for CRLs // Collection crls = crlStore.getMatches(null); assertEquals(1, crls.size()); assertTrue(crls.contains(new JcaX509CRLHolder(_signCrl))); // // try using existing signer // gen = new CMSSignedDataGenerator(); gen.addSigners(s.getSignerInfos()); gen.addCertificates(s.getCertificates()); s = gen.generate(msg, true); bIn = new ByteArrayInputStream(s.getEncoded()); aIn = new ASN1InputStream(bIn); s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject())); certStore = s.getCertificates(); signers = s.getSignerInfos(); c = signers.getSigners(); it = c.iterator(); while (it.hasNext()) { SignerInformation signer = (SignerInformation)it.next(); Collection certCollection = certStore.getMatches(signer.getSID()); Iterator certIt = certCollection.iterator(); X509CertificateHolder cert = (X509CertificateHolder)certIt.next(); assertEquals(true, signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC).build(cert))); } checkSignerStoreReplacement(s, signers); } private void encapsulatedTest( KeyPair signaturePair, X509Certificate signatureCert, String signatureAlgorithm) throws Exception { List certList = new ArrayList(); List crlList = new ArrayList(); CMSTypedData msg = new CMSProcessableByteArray("Hello World!".getBytes()); certList.add(signatureCert); certList.add(_origCert); crlList.add(_signCrl); Store certs = new JcaCertStore(certList); Store crlStore = new JcaCRLStore(crlList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithm).setProvider(BC).build(signaturePair.getPrivate()); gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider(BC).build()).build(contentSigner, signatureCert)); gen.addCertificates(certs); CMSSignedData s = gen.generate(msg, true); ByteArrayInputStream bIn = new ByteArrayInputStream(s.getEncoded()); ASN1InputStream aIn = new ASN1InputStream(bIn); s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject())); certs = s.getCertificates(); SignerInformationStore signers = s.getSignerInfos(); Collection c = signers.getSigners(); Iterator it = c.iterator(); while (it.hasNext()) { SignerInformation signer = (SignerInformation)it.next(); Collection certCollection = certs.getMatches(signer.getSID()); Iterator certIt = certCollection.iterator(); X509CertificateHolder cert = (X509CertificateHolder)certIt.next(); assertEquals(true, signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC).build(cert))); } // // check signer information lookup // SignerId sid = new JcaSignerId(signatureCert); Collection collection = signers.getSigners(sid); assertEquals(1, collection.size()); assertTrue(collection.iterator().next() instanceof SignerInformation); // // check for CRLs // Collection crls = crlStore.getMatches(null); assertEquals(1, crls.size()); assertTrue(crls.contains(new JcaX509CRLHolder(_signCrl))); // // try using existing signer // gen = new CMSSignedDataGenerator(); gen.addSigners(s.getSignerInfos()); gen.addCertificates(s.getCertificates()); s = gen.generate(msg, true); bIn = new ByteArrayInputStream(s.getEncoded()); aIn = new ASN1InputStream(bIn); s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject())); certs = s.getCertificates(); signers = s.getSignerInfos(); c = signers.getSigners(); it = c.iterator(); while (it.hasNext()) { SignerInformation signer = (SignerInformation)it.next(); Collection certCollection = certs.getMatches(signer.getSID()); Iterator certIt = certCollection.iterator(); X509CertificateHolder cert = (X509CertificateHolder)certIt.next(); assertEquals(true, signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC).build(cert))); } checkSignerStoreReplacement(s, signers); } // // signerInformation store replacement test. // private void checkSignerStoreReplacement( CMSSignedData orig, SignerInformationStore signers) throws Exception { CMSSignedData s = CMSSignedData.replaceSigners(orig, signers); Store certs = s.getCertificates(); signers = s.getSignerInfos(); Collection c = signers.getSigners(); Iterator it = c.iterator(); while (it.hasNext()) { SignerInformation signer = (SignerInformation)it.next(); Collection certCollection = certs.getMatches(signer.getSID()); Iterator certIt = certCollection.iterator(); X509CertificateHolder cert = (X509CertificateHolder)certIt.next(); assertEquals(true, signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC).build(cert))); } } public void testUnsortedAttributes() throws Exception { CMSSignedData s = new CMSSignedData(new CMSProcessableByteArray(disorderedMessage), disorderedSet); Store certs = s.getCertificates(); SignerInformationStore signers = s.getSignerInfos(); Collection c = signers.getSigners(); Iterator it = c.iterator(); while (it.hasNext()) { SignerInformation signer = (SignerInformation)it.next(); Collection certCollection = certs.getMatches(signer.getSID()); Iterator certIt = certCollection.iterator(); X509CertificateHolder cert = (X509CertificateHolder)certIt.next(); assertEquals(false, signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC).build(cert))); Signature sig = Signature.getInstance("SHA1withRSA", BC); sig.initVerify(new JcaX509CertificateConverter().getCertificate(cert).getPublicKey()); sig.update(signer.toASN1Structure().getAuthenticatedAttributes().getEncoded()); assertEquals(true, sig.verify(signer.getSignature())); } } public void testNullContentWithSigner() throws Exception { List certList = new ArrayList(); certList.add(_origCert); certList.add(_signCert); Store certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(BC).build(_origKP.getPrivate()); gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider(BC).build()).build(sha1Signer, _origCert)); gen.addCertificates(certs); CMSSignedData s = gen.generate(new CMSAbsentContent(), false); ByteArrayInputStream bIn = new ByteArrayInputStream(s.getEncoded()); ASN1InputStream aIn = new ASN1InputStream(bIn); s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject())); verifySignatures(s); } public void testWithAttributeCertificate() throws Exception { List certList = new ArrayList(); CMSTypedData msg = new CMSProcessableByteArray("Hello World!".getBytes()); certList.add(_signDsaCert); Store certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); JcaSignerInfoGeneratorBuilder builder = new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider(BC).build()); ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(BC).build(_origKP.getPrivate()); gen.addSignerInfoGenerator(builder.build(sha1Signer, _origCert)); gen.addCertificates(certs); X509AttributeCertificateHolder attrCert = CMSTestUtil.getAttributeCertificate(); List attrList = new ArrayList(); attrList.add(new X509AttributeCertificateHolder(attrCert.getEncoded())); Store store = new CollectionStore(attrList); gen.addAttributeCertificates(store); CMSSignedData sd = gen.generate(msg); assertEquals(4, sd.getVersion()); store = sd.getAttributeCertificates(); Collection coll = store.getMatches(null); assertEquals(1, coll.size()); assertTrue(coll.contains(new X509AttributeCertificateHolder(attrCert.getEncoded()))); // // create new certstore // certList = new ArrayList(); certList.add(_origCert); certList.add(_signCert); certs = new JcaCertStore(certList); // // replace certs // sd = CMSSignedData.replaceCertificatesAndCRLs(sd, certs, null, null); verifySignatures(sd); } public void testCertStoreReplacement() throws Exception { List certList = new ArrayList(); CMSTypedData msg = new CMSProcessableByteArray("Hello World!".getBytes()); certList.add(_signDsaCert); Store certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(BC).build(_origKP.getPrivate()); gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider(BC).build()).build(sha1Signer, _origCert)); gen.addCertificates(certs); CMSSignedData sd = gen.generate(msg); // // create new certstore // certList = new ArrayList(); certList.add(_origCert); certList.add(_signCert); certs = new JcaCertStore(certList); // // replace certs // sd = CMSSignedData.replaceCertificatesAndCRLs(sd, certs, null, null); verifySignatures(sd); } public void testEncapsulatedCertStoreReplacement() throws Exception { List certList = new ArrayList(); CMSTypedData msg = new CMSProcessableByteArray("Hello World!".getBytes()); certList.add(_signDsaCert); Store certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(BC).build(_origKP.getPrivate()); gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider(BC).build()).build(sha1Signer, _origCert)); gen.addCertificates(certs); CMSSignedData sd = gen.generate(msg, true); // // create new certstore // certList = new ArrayList(); certList.add(_origCert); certList.add(_signCert); certs = new JcaCertStore(certList); // // replace certs // sd = CMSSignedData.replaceCertificatesAndCRLs(sd, certs, null, null); verifySignatures(sd); } public void testCertOrdering1() throws Exception { List certList = new ArrayList(); CMSTypedData msg = new CMSProcessableByteArray("Hello World!".getBytes()); certList.add(_origCert); certList.add(_signCert); certList.add(_signDsaCert); Store certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(BC).build(_origKP.getPrivate()); gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider(BC).build()).build(sha1Signer, _origCert)); gen.addCertificates(certs); CMSSignedData sd = gen.generate(msg, true); certs = sd.getCertificates(); Iterator it = certs.getMatches(null).iterator(); assertEquals(new JcaX509CertificateHolder(_origCert), it.next()); assertEquals(new JcaX509CertificateHolder(_signCert), it.next()); assertEquals(new JcaX509CertificateHolder(_signDsaCert), it.next()); } public void testCertOrdering2() throws Exception { List certList = new ArrayList(); CMSTypedData msg = new CMSProcessableByteArray("Hello World!".getBytes()); certList.add(_signCert); certList.add(_signDsaCert); certList.add(_origCert); Store certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(BC).build(_origKP.getPrivate()); gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider(BC).build()).build(sha1Signer, _origCert)); gen.addCertificates(certs); CMSSignedData sd = gen.generate(msg, true); certs = sd.getCertificates(); Iterator it = certs.getMatches(null).iterator(); assertEquals(new JcaX509CertificateHolder(_signCert), it.next()); assertEquals(new JcaX509CertificateHolder(_signDsaCert), it.next()); assertEquals(new JcaX509CertificateHolder(_origCert), it.next()); } public void testSignerStoreReplacement() throws Exception { List certList = new ArrayList(); CMSTypedData msg = new CMSProcessableByteArray("Hello World!".getBytes()); certList.add(_origCert); certList.add(_signCert); Store certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(BC).build(_origKP.getPrivate()); gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider(BC).build()).build(sha1Signer, _origCert)); gen.addCertificates(certs); CMSSignedData original = gen.generate(msg, true); // // create new Signer // gen = new CMSSignedDataGenerator(); ContentSigner sha224Signer = new JcaContentSignerBuilder("SHA224withRSA").setProvider(BC).build(_origKP.getPrivate()); gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider(BC).build()).build(sha224Signer, _origCert)); gen.addCertificates(certs); CMSSignedData newSD = gen.generate(msg, true); // // replace signer // CMSSignedData sd = CMSSignedData.replaceSigners(original, newSD.getSignerInfos()); SignerInformation signer = (SignerInformation)sd.getSignerInfos().getSigners().iterator().next(); assertEquals(CMSAlgorithm.SHA224.getId(), signer.getDigestAlgOID()); // we use a parser here as it requires the digests to be correct in the digest set, if it // isn't we'll get a NullPointerException CMSSignedDataParser sp = new CMSSignedDataParser(new JcaDigestCalculatorProviderBuilder().setProvider(BC).build(), sd.getEncoded()); sp.getSignedContent().drain(); verifySignatures(sp); } public void testEncapsulatedSamples() throws Exception { testSample("PSSSignDataSHA1Enc.sig"); testSample("PSSSignDataSHA256Enc.sig"); testSample("PSSSignDataSHA512Enc.sig"); } public void testSamples() throws Exception { testSample("PSSSignData.data", "PSSSignDataSHA1.sig"); testSample("PSSSignData.data", "PSSSignDataSHA256.sig"); testSample("PSSSignData.data", "PSSSignDataSHA512.sig"); } public void testNoAttrEncapsulatedSample() throws Exception { CMSSignedData s = new CMSSignedData(noAttrEncData); Store certStore = s.getCertificates(); assertNotNull(certStore); SignerInformationStore signers = s.getSignerInfos(); assertNotNull(signers); Collection c = signers.getSigners(); Iterator it = c.iterator(); while (it.hasNext()) { SignerInformation signer = (SignerInformation)it.next(); Collection certCollection = certStore.getMatches(signer.getSID()); Iterator certIt = certCollection.iterator(); X509CertificateHolder cert = (X509CertificateHolder)certIt.next(); if (!signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC).build(cert))) { fail("Verification FAILED! "); } } } public void testCounterSig() throws Exception { CMSSignedData sig = new CMSSignedData(getInput("counterSig.p7m")); SignerInformationStore ss = sig.getSignerInfos(); Collection signers = ss.getSigners(); SignerInformationStore cs = ((SignerInformation)signers.iterator().next()).getCounterSignatures(); Collection csSigners = cs.getSigners(); assertEquals(1, csSigners.size()); Iterator it = csSigners.iterator(); while (it.hasNext()) { SignerInformation cSigner = (SignerInformation)it.next(); Collection certCollection = sig.getCertificates().getMatches(cSigner.getSID()); Iterator certIt = certCollection.iterator(); X509CertificateHolder cert = (X509CertificateHolder)certIt.next(); assertTrue(cSigner.isCounterSignature()); assertNull(cSigner.getSignedAttributes().get(PKCSObjectIdentifiers.pkcs_9_at_contentType)); assertEquals(true, cSigner.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC).build(cert))); } verifySignatures(sig); } public void testCertificateManagement() throws Exception { CMSSignedDataGenerator sGen = new CMSSignedDataGenerator(); List certList = new ArrayList(); certList.add(_origCert); certList.add(_signCert); Store certs = new JcaCertStore(certList); sGen.addCertificates(certs); CMSSignedData sData = sGen.generate(new CMSAbsentContent(), true); CMSSignedData rsData = new CMSSignedData(sData.getEncoded()); assertEquals(2, rsData.getCertificates().getMatches(null).size()); } private void testSample(String sigName) throws Exception { CMSSignedData sig = new CMSSignedData(getInput(sigName)); verifySignatures(sig); } private void testSample(String messageName, String sigName) throws Exception { CMSSignedData sig = new CMSSignedData(new CMSProcessableByteArray(getInput(messageName)), getInput(sigName)); verifySignatures(sig); } private byte[] getInput(String name) throws IOException { return Streams.readAll(getClass().getResourceAsStream(name)); } public void testForMultipleCounterSignatures() throws Exception { CMSSignedData sd = new CMSSignedData(xtraCounterSig); for (Iterator sI = sd.getSignerInfos().getSigners().iterator(); sI.hasNext();) { SignerInformation sigI = (SignerInformation)sI.next(); SignerInformationStore counter = sigI.getCounterSignatures(); List sigs = new ArrayList(counter.getSigners()); assertEquals(2, sigs.size()); } } private void verifySignatures(CMSSignedDataParser sp) throws Exception { Store certs = sp.getCertificates(); SignerInformationStore signers = sp.getSignerInfos(); Collection c = signers.getSigners(); Iterator it = c.iterator(); while (it.hasNext()) { SignerInformation signer = (SignerInformation)it.next(); Collection certCollection = certs.getMatches(signer.getSID()); Iterator certIt = certCollection.iterator(); X509CertificateHolder cert = (X509CertificateHolder)certIt.next(); assertEquals(true, signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC).build(cert))); } } private class TestCMSSignatureAlgorithmNameGenerator extends DefaultCMSSignatureAlgorithmNameGenerator { void setDigestAlgorithmMapping(ASN1ObjectIdentifier oid, String algName) { super.setSigningDigestAlgorithmMapping(oid, algName); } void setEncryptionAlgorithmMapping(ASN1ObjectIdentifier oid, String algName) { super.setSigningEncryptionAlgorithmMapping(oid, algName); } } }
pkix/src/test/java/org/bouncycastle/cms/test/NewSignedDataTest.java
package org.bouncycastle.cms.test; import java.io.ByteArrayInputStream; import java.io.IOException; import java.security.KeyFactory; import java.security.KeyPair; import java.security.MessageDigest; import java.security.Security; import java.security.Signature; import java.security.cert.X509CRL; import java.security.cert.X509Certificate; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.DEROctetString; import org.bouncycastle.asn1.DERSet; import org.bouncycastle.asn1.cms.Attribute; import org.bouncycastle.asn1.cms.AttributeTable; import org.bouncycastle.asn1.cms.CMSAttributes; import org.bouncycastle.asn1.cms.CMSObjectIdentifiers; import org.bouncycastle.asn1.cms.ContentInfo; import org.bouncycastle.asn1.ocsp.OCSPResponse; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.cert.X509AttributeCertificateHolder; import org.bouncycastle.cert.X509CertificateHolder; import org.bouncycastle.cert.jcajce.JcaCRLStore; import org.bouncycastle.cert.jcajce.JcaCertStore; import org.bouncycastle.cert.jcajce.JcaX509CRLHolder; import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder; import org.bouncycastle.cert.ocsp.OCSPResp; import org.bouncycastle.cms.CMSAbsentContent; import org.bouncycastle.cms.CMSAlgorithm; import org.bouncycastle.cms.CMSProcessableByteArray; import org.bouncycastle.cms.CMSSignedData; import org.bouncycastle.cms.CMSSignedDataGenerator; import org.bouncycastle.cms.CMSSignedDataParser; import org.bouncycastle.cms.CMSTypedData; import org.bouncycastle.cms.DefaultCMSSignatureAlgorithmNameGenerator; import org.bouncycastle.cms.DefaultSignedAttributeTableGenerator; import org.bouncycastle.cms.SignerId; import org.bouncycastle.cms.SignerInfoGeneratorBuilder; import org.bouncycastle.cms.SignerInformation; import org.bouncycastle.cms.SignerInformationStore; import org.bouncycastle.cms.SignerInformationVerifier; import org.bouncycastle.cms.SignerInformationVerifierProvider; import org.bouncycastle.cms.bc.BcRSASignerInfoVerifierBuilder; import org.bouncycastle.cms.jcajce.JcaSignerId; import org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder; import org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoGeneratorBuilder; import org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder; import org.bouncycastle.crypto.Signer; import org.bouncycastle.crypto.params.AsymmetricKeyParameter; import org.bouncycastle.crypto.tls.SignatureAndHashAlgorithm; import org.bouncycastle.crypto.util.PrivateKeyFactory; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.operator.ContentSigner; import org.bouncycastle.operator.DefaultDigestAlgorithmIdentifierFinder; import org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder; import org.bouncycastle.operator.DigestCalculatorProvider; import org.bouncycastle.operator.OperatorCreationException; import org.bouncycastle.operator.bc.BcContentSignerBuilder; import org.bouncycastle.operator.bc.BcDigestCalculatorProvider; import org.bouncycastle.operator.bc.BcRSAContentSignerBuilder; import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder; import org.bouncycastle.util.CollectionStore; import org.bouncycastle.util.Store; import org.bouncycastle.util.encoders.Base64; import org.bouncycastle.util.io.Streams; public class NewSignedDataTest extends TestCase { private static final String BC = BouncyCastleProvider.PROVIDER_NAME; boolean DEBUG = true; private static String _origDN; private static KeyPair _origKP; private static X509Certificate _origCert; private static String _signDN; private static KeyPair _signKP; private static X509Certificate _signCert; private static KeyPair _signGostKP; private static X509Certificate _signGostCert; private static KeyPair _signEcDsaKP; private static X509Certificate _signEcDsaCert; private static KeyPair _signEcGostKP; private static X509Certificate _signEcGostCert; private static KeyPair _signDsaKP; private static X509Certificate _signDsaCert; private static String _reciDN; private static KeyPair _reciKP; private static X509Certificate _reciCert; private static X509CRL _signCrl; private static boolean _initialised = false; private byte[] disorderedMessage = Base64.decode( "SU9fc3RkaW5fdXNlZABfX2xpYmNfc3RhcnRfbWFpbgBnZXRob3N0aWQAX19n" + "bW9uX3M="); private byte[] disorderedSet = Base64.decode( "MIIYXQYJKoZIhvcNAQcCoIIYTjCCGEoCAQExCzAJBgUrDgMCGgUAMAsGCSqG" + "SIb3DQEHAaCCFqswggJUMIIBwKADAgECAgMMg6wwCgYGKyQDAwECBQAwbzEL" + "MAkGA1UEBhMCREUxPTA7BgNVBAoUNFJlZ3VsaWVydW5nc2JlaMhvcmRlIGbI" + "dXIgVGVsZWtvbW11bmlrYXRpb24gdW5kIFBvc3QxITAMBgcCggYBCgcUEwEx" + "MBEGA1UEAxQKNFItQ0EgMTpQTjAiGA8yMDAwMDMyMjA5NDM1MFoYDzIwMDQw" + "MTIxMTYwNDUzWjBvMQswCQYDVQQGEwJERTE9MDsGA1UEChQ0UmVndWxpZXJ1" + "bmdzYmVoyG9yZGUgZsh1ciBUZWxla29tbXVuaWthdGlvbiB1bmQgUG9zdDEh" + "MAwGBwKCBgEKBxQTATEwEQYDVQQDFAo1Ui1DQSAxOlBOMIGhMA0GCSqGSIb3" + "DQEBAQUAA4GPADCBiwKBgQCKHkFTJx8GmoqFTxEOxpK9XkC3NZ5dBEKiUv0I" + "fe3QMqeGMoCUnyJxwW0k2/53duHxtv2yHSZpFKjrjvE/uGwdOMqBMTjMzkFg" + "19e9JPv061wyADOucOIaNAgha/zFt9XUyrHF21knKCvDNExv2MYIAagkTKaj" + "LMAw0bu1J0FadQIFAMAAAAEwCgYGKyQDAwECBQADgYEAgFauXpoTLh3Z3pT/" + "3bhgrxO/2gKGZopWGSWSJPNwq/U3x2EuctOJurj+y2inTcJjespThflpN+7Q" + "nvsUhXU+jL2MtPlObU0GmLvWbi47cBShJ7KElcZAaxgWMBzdRGqTOdtMv+ev" + "2t4igGF/q71xf6J2c3pTLWr6P8s6tzLfOCMwggJDMIIBr6ADAgECAgQAuzyu" + "MAoGBiskAwMBAgUAMG8xCzAJBgNVBAYTAkRFMT0wOwYDVQQKFDRSZWd1bGll" + "cnVuZ3NiZWjIb3JkZSBmyHVyIFRlbGVrb21tdW5pa2F0aW9uIHVuZCBQb3N0" + "MSEwDAYHAoIGAQoHFBMBMTARBgNVBAMUCjVSLUNBIDE6UE4wIhgPMjAwMTA4" + "MjAwODA4MjBaGA8yMDA1MDgyMDA4MDgyMFowSzELMAkGA1UEBhMCREUxEjAQ" + "BgNVBAoUCVNpZ250cnVzdDEoMAwGBwKCBgEKBxQTATEwGAYDVQQDFBFDQSBT" + "SUdOVFJVU1QgMTpQTjCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAhV12" + "N2WhlR6f+3CXP57GrBM9la5Vnsu2b92zv5MZqQOPeEsYbZqDCFkYg1bSwsDE" + "XsGVQqXdQNAGUaapr/EUVVN+hNZ07GcmC1sPeQECgUkxDYjGi4ihbvzxlahj" + "L4nX+UTzJVBfJwXoIvJ+lMHOSpnOLIuEL3SRhBItvRECxN0CAwEAAaMSMBAw" + "DgYDVR0PAQH/BAQDAgEGMAoGBiskAwMBAgUAA4GBACDc9Pc6X8sK1cerphiV" + "LfFv4kpZb9ev4WPy/C6987Qw1SOTElhZAmxaJQBqmDHWlQ63wj1DEqswk7hG" + "LrvQk/iX6KXIn8e64uit7kx6DHGRKNvNGofPjr1WelGeGW/T2ZJKgmPDjCkf" + "sIKt2c3gwa2pDn4mmCz/DStUIqcPDbqLMIICVTCCAcGgAwIBAgIEAJ16STAK" + "BgYrJAMDAQIFADBvMQswCQYDVQQGEwJERTE9MDsGA1UEChQ0UmVndWxpZXJ1" + "bmdzYmVoyG9yZGUgZsh1ciBUZWxla29tbXVuaWthdGlvbiB1bmQgUG9zdDEh" + "MAwGBwKCBgEKBxQTATEwEQYDVQQDFAo1Ui1DQSAxOlBOMCIYDzIwMDEwMjAx" + "MTM0NDI1WhgPMjAwNTAzMjIwODU1NTFaMG8xCzAJBgNVBAYTAkRFMT0wOwYD" + "VQQKFDRSZWd1bGllcnVuZ3NiZWjIb3JkZSBmyHVyIFRlbGVrb21tdW5pa2F0" + "aW9uIHVuZCBQb3N0MSEwDAYHAoIGAQoHFBMBMTARBgNVBAMUCjZSLUNhIDE6" + "UE4wgaEwDQYJKoZIhvcNAQEBBQADgY8AMIGLAoGBAIOiqxUkzVyqnvthihnl" + "tsE5m1Xn5TZKeR/2MQPStc5hJ+V4yptEtIx+Fn5rOoqT5VEVWhcE35wdbPvg" + "JyQFn5msmhPQT/6XSGOlrWRoFummXN9lQzAjCj1sgTcmoLCVQ5s5WpCAOXFw" + "VWu16qndz3sPItn3jJ0F3Kh3w79NglvPAgUAwAAAATAKBgYrJAMDAQIFAAOB" + "gQBpSRdnDb6AcNVaXSmGo6+kVPIBhot1LzJOGaPyDNpGXxd7LV4tMBF1U7gr" + "4k1g9BO6YiMWvw9uiTZmn0CfV8+k4fWEuG/nmafRoGIuay2f+ILuT+C0rnp1" + "4FgMsEhuVNJJAmb12QV0PZII+UneyhAneZuQQzVUkTcVgYxogxdSOzCCAlUw" + "ggHBoAMCAQICBACdekowCgYGKyQDAwECBQAwbzELMAkGA1UEBhMCREUxPTA7" + "BgNVBAoUNFJlZ3VsaWVydW5nc2JlaMhvcmRlIGbIdXIgVGVsZWtvbW11bmlr" + "YXRpb24gdW5kIFBvc3QxITAMBgcCggYBCgcUEwExMBEGA1UEAxQKNlItQ2Eg" + "MTpQTjAiGA8yMDAxMDIwMTEzNDcwN1oYDzIwMDUwMzIyMDg1NTUxWjBvMQsw" + "CQYDVQQGEwJERTE9MDsGA1UEChQ0UmVndWxpZXJ1bmdzYmVoyG9yZGUgZsh1" + "ciBUZWxla29tbXVuaWthdGlvbiB1bmQgUG9zdDEhMAwGBwKCBgEKBxQTATEw" + "EQYDVQQDFAo1Ui1DQSAxOlBOMIGhMA0GCSqGSIb3DQEBAQUAA4GPADCBiwKB" + "gQCKHkFTJx8GmoqFTxEOxpK9XkC3NZ5dBEKiUv0Ife3QMqeGMoCUnyJxwW0k" + "2/53duHxtv2yHSZpFKjrjvE/uGwdOMqBMTjMzkFg19e9JPv061wyADOucOIa" + "NAgha/zFt9XUyrHF21knKCvDNExv2MYIAagkTKajLMAw0bu1J0FadQIFAMAA" + "AAEwCgYGKyQDAwECBQADgYEAV1yTi+2gyB7sUhn4PXmi/tmBxAfe5oBjDW8m" + "gxtfudxKGZ6l/FUPNcrSc5oqBYxKWtLmf3XX87LcblYsch617jtNTkMzhx9e" + "qxiD02ufcrxz2EVt0Akdqiz8mdVeqp3oLcNU/IttpSrcA91CAnoUXtDZYwb/" + "gdQ4FI9l3+qo/0UwggJVMIIBwaADAgECAgQAxIymMAoGBiskAwMBAgUAMG8x" + "CzAJBgNVBAYTAkRFMT0wOwYDVQQKFDRSZWd1bGllcnVuZ3NiZWjIb3JkZSBm" + "yHVyIFRlbGVrb21tdW5pa2F0aW9uIHVuZCBQb3N0MSEwDAYHAoIGAQoHFBMB" + "MTARBgNVBAMUCjZSLUNhIDE6UE4wIhgPMjAwMTEwMTUxMzMxNThaGA8yMDA1" + "MDYwMTA5NTIxN1owbzELMAkGA1UEBhMCREUxPTA7BgNVBAoUNFJlZ3VsaWVy" + "dW5nc2JlaMhvcmRlIGbIdXIgVGVsZWtvbW11bmlrYXRpb24gdW5kIFBvc3Qx" + "ITAMBgcCggYBCgcUEwExMBEGA1UEAxQKN1ItQ0EgMTpQTjCBoTANBgkqhkiG" + "9w0BAQEFAAOBjwAwgYsCgYEAiokD/j6lEP4FexF356OpU5teUpGGfUKjIrFX" + "BHc79G0TUzgVxqMoN1PWnWktQvKo8ETaugxLkP9/zfX3aAQzDW4Zki6x6GDq" + "fy09Agk+RJvhfbbIzRkV4sBBco0n73x7TfG/9NTgVr/96U+I+z/1j30aboM6" + "9OkLEhjxAr0/GbsCBQDAAAABMAoGBiskAwMBAgUAA4GBAHWRqRixt+EuqHhR" + "K1kIxKGZL2vZuakYV0R24Gv/0ZR52FE4ECr+I49o8FP1qiGSwnXB0SwjuH2S" + "iGiSJi+iH/MeY85IHwW1P5e+bOMvEOFhZhQXQixOD7totIoFtdyaj1XGYRef" + "0f2cPOjNJorXHGV8wuBk+/j++sxbd/Net3FtMIICVTCCAcGgAwIBAgIEAMSM" + "pzAKBgYrJAMDAQIFADBvMQswCQYDVQQGEwJERTE9MDsGA1UEChQ0UmVndWxp" + "ZXJ1bmdzYmVoyG9yZGUgZsh1ciBUZWxla29tbXVuaWthdGlvbiB1bmQgUG9z" + "dDEhMAwGBwKCBgEKBxQTATEwEQYDVQQDFAo3Ui1DQSAxOlBOMCIYDzIwMDEx" + "MDE1MTMzNDE0WhgPMjAwNTA2MDEwOTUyMTdaMG8xCzAJBgNVBAYTAkRFMT0w" + "OwYDVQQKFDRSZWd1bGllcnVuZ3NiZWjIb3JkZSBmyHVyIFRlbGVrb21tdW5p" + "a2F0aW9uIHVuZCBQb3N0MSEwDAYHAoIGAQoHFBMBMTARBgNVBAMUCjZSLUNh" + "IDE6UE4wgaEwDQYJKoZIhvcNAQEBBQADgY8AMIGLAoGBAIOiqxUkzVyqnvth" + "ihnltsE5m1Xn5TZKeR/2MQPStc5hJ+V4yptEtIx+Fn5rOoqT5VEVWhcE35wd" + "bPvgJyQFn5msmhPQT/6XSGOlrWRoFummXN9lQzAjCj1sgTcmoLCVQ5s5WpCA" + "OXFwVWu16qndz3sPItn3jJ0F3Kh3w79NglvPAgUAwAAAATAKBgYrJAMDAQIF" + "AAOBgQBi5W96UVDoNIRkCncqr1LLG9vF9SGBIkvFpLDIIbcvp+CXhlvsdCJl" + "0pt2QEPSDl4cmpOet+CxJTdTuMeBNXxhb7Dvualog69w/+K2JbPhZYxuVFZs" + "Zh5BkPn2FnbNu3YbJhE60aIkikr72J4XZsI5DxpZCGh6xyV/YPRdKSljFjCC" + "AlQwggHAoAMCAQICAwyDqzAKBgYrJAMDAQIFADBvMQswCQYDVQQGEwJERTE9" + "MDsGA1UEChQ0UmVndWxpZXJ1bmdzYmVoyG9yZGUgZsh1ciBUZWxla29tbXVu" + "aWthdGlvbiB1bmQgUG9zdDEhMAwGBwKCBgEKBxQTATEwEQYDVQQDFAo1Ui1D" + "QSAxOlBOMCIYDzIwMDAwMzIyMDk0MTI3WhgPMjAwNDAxMjExNjA0NTNaMG8x" + "CzAJBgNVBAYTAkRFMT0wOwYDVQQKFDRSZWd1bGllcnVuZ3NiZWjIb3JkZSBm" + "yHVyIFRlbGVrb21tdW5pa2F0aW9uIHVuZCBQb3N0MSEwDAYHAoIGAQoHFBMB" + "MTARBgNVBAMUCjRSLUNBIDE6UE4wgaEwDQYJKoZIhvcNAQEBBQADgY8AMIGL" + "AoGBAI8x26tmrFJanlm100B7KGlRemCD1R93PwdnG7svRyf5ZxOsdGrDszNg" + "xg6ouO8ZHQMT3NC2dH8TvO65Js+8bIyTm51azF6clEg0qeWNMKiiXbBXa+ph" + "hTkGbXiLYvACZ6/MTJMJ1lcrjpRF7BXtYeYMcEF6znD4pxOqrtbf9z5hAgUA" + "wAAAATAKBgYrJAMDAQIFAAOBgQB99BjSKlGPbMLQAgXlvA9jUsDNhpnVm3a1" + "YkfxSqS/dbQlYkbOKvCxkPGA9NBxisBM8l1zFynVjJoy++aysRmcnLY/sHaz" + "23BF2iU7WERy18H3lMBfYB6sXkfYiZtvQZcWaO48m73ZBySuiV3iXpb2wgs/" + "Cs20iqroAWxwq/W/9jCCAlMwggG/oAMCAQICBDsFZ9UwCgYGKyQDAwECBQAw" + "bzELMAkGA1UEBhMCREUxITAMBgcCggYBCgcUEwExMBEGA1UEAxQKNFItQ0Eg" + "MTpQTjE9MDsGA1UEChQ0UmVndWxpZXJ1bmdzYmVoyG9yZGUgZsh1ciBUZWxl" + "a29tbXVuaWthdGlvbiB1bmQgUG9zdDAiGA8xOTk5MDEyMTE3MzUzNFoYDzIw" + "MDQwMTIxMTYwMDAyWjBvMQswCQYDVQQGEwJERTE9MDsGA1UEChQ0UmVndWxp" + "ZXJ1bmdzYmVoyG9yZGUgZsh1ciBUZWxla29tbXVuaWthdGlvbiB1bmQgUG9z" + "dDEhMAwGBwKCBgEKBxQTATEwEQYDVQQDFAozUi1DQSAxOlBOMIGfMA0GCSqG" + "SIb3DQEBAQUAA4GNADCBiQKBgI4B557mbKQg/AqWBXNJhaT/6lwV93HUl4U8" + "u35udLq2+u9phns1WZkdM3gDfEpL002PeLfHr1ID/96dDYf04lAXQfombils" + "of1C1k32xOvxjlcrDOuPEMxz9/HDAQZA5MjmmYHAIulGI8Qg4Tc7ERRtg/hd" + "0QX0/zoOeXoDSEOBAgTAAAABMAoGBiskAwMBAgUAA4GBAIyzwfT3keHI/n2P" + "LrarRJv96mCohmDZNpUQdZTVjGu5VQjVJwk3hpagU0o/t/FkdzAjOdfEw8Ql" + "3WXhfIbNLv1YafMm2eWSdeYbLcbB5yJ1od+SYyf9+tm7cwfDAcr22jNRBqx8" + "wkWKtKDjWKkevaSdy99sAI8jebHtWz7jzydKMIID9TCCA16gAwIBAgICbMcw" + "DQYJKoZIhvcNAQEFBQAwSzELMAkGA1UEBhMCREUxEjAQBgNVBAoUCVNpZ250" + "cnVzdDEoMAwGBwKCBgEKBxQTATEwGAYDVQQDFBFDQSBTSUdOVFJVU1QgMTpQ" + "TjAeFw0wNDA3MzAxMzAyNDZaFw0wNzA3MzAxMzAyNDZaMDwxETAPBgNVBAMM" + "CFlhY29tOlBOMQ4wDAYDVQRBDAVZYWNvbTELMAkGA1UEBhMCREUxCjAIBgNV" + "BAUTATEwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAIWzLlYLQApocXIp" + "pgCCpkkOUVLgcLYKeOd6/bXAnI2dTHQqT2bv7qzfUnYvOqiNgYdF13pOYtKg" + "XwXMTNFL4ZOI6GoBdNs9TQiZ7KEWnqnr2945HYx7UpgTBclbOK/wGHuCdcwO" + "x7juZs1ZQPFG0Lv8RoiV9s6HP7POqh1sO0P/AgMBAAGjggH1MIIB8TCBnAYD" + "VR0jBIGUMIGRgBQcZzNghfnXoXRm8h1+VITC5caNRqFzpHEwbzELMAkGA1UE" + "BhMCREUxPTA7BgNVBAoUNFJlZ3VsaWVydW5nc2JlaMhvcmRlIGbIdXIgVGVs" + "ZWtvbW11bmlrYXRpb24gdW5kIFBvc3QxITAMBgcCggYBCgcUEwExMBEGA1UE" + "AxQKNVItQ0EgMTpQToIEALs8rjAdBgNVHQ4EFgQU2e5KAzkVuKaM9I5heXkz" + "bcAIuR8wDgYDVR0PAQH/BAQDAgZAMBIGA1UdIAQLMAkwBwYFKyQIAQEwfwYD" + "VR0fBHgwdjB0oCygKoYobGRhcDovL2Rpci5zaWdudHJ1c3QuZGUvbz1TaWdu" + "dHJ1c3QsYz1kZaJEpEIwQDEdMBsGA1UEAxMUQ1JMU2lnblNpZ250cnVzdDE6" + "UE4xEjAQBgNVBAoTCVNpZ250cnVzdDELMAkGA1UEBhMCREUwYgYIKwYBBQUH" + "AQEEVjBUMFIGCCsGAQUFBzABhkZodHRwOi8vZGlyLnNpZ250cnVzdC5kZS9T" + "aWdudHJ1c3QvT0NTUC9zZXJ2bGV0L2h0dHBHYXRld2F5LlBvc3RIYW5kbGVy" + "MBgGCCsGAQUFBwEDBAwwCjAIBgYEAI5GAQEwDgYHAoIGAQoMAAQDAQH/MA0G" + "CSqGSIb3DQEBBQUAA4GBAHn1m3GcoyD5GBkKUY/OdtD6Sj38LYqYCF+qDbJR" + "6pqUBjY2wsvXepUppEler+stH8mwpDDSJXrJyuzf7xroDs4dkLl+Rs2x+2tg" + "BjU+ABkBDMsym2WpwgA8LCdymmXmjdv9tULxY+ec2pjSEzql6nEZNEfrU8nt" + "ZCSCavgqW4TtMYIBejCCAXYCAQEwUTBLMQswCQYDVQQGEwJERTESMBAGA1UE" + "ChQJU2lnbnRydXN0MSgwDAYHAoIGAQoHFBMBMTAYBgNVBAMUEUNBIFNJR05U" + "UlVTVCAxOlBOAgJsxzAJBgUrDgMCGgUAoIGAMBgGCSqGSIb3DQEJAzELBgkq" + "hkiG9w0BBwEwIwYJKoZIhvcNAQkEMRYEFIYfhPoyfGzkLWWSSLjaHb4HQmaK" + "MBwGCSqGSIb3DQEJBTEPFw0wNTAzMjQwNzM4MzVaMCEGBSskCAYFMRgWFi92" + "YXIvZmlsZXMvdG1wXzEvdGVzdDEwDQYJKoZIhvcNAQEFBQAEgYA2IvA8lhVz" + "VD5e/itUxbFboKxeKnqJ5n/KuO/uBCl1N14+7Z2vtw1sfkIG+bJdp3OY2Cmn" + "mrQcwsN99Vjal4cXVj8t+DJzFG9tK9dSLvD3q9zT/GQ0kJXfimLVwCa4NaSf" + "Qsu4xtG0Rav6bCcnzabAkKuNNvKtH8amSRzk870DBg=="); public static byte[] xtraCounterSig = Base64.decode( "MIIR/AYJKoZIhvcNAQcCoIIR7TCCEekCAQExCzAJBgUrDgMCGgUAMBoGCSqG" + "SIb3DQEHAaANBAtIZWxsbyB3b3JsZKCCDnkwggTPMIIDt6ADAgECAgRDnYD3" + "MA0GCSqGSIb3DQEBBQUAMFgxCzAJBgNVBAYTAklUMRowGAYDVQQKExFJbi5U" + "ZS5TLkEuIFMucC5BLjEtMCsGA1UEAxMkSW4uVGUuUy5BLiAtIENlcnRpZmlj" + "YXRpb24gQXV0aG9yaXR5MB4XDTA4MDkxMjExNDMxMloXDTEwMDkxMjExNDMx" + "MlowgdgxCzAJBgNVBAYTAklUMSIwIAYDVQQKDBlJbnRlc2EgUy5wLkEuLzA1" + "MjYyODkwMDE0MSowKAYDVQQLDCFCdXNpbmVzcyBDb2xsYWJvcmF0aW9uICYg" + "U2VjdXJpdHkxHjAcBgNVBAMMFU1BU1NJTUlMSUFOTyBaSUNDQVJESTERMA8G" + "A1UEBAwIWklDQ0FSREkxFTATBgNVBCoMDE1BU1NJTUlMSUFOTzEcMBoGA1UE" + "BRMTSVQ6WkNDTVNNNzZIMTRMMjE5WTERMA8GA1UELhMIMDAwMDI1ODUwgaAw" + "DQYJKoZIhvcNAQEBBQADgY4AMIGKAoGBALeJTjmyFgx1SIP6c2AuB/kuyHo5" + "j/prKELTALsFDimre/Hxr3wOSet1TdQfFzU8Lu+EJqgfV9cV+cI1yeH1rZs7" + "lei7L3tX/VR565IywnguX5xwvteASgWZr537Fkws50bvTEMyYOj1Tf3FZvZU" + "z4n4OD39KI4mfR9i1eEVIxR3AgQAizpNo4IBoTCCAZ0wHQYDVR0RBBYwFIES" + "emljY2FyZGlAaW50ZXNhLml0MC8GCCsGAQUFBwEDBCMwITAIBgYEAI5GAQEw" + "CwYGBACORgEDAgEUMAgGBgQAjkYBBDBZBgNVHSAEUjBQME4GBgQAizABATBE" + "MEIGCCsGAQUFBwIBFjZodHRwOi8vZS10cnVzdGNvbS5pbnRlc2EuaXQvY2Ff" + "cHViYmxpY2EvQ1BTX0lOVEVTQS5odG0wDgYDVR0PAQH/BAQDAgZAMIGDBgNV" + "HSMEfDB6gBQZCQOW0bjFWBt+EORuxPagEgkQqKFcpFowWDELMAkGA1UEBhMC" + "SVQxGjAYBgNVBAoTEUluLlRlLlMuQS4gUy5wLkEuMS0wKwYDVQQDEyRJbi5U" + "ZS5TLkEuIC0gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHmCBDzRARMwOwYDVR0f" + "BDQwMjAwoC6gLIYqaHR0cDovL2UtdHJ1c3Rjb20uaW50ZXNhLml0L0NSTC9J" + "TlRFU0EuY3JsMB0GA1UdDgQWBBTf5ItL8KmQh541Dxt7YxcWI1254TANBgkq" + "hkiG9w0BAQUFAAOCAQEAgW+uL1CVWQepbC/wfCmR6PN37Sueb4xiKQj2mTD5" + "UZ5KQjpivy/Hbuf0NrfKNiDEhAvoHSPC31ebGiKuTMFNyZPHfPEUnyYGSxea" + "2w837aXJFr6utPNQGBRi89kH90sZDlXtOSrZI+AzJJn5QK3F9gjcayU2NZXQ" + "MJgRwYmFyn2w4jtox+CwXPQ9E5XgxiMZ4WDL03cWVXDLX00EOJwnDDMUNTRI" + "m9Zv+4SKTNlfFbi9UTBqWBySkDzAelsfB2U61oqc2h1xKmCtkGMmN9iZT+Qz" + "ZC/vaaT+hLEBFGAH2gwFrYc4/jTBKyBYeU1vsAxsibIoTs1Apgl6MH75qPDL" + "BzCCBM8wggO3oAMCAQICBEOdgPcwDQYJKoZIhvcNAQEFBQAwWDELMAkGA1UE" + "BhMCSVQxGjAYBgNVBAoTEUluLlRlLlMuQS4gUy5wLkEuMS0wKwYDVQQDEyRJ" + "bi5UZS5TLkEuIC0gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDgwOTEy" + "MTE0MzEyWhcNMTAwOTEyMTE0MzEyWjCB2DELMAkGA1UEBhMCSVQxIjAgBgNV" + "BAoMGUludGVzYSBTLnAuQS4vMDUyNjI4OTAwMTQxKjAoBgNVBAsMIUJ1c2lu" + "ZXNzIENvbGxhYm9yYXRpb24gJiBTZWN1cml0eTEeMBwGA1UEAwwVTUFTU0lN" + "SUxJQU5PIFpJQ0NBUkRJMREwDwYDVQQEDAhaSUNDQVJESTEVMBMGA1UEKgwM" + "TUFTU0lNSUxJQU5PMRwwGgYDVQQFExNJVDpaQ0NNU003NkgxNEwyMTlZMREw" + "DwYDVQQuEwgwMDAwMjU4NTCBoDANBgkqhkiG9w0BAQEFAAOBjgAwgYoCgYEA" + "t4lOObIWDHVIg/pzYC4H+S7IejmP+msoQtMAuwUOKat78fGvfA5J63VN1B8X" + "NTwu74QmqB9X1xX5wjXJ4fWtmzuV6Lsve1f9VHnrkjLCeC5fnHC+14BKBZmv" + "nfsWTCznRu9MQzJg6PVN/cVm9lTPifg4Pf0ojiZ9H2LV4RUjFHcCBACLOk2j" + "ggGhMIIBnTAdBgNVHREEFjAUgRJ6aWNjYXJkaUBpbnRlc2EuaXQwLwYIKwYB" + "BQUHAQMEIzAhMAgGBgQAjkYBATALBgYEAI5GAQMCARQwCAYGBACORgEEMFkG" + "A1UdIARSMFAwTgYGBACLMAEBMEQwQgYIKwYBBQUHAgEWNmh0dHA6Ly9lLXRy" + "dXN0Y29tLmludGVzYS5pdC9jYV9wdWJibGljYS9DUFNfSU5URVNBLmh0bTAO" + "BgNVHQ8BAf8EBAMCBkAwgYMGA1UdIwR8MHqAFBkJA5bRuMVYG34Q5G7E9qAS" + "CRCooVykWjBYMQswCQYDVQQGEwJJVDEaMBgGA1UEChMRSW4uVGUuUy5BLiBT" + "LnAuQS4xLTArBgNVBAMTJEluLlRlLlMuQS4gLSBDZXJ0aWZpY2F0aW9uIEF1" + "dGhvcml0eYIEPNEBEzA7BgNVHR8ENDAyMDCgLqAshipodHRwOi8vZS10cnVz" + "dGNvbS5pbnRlc2EuaXQvQ1JML0lOVEVTQS5jcmwwHQYDVR0OBBYEFN/ki0vw" + "qZCHnjUPG3tjFxYjXbnhMA0GCSqGSIb3DQEBBQUAA4IBAQCBb64vUJVZB6ls" + "L/B8KZHo83ftK55vjGIpCPaZMPlRnkpCOmK/L8du5/Q2t8o2IMSEC+gdI8Lf" + "V5saIq5MwU3Jk8d88RSfJgZLF5rbDzftpckWvq6081AYFGLz2Qf3SxkOVe05" + "Ktkj4DMkmflArcX2CNxrJTY1ldAwmBHBiYXKfbDiO2jH4LBc9D0TleDGIxnh" + "YMvTdxZVcMtfTQQ4nCcMMxQ1NEib1m/7hIpM2V8VuL1RMGpYHJKQPMB6Wx8H" + "ZTrWipzaHXEqYK2QYyY32JlP5DNkL+9ppP6EsQEUYAfaDAWthzj+NMErIFh5" + "TW+wDGyJsihOzUCmCXowfvmo8MsHMIIEzzCCA7egAwIBAgIEQ52A9zANBgkq" + "hkiG9w0BAQUFADBYMQswCQYDVQQGEwJJVDEaMBgGA1UEChMRSW4uVGUuUy5B" + "LiBTLnAuQS4xLTArBgNVBAMTJEluLlRlLlMuQS4gLSBDZXJ0aWZpY2F0aW9u" + "IEF1dGhvcml0eTAeFw0wODA5MTIxMTQzMTJaFw0xMDA5MTIxMTQzMTJaMIHY" + "MQswCQYDVQQGEwJJVDEiMCAGA1UECgwZSW50ZXNhIFMucC5BLi8wNTI2Mjg5" + "MDAxNDEqMCgGA1UECwwhQnVzaW5lc3MgQ29sbGFib3JhdGlvbiAmIFNlY3Vy" + "aXR5MR4wHAYDVQQDDBVNQVNTSU1JTElBTk8gWklDQ0FSREkxETAPBgNVBAQM" + "CFpJQ0NBUkRJMRUwEwYDVQQqDAxNQVNTSU1JTElBTk8xHDAaBgNVBAUTE0lU" + "OlpDQ01TTTc2SDE0TDIxOVkxETAPBgNVBC4TCDAwMDAyNTg1MIGgMA0GCSqG" + "SIb3DQEBAQUAA4GOADCBigKBgQC3iU45shYMdUiD+nNgLgf5Lsh6OY/6ayhC" + "0wC7BQ4pq3vx8a98DknrdU3UHxc1PC7vhCaoH1fXFfnCNcnh9a2bO5Xouy97" + "V/1UeeuSMsJ4Ll+ccL7XgEoFma+d+xZMLOdG70xDMmDo9U39xWb2VM+J+Dg9" + "/SiOJn0fYtXhFSMUdwIEAIs6TaOCAaEwggGdMB0GA1UdEQQWMBSBEnppY2Nh" + "cmRpQGludGVzYS5pdDAvBggrBgEFBQcBAwQjMCEwCAYGBACORgEBMAsGBgQA" + "jkYBAwIBFDAIBgYEAI5GAQQwWQYDVR0gBFIwUDBOBgYEAIswAQEwRDBCBggr" + "BgEFBQcCARY2aHR0cDovL2UtdHJ1c3Rjb20uaW50ZXNhLml0L2NhX3B1YmJs" + "aWNhL0NQU19JTlRFU0EuaHRtMA4GA1UdDwEB/wQEAwIGQDCBgwYDVR0jBHww" + "eoAUGQkDltG4xVgbfhDkbsT2oBIJEKihXKRaMFgxCzAJBgNVBAYTAklUMRow" + "GAYDVQQKExFJbi5UZS5TLkEuIFMucC5BLjEtMCsGA1UEAxMkSW4uVGUuUy5B" + "LiAtIENlcnRpZmljYXRpb24gQXV0aG9yaXR5ggQ80QETMDsGA1UdHwQ0MDIw" + "MKAuoCyGKmh0dHA6Ly9lLXRydXN0Y29tLmludGVzYS5pdC9DUkwvSU5URVNB" + "LmNybDAdBgNVHQ4EFgQU3+SLS/CpkIeeNQ8be2MXFiNdueEwDQYJKoZIhvcN" + "AQEFBQADggEBAIFvri9QlVkHqWwv8Hwpkejzd+0rnm+MYikI9pkw+VGeSkI6" + "Yr8vx27n9Da3yjYgxIQL6B0jwt9XmxoirkzBTcmTx3zxFJ8mBksXmtsPN+2l" + "yRa+rrTzUBgUYvPZB/dLGQ5V7Tkq2SPgMySZ+UCtxfYI3GslNjWV0DCYEcGJ" + "hcp9sOI7aMfgsFz0PROV4MYjGeFgy9N3FlVwy19NBDicJwwzFDU0SJvWb/uE" + "ikzZXxW4vVEwalgckpA8wHpbHwdlOtaKnNodcSpgrZBjJjfYmU/kM2Qv72mk" + "/oSxARRgB9oMBa2HOP40wSsgWHlNb7AMbImyKE7NQKYJejB++ajwywcxggM8" + "MIIDOAIBATBgMFgxCzAJBgNVBAYTAklUMRowGAYDVQQKExFJbi5UZS5TLkEu" + "IFMucC5BLjEtMCsGA1UEAxMkSW4uVGUuUy5BLiAtIENlcnRpZmljYXRpb24g" + "QXV0aG9yaXR5AgRDnYD3MAkGBSsOAwIaBQAwDQYJKoZIhvcNAQEBBQAEgYB+" + "lH2cwLqc91mP8prvgSV+RRzk13dJdZvdoVjgQoFrPhBiZCNIEoHvIhMMA/sM" + "X6euSRZk7EjD24FasCEGYyd0mJVLEy6TSPmuW+wWz/28w3a6IWXBGrbb/ild" + "/CJMkPgLPGgOVD1WDwiNKwfasiQSFtySf5DPn3jFevdLeMmEY6GCAjIwggEV" + "BgkqhkiG9w0BCQYxggEGMIIBAgIBATBgMFgxCzAJBgNVBAYTAklUMRowGAYD" + "VQQKExFJbi5UZS5TLkEuIFMucC5BLjEtMCsGA1UEAxMkSW4uVGUuUy5BLiAt" + "IENlcnRpZmljYXRpb24gQXV0aG9yaXR5AgRDnYD3MAkGBSsOAwIaBQAwDQYJ" + "KoZIhvcNAQEBBQAEgYBHlOULfT5GDigIvxP0qZOy8VbpntmzaPF55VV4buKV" + "35J+uHp98gXKp0LrHM69V5IRKuyuQzHHFBqsXxsRI9o6KoOfgliD9Xc+BeMg" + "dKzQhBhBYoFREq8hQM0nSbqDNHYAQyNHMzUA/ZQUO5dlFuH8Dw3iDYAhNtfd" + "PrlchKJthDCCARUGCSqGSIb3DQEJBjGCAQYwggECAgEBMGAwWDELMAkGA1UE" + "BhMCSVQxGjAYBgNVBAoTEUluLlRlLlMuQS4gUy5wLkEuMS0wKwYDVQQDEyRJ" + "bi5UZS5TLkEuIC0gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkCBEOdgPcwCQYF" + "Kw4DAhoFADANBgkqhkiG9w0BAQEFAASBgEeU5Qt9PkYOKAi/E/Spk7LxVume" + "2bNo8XnlVXhu4pXfkn64en3yBcqnQusczr1XkhEq7K5DMccUGqxfGxEj2joq" + "g5+CWIP1dz4F4yB0rNCEGEFigVESryFAzSdJuoM0dgBDI0czNQD9lBQ7l2UW" + "4fwPDeINgCE2190+uVyEom2E"); byte[] noSignedAttrSample2 = Base64.decode( "MIIIlAYJKoZIhvcNAQcCoIIIhTCCCIECAQExCzAJBgUrDgMCGgUAMAsGCSqG" + "SIb3DQEHAaCCB3UwggOtMIIDa6ADAgECAgEzMAsGByqGSM44BAMFADCBkDEL" + "MAkGA1UEBhMCVVMxCzAJBgNVBAgTAkNBMRIwEAYDVQQHEwlQYWxvIEFsdG8x" + "HTAbBgNVBAoTFFN1biBNaWNyb3N5c3RlbXMgSW5jMSMwIQYDVQQLExpKYXZh" + "IFNvZnR3YXJlIENvZGUgU2lnbmluZzEcMBoGA1UEAxMTSkNFIENvZGUgU2ln" + "bmluZyBDQTAeFw0wMTA1MjkxNjQ3MTFaFw0wNjA1MjgxNjQ3MTFaMG4xHTAb" + "BgNVBAoTFFN1biBNaWNyb3N5c3RlbXMgSW5jMSMwIQYDVQQLExpKYXZhIFNv" + "ZnR3YXJlIENvZGUgU2lnbmluZzEoMCYGA1UEAxMfVGhlIExlZ2lvbiBvZiB0" + "aGUgQm91bmN5IENhc3RsZTCCAbcwggEsBgcqhkjOOAQBMIIBHwKBgQD9f1OB" + "HXUSKVLfSpwu7OTn9hG3UjzvRADDHj+AtlEmaUVdQCJR+1k9jVj6v8X1ujD2" + "y5tVbNeBO4AdNG/yZmC3a5lQpaSfn+gEexAiwk+7qdf+t8Yb+DtX58aophUP" + "BPuD9tPFHsMCNVQTWhaRMvZ1864rYdcq7/IiAxmd0UgBxwIVAJdgUI8VIwvM" + "spK5gqLrhAvwWBz1AoGBAPfhoIXWmz3ey7yrXDa4V7l5lK+7+jrqgvlXTAs9" + "B4JnUVlXjrrUWU/mcQcQgYC0SRZxI+hMKBYTt88JMozIpuE8FnqLVHyNKOCj" + "rh4rs6Z1kW6jfwv6ITVi8ftiegEkO8yk8b6oUZCJqIPf4VrlnwaSi2ZegHtV" + "JWQBTDv+z0kqA4GEAAKBgBWry/FCAZ6miyy39+ftsa+h9lxoL+JtV0MJcUyQ" + "E4VAhpAwWb8vyjba9AwOylYQTktHX5sAkFvjBiU0LOYDbFSTVZSHMRJgfjxB" + "SHtICjOEvr1BJrrOrdzqdxcOUge5n7El124BCrv91x5Ol8UTwtiO9LrRXF/d" + "SyK+RT5n1klRo3YwdDARBglghkgBhvhCAQEEBAMCAIcwDgYDVR0PAQH/BAQD" + "AgHGMB0GA1UdDgQWBBQwMY4NRcco1AO3w1YsokfDLVseEjAPBgNVHRMBAf8E" + "BTADAQH/MB8GA1UdIwQYMBaAFGXi9IbJ007wkU5Yomr12HhamsGmMAsGByqG" + "SM44BAMFAAMvADAsAhRmigTu6QV0sTfEkVljgij/hhdVfAIUQZvMxAnIHc30" + "y/u0C1T5UEG9glUwggPAMIIDfqADAgECAgEQMAsGByqGSM44BAMFADCBkDEL" + "MAkGA1UEBhMCVVMxCzAJBgNVBAgTAkNBMRIwEAYDVQQHEwlQYWxvIEFsdG8x" + "HTAbBgNVBAoTFFN1biBNaWNyb3N5c3RlbXMgSW5jMSMwIQYDVQQLExpKYXZh" + "IFNvZnR3YXJlIENvZGUgU2lnbmluZzEcMBoGA1UEAxMTSkNFIENvZGUgU2ln" + "bmluZyBDQTAeFw0wMTA0MjUwNzAwMDBaFw0yMDA0MjUwNzAwMDBaMIGQMQsw" + "CQYDVQQGEwJVUzELMAkGA1UECBMCQ0ExEjAQBgNVBAcTCVBhbG8gQWx0bzEd" + "MBsGA1UEChMUU3VuIE1pY3Jvc3lzdGVtcyBJbmMxIzAhBgNVBAsTGkphdmEg" + "U29mdHdhcmUgQ29kZSBTaWduaW5nMRwwGgYDVQQDExNKQ0UgQ29kZSBTaWdu" + "aW5nIENBMIIBtzCCASwGByqGSM44BAEwggEfAoGBAOuvNwQeylEeaV2w8o/2" + "tUkfxqSZBdcpv3S3avUZ2B7kG/gKAZqY/3Cr4kpWhmxTs/zhyIGMMfDE87CL" + "5nAG7PdpaNuDTHIpiSk2F1w7SgegIAIqRpdRHXDICBgLzgxum3b3BePn+9Nh" + "eeFgmiSNBpWDPFEg4TDPOFeCphpyDc7TAhUAhCVF4bq5qWKreehbMLiJaxv/" + "e3UCgYEAq8l0e3Tv7kK1alNNO92QBnJokQ8LpCl2LlU71a5NZVx+KjoEpmem" + "0HGqpde34sFyDaTRqh6SVEwgAAmisAlBGTMAssNcrkL4sYvKfJbYEH83RFuq" + "zHjI13J2N2tAmahVZvqoAx6LShECactMuCUGHKB30sms0j3pChD6dnC3+9wD" + "gYQAAoGALQmYXKy4nMeZfu4gGSo0kPnXq6uu3WtylQ1m+O8nj0Sy7ShEx/6v" + "sKYnbwBnRYJbB6hWVjvSKVFhXmk51y50dxLPGUr1LcjLcmHETm/6R0M/FLv6" + "vBhmKMLZZot6LS/CYJJLFP5YPiF/aGK+bEhJ+aBLXoWdGRD5FUVRG3HU9wuj" + "ZjBkMBEGCWCGSAGG+EIBAQQEAwIABzAPBgNVHRMBAf8EBTADAQH/MB8GA1Ud" + "IwQYMBaAFGXi9IbJ007wkU5Yomr12HhamsGmMB0GA1UdDgQWBBRl4vSGydNO" + "8JFOWKJq9dh4WprBpjALBgcqhkjOOAQDBQADLwAwLAIUKvfPPJdd+Xi2CNdB" + "tNkNRUzktJwCFEXNdWkOIfod1rMpsun3Mx0z/fxJMYHoMIHlAgEBMIGWMIGQ" + "MQswCQYDVQQGEwJVUzELMAkGA1UECBMCQ0ExEjAQBgNVBAcTCVBhbG8gQWx0" + "bzEdMBsGA1UEChMUU3VuIE1pY3Jvc3lzdGVtcyBJbmMxIzAhBgNVBAsTGkph" + "dmEgU29mdHdhcmUgQ29kZSBTaWduaW5nMRwwGgYDVQQDExNKQ0UgQ29kZSBT" + "aWduaW5nIENBAgEzMAkGBSsOAwIaBQAwCwYHKoZIzjgEAQUABC8wLQIVAIGV" + "khm+kbV4a/+EP45PHcq0hIViAhR4M9os6IrJnoEDS3Y3l7O6zrSosA=="); private static final byte[] rawGost = Base64.decode( "MIIEBwYJKoZIhvcNAQcCoIID+DCCA/QCAQExDDAKBgYqhQMCAgkFADAfBgkq" + "hkiG9w0BBwGgEgQQU29tZSBEYXRhIEhFUkUhIaCCAuYwggLiMIICkaADAgEC" + "AgopoLG9AAIAArWeMAgGBiqFAwICAzBlMSAwHgYJKoZIhvcNAQkBFhFpbmZv" + "QGNyeXB0b3Byby5ydTELMAkGA1UEBhMCUlUxEzARBgNVBAoTCkNSWVBUTy1Q" + "Uk8xHzAdBgNVBAMTFlRlc3QgQ2VudGVyIENSWVBUTy1QUk8wHhcNMTIxMDE1" + "MTEwNDIzWhcNMTQxMDA0MDcwOTQxWjAhMRIwEAYDVQQDDAl0ZXN0IGdvc3Qx" + "CzAJBgNVBAYTAlJVMGMwHAYGKoUDAgITMBIGByqFAwICJAAGByqFAwICHgED" + "QwAEQPz/F99AG8wyMQz5uK3vJ3MdHk7ZyFzM4Ofnq8nAmDgI5/Nuzcu791/0" + "hRd+1i+fArRsiPMdQXOF0E7bEMHwWfWjggFjMIIBXzAOBgNVHQ8BAf8EBAMC" + "BPAwEwYDVR0lBAwwCgYIKwYBBQUHAwIwHQYDVR0OBBYEFO353ZD7sLCx6rVR" + "2o/IsSxuE1gAMB8GA1UdIwQYMBaAFG2PXgXZX6yRF5QelZoFMDg3ehAqMFUG" + "A1UdHwROMEwwSqBIoEaGRGh0dHA6Ly93d3cuY3J5cHRvcHJvLnJ1L0NlcnRF" + "bnJvbGwvVGVzdCUyMENlbnRlciUyMENSWVBUTy1QUk8oMikuY3JsMIGgBggr" + "BgEFBQcBAQSBkzCBkDAzBggrBgEFBQcwAYYnaHR0cDovL3d3dy5jcnlwdG9w" + "cm8ucnUvb2NzcG5jL29jc3Auc3JmMFkGCCsGAQUFBzAChk1odHRwOi8vd3d3" + "LmNyeXB0b3Byby5ydS9DZXJ0RW5yb2xsL3BraS1zaXRlX1Rlc3QlMjBDZW50" + "ZXIlMjBDUllQVE8tUFJPKDIpLmNydDAIBgYqhQMCAgMDQQBAR4mr69a62d3l" + "yK/UZ4Yz/Yi3jqURtbnJR2gugdzkG5pYHRwC41BbDaa1ItP+1gDp4s78+EiK" + "AJc17CHGZTz3MYHVMIHSAgEBMHMwZTEgMB4GCSqGSIb3DQEJARYRaW5mb0Bj" + "cnlwdG9wcm8ucnUxCzAJBgNVBAYTAlJVMRMwEQYDVQQKEwpDUllQVE8tUFJP" + "MR8wHQYDVQQDExZUZXN0IENlbnRlciBDUllQVE8tUFJPAgopoLG9AAIAArWe" + "MAoGBiqFAwICCQUAMAoGBiqFAwICEwUABED0Gs9zP9lSz/2/e3BUSpzCI3dx" + "39gfl/pFVkx4p5N/GW5o4gHIST9OhDSmdxwpMSK+39YSRD4R0Ue0faOqWEsj" + "AAAAAAAAAAAAAAAAAAAAAA=="); private static final byte[] noAttrEncData = Base64.decode( "MIIFjwYJKoZIhvcNAQcCoIIFgDCCBXwCAQExDTALBglghkgBZQMEAgEwgdAG" + "CSqGSIb3DQEHAaCBwgSBv01JTUUtVmVyc2lvbjogMS4wCkNvbnRlbnQtVHlw" + "ZTogYXBwbGljYXRpb24vb2N0ZXQtc3RyZWFtCkNvbnRlbnQtVHJhbnNmZXIt" + "RW5jb2Rpbmc6IGJpbmFyeQpDb250ZW50LURpc3Bvc2l0aW9uOiBhdHRhY2ht" + "ZW50OyBmaWxlbmFtZT1kb2MuYmluCgpUaGlzIGlzIGEgdmVyeSBodWdlIHNl" + "Y3JldCwgbWFkZSB3aXRoIG9wZW5zc2wKCgoKoIIDNDCCAzAwggKZoAMCAQIC" + "AQEwDQYJKoZIhvcNAQEFBQAwgawxCzAJBgNVBAYTAkFUMRAwDgYDVQQIEwdB" + "dXN0cmlhMQ8wDQYDVQQHEwZWaWVubmExFTATBgNVBAoTDFRpYW5pIFNwaXJp" + "dDEUMBIGA1UECxMLSlVuaXQgdGVzdHMxGjAYBgNVBAMTEU1hc3NpbWlsaWFu" + "byBNYXNpMTEwLwYJKoZIhvcNAQkBFiJtYXNzaW1pbGlhbm8ubWFzaUB0aWFu" + "aS1zcGlyaXQuY29tMCAXDTEyMDEwMjA5MDAzNVoYDzIxOTEwNjA4MDkwMDM1" + "WjCBjzELMAkGA1UEBhMCQVQxEDAOBgNVBAgTB0F1c3RyaWExFTATBgNVBAoT" + "DFRpYW5pIFNwaXJpdDEUMBIGA1UECxMLSlVuaXQgVGVzdHMxDjAMBgNVBAMT" + "BWNlcnQxMTEwLwYJKoZIhvcNAQkBFiJtYXNzaW1pbGlhbm8ubWFzaUB0aWFu" + "aS1zcGlyaXQuY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDYHz8n" + "soeWpILn+5tK8XgJc3k5n0h0MOlRXLbZZVB7yuxKMBIZwl8kqqnehfqxX+hr" + "b2MXSCgKEstnVunJVPUGuNxnQ8Z0R9p1o/9gR0KTXmoJ+Epx5wdEofk4Phsi" + "MxjC8FVvt3sSnzal1/m0/9KntrPWksefumGm5XD3W43e5wIDAQABo3sweTAJ" + "BgNVHRMEAjAAMCwGCWCGSAGG+EIBDQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBD" + "ZXJ0aWZpY2F0ZTAdBgNVHQ4EFgQU8mTZGl0EFv6aHo3bup144d6wYW8wHwYD" + "VR0jBBgwFoAUdHG2RdrchT0PFcUBiIiYcy5hAA4wDQYJKoZIhvcNAQEFBQAD" + "gYEATcc52eo73zEA4wmbyPv0lRrmyAxrHvZGIHiKpM8bP38WUB39lgmS8J0S" + "1ioj21bosiakGj/gXnxlk8M8O+mm4zzpYjy8gqGXiUt20+j3bm7MJYM8ePcq" + "dG/kReNuLUbRgIA6b0T4o+0WCELhrd9IlTk5IBKjHIjsP/GR1h0t//kxggFb" + "MIIBVwIBATCBsjCBrDELMAkGA1UEBhMCQVQxEDAOBgNVBAgTB0F1c3RyaWEx" + "DzANBgNVBAcTBlZpZW5uYTEVMBMGA1UEChMMVGlhbmkgU3Bpcml0MRQwEgYD" + "VQQLEwtKVW5pdCB0ZXN0czEaMBgGA1UEAxMRTWFzc2ltaWxpYW5vIE1hc2kx" + "MTAvBgkqhkiG9w0BCQEWIm1hc3NpbWlsaWFuby5tYXNpQHRpYW5pLXNwaXJp" + "dC5jb20CAQEwCwYJYIZIAWUDBAIBMA0GCSqGSIb3DQEBAQUABIGAEthqA7FK" + "V1i+MzzS4zz4DxT4lwUYkWfHaDtZADUyTD5lnP3Pf+t/ScpBEGkEtI7hDqOO" + "zE0WfkBshTx5B/uxDibc/jqjQpSYSz5cvBTgpocIalbqsErOkDYF1QP6UgaV" + "ZoVGwvGYIuIrFgWqgk08NsPHVVjYseTEhUDwkI1KSxU="); byte[] successResp = Base64.decode( "MIIFnAoBAKCCBZUwggWRBgkrBgEFBQcwAQEEggWCMIIFfjCCARehgZ8wgZwx" + "CzAJBgNVBAYTAklOMRcwFQYDVQQIEw5BbmRocmEgcHJhZGVzaDESMBAGA1UE" + "BxMJSHlkZXJhYmFkMQwwCgYDVQQKEwNUQ1MxDDAKBgNVBAsTA0FUQzEeMBwG" + "A1UEAxMVVENTLUNBIE9DU1AgUmVzcG9uZGVyMSQwIgYJKoZIhvcNAQkBFhVv" + "Y3NwQHRjcy1jYS50Y3MuY28uaW4YDzIwMDMwNDAyMTIzNDU4WjBiMGAwOjAJ" + "BgUrDgMCGgUABBRs07IuoCWNmcEl1oHwIak1BPnX8QQUtGyl/iL9WJ1VxjxF" + "j0hAwJ/s1AcCAQKhERgPMjAwMjA4MjkwNzA5MjZaGA8yMDAzMDQwMjEyMzQ1" + "OFowDQYJKoZIhvcNAQEFBQADgYEAfbN0TCRFKdhsmvOdUoiJ+qvygGBzDxD/" + "VWhXYA+16AphHLIWNABR3CgHB3zWtdy2j7DJmQ/R7qKj7dUhWLSqclAiPgFt" + "QQ1YvSJAYfEIdyHkxv4NP0LSogxrumANcDyC9yt/W9yHjD2ICPBIqCsZLuLk" + "OHYi5DlwWe9Zm9VFwCGgggPMMIIDyDCCA8QwggKsoAMCAQICAQYwDQYJKoZI" + "hvcNAQEFBQAwgZQxFDASBgNVBAMTC1RDUy1DQSBPQ1NQMSYwJAYJKoZIhvcN" + "AQkBFhd0Y3MtY2FAdGNzLWNhLnRjcy5jby5pbjEMMAoGA1UEChMDVENTMQww" + "CgYDVQQLEwNBVEMxEjAQBgNVBAcTCUh5ZGVyYWJhZDEXMBUGA1UECBMOQW5k" + "aHJhIHByYWRlc2gxCzAJBgNVBAYTAklOMB4XDTAyMDgyOTA3MTE0M1oXDTAz" + "MDgyOTA3MTE0M1owgZwxCzAJBgNVBAYTAklOMRcwFQYDVQQIEw5BbmRocmEg" + "cHJhZGVzaDESMBAGA1UEBxMJSHlkZXJhYmFkMQwwCgYDVQQKEwNUQ1MxDDAK" + "BgNVBAsTA0FUQzEeMBwGA1UEAxMVVENTLUNBIE9DU1AgUmVzcG9uZGVyMSQw" + "IgYJKoZIhvcNAQkBFhVvY3NwQHRjcy1jYS50Y3MuY28uaW4wgZ8wDQYJKoZI" + "hvcNAQEBBQADgY0AMIGJAoGBAM+XWW4caMRv46D7L6Bv8iwtKgmQu0SAybmF" + "RJiz12qXzdvTLt8C75OdgmUomxp0+gW/4XlTPUqOMQWv463aZRv9Ust4f8MH" + "EJh4ekP/NS9+d8vEO3P40ntQkmSMcFmtA9E1koUtQ3MSJlcs441JjbgUaVnm" + "jDmmniQnZY4bU3tVAgMBAAGjgZowgZcwDAYDVR0TAQH/BAIwADALBgNVHQ8E" + "BAMCB4AwEwYDVR0lBAwwCgYIKwYBBQUHAwkwNgYIKwYBBQUHAQEEKjAoMCYG" + "CCsGAQUFBzABhhpodHRwOi8vMTcyLjE5LjQwLjExMDo3NzAwLzAtBgNVHR8E" + "JjAkMCKgIKAehhxodHRwOi8vMTcyLjE5LjQwLjExMC9jcmwuY3JsMA0GCSqG" + "SIb3DQEBBQUAA4IBAQB6FovM3B4VDDZ15o12gnADZsIk9fTAczLlcrmXLNN4" + "PgmqgnwF0Ymj3bD5SavDOXxbA65AZJ7rBNAguLUo+xVkgxmoBH7R2sBxjTCc" + "r07NEadxM3HQkt0aX5XYEl8eRoifwqYAI9h0ziZfTNes8elNfb3DoPPjqq6V" + "mMg0f0iMS4W8LjNPorjRB+kIosa1deAGPhq0eJ8yr0/s2QR2/WFD5P4aXc8I" + "KWleklnIImS3zqiPrq6tl2Bm8DZj7vXlTOwmraSQxUwzCKwYob1yGvNOUQTq" + "pG6jxn7jgDawHU1+WjWQe4Q34/pWeGLysxTraMa+Ug9kPe+jy/qRX2xwvKBZ"); public NewSignedDataTest(String name) { super(name); } public static void main(String args[]) { junit.textui.TestRunner.run(NewSignedDataTest.class); } public static Test suite() throws Exception { init(); return new CMSTestSetup(new TestSuite(NewSignedDataTest.class)); } private static void init() throws Exception { if (!_initialised) { _initialised = true; if (Security.getProvider(BC) == null) { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); } _origDN = "O=Bouncy Castle, C=AU"; _origKP = CMSTestUtil.makeKeyPair(); _origCert = CMSTestUtil.makeCertificate(_origKP, _origDN, _origKP, _origDN); _signDN = "CN=Bob, OU=Sales, O=Bouncy Castle, C=AU"; _signKP = CMSTestUtil.makeKeyPair(); _signCert = CMSTestUtil.makeCertificate(_signKP, _signDN, _origKP, _origDN); _signGostKP = CMSTestUtil.makeGostKeyPair(); _signGostCert = CMSTestUtil.makeCertificate(_signGostKP, _signDN, _origKP, _origDN); _signDsaKP = CMSTestUtil.makeDsaKeyPair(); _signDsaCert = CMSTestUtil.makeCertificate(_signDsaKP, _signDN, _origKP, _origDN); _signEcDsaKP = CMSTestUtil.makeEcDsaKeyPair(); _signEcDsaCert = CMSTestUtil.makeCertificate(_signEcDsaKP, _signDN, _origKP, _origDN); _signEcGostKP = CMSTestUtil.makeEcGostKeyPair(); _signEcGostCert = CMSTestUtil.makeCertificate(_signEcGostKP, _signDN, _origKP, _origDN); _reciDN = "CN=Doug, OU=Sales, O=Bouncy Castle, C=AU"; _reciKP = CMSTestUtil.makeKeyPair(); _reciCert = CMSTestUtil.makeCertificate(_reciKP, _reciDN, _signKP, _signDN); _signCrl = CMSTestUtil.makeCrl(_signKP); } } private void verifyRSASignatures(CMSSignedData s, byte[] contentDigest) throws Exception { Store certStore = s.getCertificates(); SignerInformationStore signers = s.getSignerInfos(); Collection c = signers.getSigners(); Iterator it = c.iterator(); while (it.hasNext()) { SignerInformation signer = (SignerInformation)it.next(); Collection certCollection = certStore.getMatches(signer.getSID()); Iterator certIt = certCollection.iterator(); X509CertificateHolder cert = (X509CertificateHolder)certIt.next(); assertEquals(true, signer.verify(new BcRSASignerInfoVerifierBuilder(new DefaultCMSSignatureAlgorithmNameGenerator(), new DefaultSignatureAlgorithmIdentifierFinder(), new DefaultDigestAlgorithmIdentifierFinder(), new BcDigestCalculatorProvider()).build(cert))); if (contentDigest != null) { assertTrue(MessageDigest.isEqual(contentDigest, signer.getContentDigest())); } } } private void verifySignatures(CMSSignedData s, byte[] contentDigest) throws Exception { Store certStore = s.getCertificates(); Store crlStore = s.getCRLs(); SignerInformationStore signers = s.getSignerInfos(); Collection c = signers.getSigners(); Iterator it = c.iterator(); while (it.hasNext()) { SignerInformation signer = (SignerInformation)it.next(); Collection certCollection = certStore.getMatches(signer.getSID()); Iterator certIt = certCollection.iterator(); X509CertificateHolder cert = (X509CertificateHolder)certIt.next(); assertEquals(true, signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC).build(cert))); if (contentDigest != null) { assertTrue(MessageDigest.isEqual(contentDigest, signer.getContentDigest())); } } Collection certColl = certStore.getMatches(null); Collection crlColl = crlStore.getMatches(null); assertEquals(certColl.size(), s.getCertificates().getMatches(null).size()); assertEquals(crlColl.size(), s.getCRLs().getMatches(null).size()); } private void verifySignatures(CMSSignedData s) throws Exception { verifySignatures(s, null); } public void testDetachedVerification() throws Exception { byte[] data = "Hello World!".getBytes(); List certList = new ArrayList(); CMSTypedData msg = new CMSProcessableByteArray(data); certList.add(_origCert); certList.add(_signCert); Store certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); DigestCalculatorProvider digProvider = new JcaDigestCalculatorProviderBuilder().setProvider(BC).build(); JcaSignerInfoGeneratorBuilder signerInfoGeneratorBuilder = new JcaSignerInfoGeneratorBuilder(digProvider); ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(BC).build(_origKP.getPrivate()); ContentSigner md5Signer = new JcaContentSignerBuilder("MD5withRSA").setProvider(BC).build(_origKP.getPrivate()); gen.addSignerInfoGenerator(signerInfoGeneratorBuilder.build(sha1Signer, _origCert)); gen.addSignerInfoGenerator(signerInfoGeneratorBuilder.build(md5Signer, _origCert)); gen.addCertificates(certs); CMSSignedData s = gen.generate(msg); MessageDigest sha1 = MessageDigest.getInstance("SHA1", BC); MessageDigest md5 = MessageDigest.getInstance("MD5", BC); Map hashes = new HashMap(); byte[] sha1Hash = sha1.digest(data); byte[] md5Hash = md5.digest(data); hashes.put(CMSAlgorithm.SHA1, sha1Hash); hashes.put(CMSAlgorithm.MD5, md5Hash); s = new CMSSignedData(hashes, s.getEncoded()); verifySignatures(s, null); } public void testSHA1AndMD5WithRSAEncapsulatedRepeated() throws Exception { List certList = new ArrayList(); CMSTypedData msg = new CMSProcessableByteArray("Hello World!".getBytes()); certList.add(_origCert); certList.add(_signCert); Store certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder().setProvider(BC).build(); gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(digCalcProv).build(new JcaContentSignerBuilder("SHA1withRSA").setProvider(BC).build(_origKP.getPrivate()), _origCert)); gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(digCalcProv).build(new JcaContentSignerBuilder("MD5withRSA").setProvider(BC).build(_origKP.getPrivate()), _origCert)); gen.addCertificates(certs); CMSSignedData s = gen.generate(msg, true); ByteArrayInputStream bIn = new ByteArrayInputStream(s.getEncoded()); ASN1InputStream aIn = new ASN1InputStream(bIn); s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject())); certs = s.getCertificates(); SignerInformationStore signers = s.getSignerInfos(); assertEquals(2, signers.size()); Collection c = signers.getSigners(); Iterator it = c.iterator(); SignerId sid = null; while (it.hasNext()) { SignerInformation signer = (SignerInformation)it.next(); Collection certCollection = certs.getMatches(signer.getSID()); Iterator certIt = certCollection.iterator(); X509CertificateHolder cert = (X509CertificateHolder)certIt.next(); sid = signer.getSID(); assertEquals(true, signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC).build(cert))); // // check content digest // byte[] contentDigest = (byte[])gen.getGeneratedDigests().get(signer.getDigestAlgOID()); AttributeTable table = signer.getSignedAttributes(); Attribute hash = table.get(CMSAttributes.messageDigest); assertTrue(MessageDigest.isEqual(contentDigest, ((ASN1OctetString)hash.getAttrValues().getObjectAt(0)).getOctets())); } c = signers.getSigners(sid); assertEquals(2, c.size()); // // try using existing signer // gen = new CMSSignedDataGenerator(); gen.addSigners(s.getSignerInfos()); gen.addCertificates(s.getCertificates()); s = gen.generate(msg, true); bIn = new ByteArrayInputStream(s.getEncoded()); aIn = new ASN1InputStream(bIn); s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject())); certs = s.getCertificates(); signers = s.getSignerInfos(); c = signers.getSigners(); it = c.iterator(); assertEquals(2, c.size()); while (it.hasNext()) { SignerInformation signer = (SignerInformation)it.next(); Collection certCollection = certs.getMatches(signer.getSID()); Iterator certIt = certCollection.iterator(); X509CertificateHolder cert = (X509CertificateHolder)certIt.next(); assertEquals(true, signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC).build(cert))); } checkSignerStoreReplacement(s, signers); } public void testSHA1WithRSANoAttributes() throws Exception { List certList = new ArrayList(); CMSTypedData msg = new CMSProcessableByteArray("Hello world!".getBytes()); certList.add(_origCert); certList.add(_signCert); Store certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(BC).build(_origKP.getPrivate()); JcaSignerInfoGeneratorBuilder builder = new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider(BC).build()); builder.setDirectSignature(true); gen.addSignerInfoGenerator(builder.build(sha1Signer, _origCert)); gen.addCertificates(certs); CMSSignedData s = gen.generate(msg, false); // // compute expected content digest // MessageDigest md = MessageDigest.getInstance("SHA1", BC); verifySignatures(s, md.digest("Hello world!".getBytes())); } public void testSHA1WithRSANoAttributesSimple() throws Exception { List certList = new ArrayList(); CMSTypedData msg = new CMSProcessableByteArray("Hello world!".getBytes()); certList.add(_origCert); certList.add(_signCert); Store certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); JcaSimpleSignerInfoGeneratorBuilder builder = new JcaSimpleSignerInfoGeneratorBuilder().setProvider(BC).setDirectSignature(true); gen.addSignerInfoGenerator(builder.build("SHA1withRSA", _origKP.getPrivate(), _origCert)); gen.addCertificates(certs); CMSSignedData s = gen.generate(msg, false); // // compute expected content digest // MessageDigest md = MessageDigest.getInstance("SHA1", BC); verifySignatures(s, md.digest("Hello world!".getBytes())); } public void testSHA1WithRSAAndOtherRevocation() throws Exception { List certList = new ArrayList(); CMSTypedData msg = new CMSProcessableByteArray("Hello world!".getBytes()); certList.add(_origCert); certList.add(_signCert); Store certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(BC).build(_origKP.getPrivate()); gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider(BC).build()).build(sha1Signer, _origCert)); gen.addCertificates(certs); List otherInfo = new ArrayList(); OCSPResp response = new OCSPResp(successResp); otherInfo.add(response.toASN1Structure()); gen.addOtherRevocationInfo(CMSObjectIdentifiers.id_ri_ocsp_response, new CollectionStore(otherInfo)); CMSSignedData s; s = gen.generate(msg, false); // // check version // assertEquals(5, s.getVersion()); // // compute expected content digest // MessageDigest md = MessageDigest.getInstance("SHA1", BC); verifySignatures(s, md.digest("Hello world!".getBytes())); Store dataOtherInfo = s.getOtherRevocationInfo(CMSObjectIdentifiers.id_ri_ocsp_response); assertEquals(1, dataOtherInfo.getMatches(null).size()); OCSPResp dataResponse = new OCSPResp(OCSPResponse.getInstance(dataOtherInfo.getMatches(null).iterator().next())); assertEquals(response, dataResponse); } public void testSHA1WithRSAAndAttributeTableSimple() throws Exception { MessageDigest md = MessageDigest.getInstance("SHA1", BC); List certList = new ArrayList(); CMSTypedData msg = new CMSProcessableByteArray("Hello world!".getBytes()); certList.add(_origCert); certList.add(_signCert); Store certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); Attribute attr = new Attribute(CMSAttributes.messageDigest, new DERSet( new DEROctetString( md.digest("Hello world!".getBytes())))); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(attr); JcaSimpleSignerInfoGeneratorBuilder builder = new JcaSimpleSignerInfoGeneratorBuilder().setProvider(BC).setSignedAttributeGenerator(new DefaultSignedAttributeTableGenerator(new AttributeTable(v))); gen.addSignerInfoGenerator(builder.build("SHA1withRSA", _origKP.getPrivate(), _origCert)); gen.addCertificates(certs); CMSSignedData s = gen.generate(new CMSAbsentContent(), false); // // the signature is detached, so need to add msg before passing on // s = new CMSSignedData(msg, s.getEncoded()); // // compute expected content digest // verifySignatures(s, md.digest("Hello world!".getBytes())); verifyRSASignatures(s, md.digest("Hello world!".getBytes())); } public void testSHA1WithRSAAndAttributeTable() throws Exception { MessageDigest md = MessageDigest.getInstance("SHA1", BC); List certList = new ArrayList(); CMSTypedData msg = new CMSProcessableByteArray("Hello world!".getBytes()); certList.add(_origCert); certList.add(_signCert); Store certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); Attribute attr = new Attribute(CMSAttributes.messageDigest, new DERSet( new DEROctetString( md.digest("Hello world!".getBytes())))); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(attr); JcaSignerInfoGeneratorBuilder builder = new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider(BC).build()); builder.setSignedAttributeGenerator(new DefaultSignedAttributeTableGenerator(new AttributeTable(v))); ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(BC).build(_origKP.getPrivate()); gen.addSignerInfoGenerator(builder.build(sha1Signer, _origCert)); gen.addCertificates(certs); CMSSignedData s = gen.generate(new CMSAbsentContent(), false); // // the signature is detached, so need to add msg before passing on // s = new CMSSignedData(msg, s.getEncoded()); // // compute expected content digest // verifySignatures(s, md.digest("Hello world!".getBytes())); verifyRSASignatures(s, md.digest("Hello world!".getBytes())); } public void testLwSHA1WithRSAAndAttributeTable() throws Exception { MessageDigest md = MessageDigest.getInstance("SHA1", BC); List certList = new ArrayList(); CMSTypedData msg = new CMSProcessableByteArray("Hello world!".getBytes()); certList.add(_origCert); certList.add(_signCert); Store certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); Attribute attr = new Attribute(CMSAttributes.messageDigest, new DERSet( new DEROctetString( md.digest("Hello world!".getBytes())))); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(attr); AsymmetricKeyParameter privKey = PrivateKeyFactory.createKey(_origKP.getPrivate().getEncoded()); AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withRSA"); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); BcContentSignerBuilder contentSignerBuilder = new BcRSAContentSignerBuilder(sigAlgId, digAlgId); gen.addSignerInfoGenerator( new SignerInfoGeneratorBuilder(new BcDigestCalculatorProvider()) .setSignedAttributeGenerator(new DefaultSignedAttributeTableGenerator(new AttributeTable(v))) .build(contentSignerBuilder.build(privKey), new JcaX509CertificateHolder(_origCert))); gen.addCertificates(certs); CMSSignedData s = gen.generate(new CMSAbsentContent(), false); // // the signature is detached, so need to add msg before passing on // s = new CMSSignedData(msg, s.getEncoded()); // // compute expected content digest // verifySignatures(s, md.digest("Hello world!".getBytes())); verifyRSASignatures(s, md.digest("Hello world!".getBytes())); } public void testSHA1WithRSAEncapsulated() throws Exception { encapsulatedTest(_signKP, _signCert, "SHA1withRSA"); } public void testSHA1WithRSAEncapsulatedSubjectKeyID() throws Exception { subjectKeyIDTest(_signKP, _signCert, "SHA1withRSA"); } public void testSHA1WithRSAPSS() throws Exception { rsaPSSTest("SHA1withRSAandMGF1"); } public void testSHA224WithRSAPSS() throws Exception { rsaPSSTest("SHA224withRSAandMGF1"); } public void testSHA256WithRSAPSS() throws Exception { rsaPSSTest("SHA256withRSAandMGF1"); } public void testSHA384WithRSAPSS() throws Exception { rsaPSSTest("SHA384withRSAandMGF1"); } public void testSHA224WithRSAEncapsulated() throws Exception { encapsulatedTest(_signKP, _signCert, "SHA224withRSA"); } public void testSHA256WithRSAEncapsulated() throws Exception { encapsulatedTest(_signKP, _signCert, "SHA256withRSA"); } public void testRIPEMD128WithRSAEncapsulated() throws Exception { encapsulatedTest(_signKP, _signCert, "RIPEMD128withRSA"); } public void testRIPEMD160WithRSAEncapsulated() throws Exception { encapsulatedTest(_signKP, _signCert, "RIPEMD160withRSA"); } public void testRIPEMD256WithRSAEncapsulated() throws Exception { encapsulatedTest(_signKP, _signCert, "RIPEMD256withRSA"); } public void testECDSAEncapsulated() throws Exception { encapsulatedTest(_signEcDsaKP, _signEcDsaCert, "SHA1withECDSA"); } public void testECDSAEncapsulatedSubjectKeyID() throws Exception { subjectKeyIDTest(_signEcDsaKP, _signEcDsaCert, "SHA1withECDSA"); } public void testECDSASHA224Encapsulated() throws Exception { encapsulatedTest(_signEcDsaKP, _signEcDsaCert, "SHA224withECDSA"); } public void testECDSASHA256Encapsulated() throws Exception { encapsulatedTest(_signEcDsaKP, _signEcDsaCert, "SHA256withECDSA"); } public void testECDSASHA384Encapsulated() throws Exception { encapsulatedTest(_signEcDsaKP, _signEcDsaCert, "SHA384withECDSA"); } public void testECDSASHA512Encapsulated() throws Exception { encapsulatedTest(_signEcDsaKP, _signEcDsaCert, "SHA512withECDSA"); } public void testECDSASHA512EncapsulatedWithKeyFactoryAsEC() throws Exception { X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(_signEcDsaKP.getPublic().getEncoded()); PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(_signEcDsaKP.getPrivate().getEncoded()); KeyFactory keyFact = KeyFactory.getInstance("EC", BC); KeyPair kp = new KeyPair(keyFact.generatePublic(pubSpec), keyFact.generatePrivate(privSpec)); encapsulatedTest(kp, _signEcDsaCert, "SHA512withECDSA"); } public void testDSAEncapsulated() throws Exception { encapsulatedTest(_signDsaKP, _signDsaCert, "SHA1withDSA"); } public void testDSAEncapsulatedSubjectKeyID() throws Exception { subjectKeyIDTest(_signDsaKP, _signDsaCert, "SHA1withDSA"); } public void testGOST3411WithGOST3410Encapsulated() throws Exception { encapsulatedTest(_signGostKP, _signGostCert, "GOST3411withGOST3410"); } public void testGOST3411WithECGOST3410Encapsulated() throws Exception { encapsulatedTest(_signEcGostKP, _signEcGostCert, "GOST3411withECGOST3410"); } public void testGostNoAttributesEncapsulated() throws Exception { CMSSignedData data = new CMSSignedData(rawGost); Store certStore = data.getCertificates(); SignerInformationStore signers = data.getSignerInfos(); Collection c = signers.getSigners(); Iterator it = c.iterator(); while (it.hasNext()) { SignerInformation signer = (SignerInformation)it.next(); Collection certCollection = certStore.getMatches(signer.getSID()); Iterator certIt = certCollection.iterator(); X509CertificateHolder cert = (X509CertificateHolder)certIt.next(); assertEquals(true, signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert))); } } public void testSHA1WithRSACounterSignature() throws Exception { List certList = new ArrayList(); List crlList = new ArrayList(); CMSTypedData msg = new CMSProcessableByteArray("Hello World!".getBytes()); certList.add(_signCert); certList.add(_origCert); crlList.add(_signCrl); Store certStore = new JcaCertStore(certList); Store crlStore = new JcaCRLStore(crlList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(BC).build(_signKP.getPrivate()); gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider(BC).build()).build(sha1Signer, _signCert)); gen.addCertificates(certStore); gen.addCRLs(crlStore); CMSSignedData s = gen.generate(msg, true); SignerInformation origSigner = (SignerInformation)s.getSignerInfos().getSigners().toArray()[0]; SignerInformationStore counterSigners1 = gen.generateCounterSigners(origSigner); SignerInformationStore counterSigners2 = gen.generateCounterSigners(origSigner); SignerInformation signer1 = SignerInformation.addCounterSigners(origSigner, counterSigners1); SignerInformation signer2 = SignerInformation.addCounterSigners(signer1, counterSigners2); SignerInformationStore cs = signer2.getCounterSignatures(); Collection csSigners = cs.getSigners(); assertEquals(2, csSigners.size()); Iterator it = csSigners.iterator(); while (it.hasNext()) { SignerInformation cSigner = (SignerInformation)it.next(); Collection certCollection = certStore.getMatches(cSigner.getSID()); Iterator certIt = certCollection.iterator(); X509CertificateHolder cert = (X509CertificateHolder)certIt.next(); assertTrue(cSigner.isCounterSignature()); assertNull(cSigner.getSignedAttributes().get(PKCSObjectIdentifiers.pkcs_9_at_contentType)); assertEquals(true, cSigner.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC).build(cert))); } } public void testSHA1WithRSACounterSignatureAndVerifierProvider() throws Exception { List certList = new ArrayList(); List crlList = new ArrayList(); CMSTypedData msg = new CMSProcessableByteArray("Hello World!".getBytes()); certList.add(_signCert); certList.add(_origCert); crlList.add(_signCrl); Store certStore = new JcaCertStore(certList); Store crlStore = new JcaCRLStore(crlList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(BC).build(_signKP.getPrivate()); gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider(BC).build()).build(sha1Signer, _signCert)); gen.addCertificates(certStore); gen.addCRLs(crlStore); CMSSignedData s = gen.generate(msg, true); SignerInformationVerifierProvider vProv = new SignerInformationVerifierProvider() { public SignerInformationVerifier get(SignerId signerId) throws OperatorCreationException { return new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC).build(_signCert); } }; assertTrue(s.verifySignatures(vProv)); SignerInformation origSigner = (SignerInformation)s.getSignerInfos().getSigners().toArray()[0]; gen = new CMSSignedDataGenerator(); sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(BC).build(_origKP.getPrivate()); gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider(BC).build()).build(sha1Signer, _origCert)); SignerInformationStore counterSigners = gen.generateCounterSigners(origSigner); SignerInformation signer1 = SignerInformation.addCounterSigners(origSigner, counterSigners); List signers = new ArrayList(); signers.add(signer1); s = CMSSignedData.replaceSigners(s, new SignerInformationStore(signers)); assertTrue(s.verifySignatures(vProv, true)); // provider can't handle counter sig assertFalse(s.verifySignatures(vProv, false)); vProv = new SignerInformationVerifierProvider() { public SignerInformationVerifier get(SignerId signerId) throws OperatorCreationException { if (_signCert.getSerialNumber().equals(signerId.getSerialNumber())) { return new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC).build(_signCert); } else { return new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC).build(_origCert); } } }; // verify sig and counter sig. assertFalse(s.verifySignatures(vProv, false)); } private void rsaPSSTest(String signatureAlgorithmName) throws Exception { List certList = new ArrayList(); CMSTypedData msg = new CMSProcessableByteArray("Hello world!".getBytes()); certList.add(_origCert); certList.add(_signCert); Store certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithmName).setProvider(BC).build(_origKP.getPrivate()); JcaSignerInfoGeneratorBuilder siBuilder = new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider(BC).build()); siBuilder.setDirectSignature(true); gen.addSignerInfoGenerator(siBuilder.build(contentSigner, _origCert)); gen.addCertificates(certs); CMSSignedData s = gen.generate(msg, false); // // compute expected content digest // String digestName = signatureAlgorithmName.substring(0, signatureAlgorithmName.indexOf('w')); MessageDigest md = MessageDigest.getInstance(digestName, BC); verifySignatures(s, md.digest("Hello world!".getBytes())); } private void subjectKeyIDTest( KeyPair signaturePair, X509Certificate signatureCert, String signatureAlgorithm) throws Exception { List certList = new ArrayList(); List crlList = new ArrayList(); CMSTypedData msg = new CMSProcessableByteArray("Hello World!".getBytes()); certList.add(signatureCert); certList.add(_origCert); crlList.add(_signCrl); Store certStore = new JcaCertStore(certList); Store crlStore = new JcaCRLStore(crlList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithm).setProvider(BC).build(signaturePair.getPrivate()); gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider(BC).build()).build(contentSigner, CMSTestUtil.createSubjectKeyId(signatureCert.getPublicKey()).getKeyIdentifier())); gen.addCertificates(certStore); gen.addCRLs(crlStore); CMSSignedData s = gen.generate(msg, true); assertEquals(3, s.getVersion()); ByteArrayInputStream bIn = new ByteArrayInputStream(s.getEncoded()); ASN1InputStream aIn = new ASN1InputStream(bIn); s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject())); certStore = s.getCertificates(); SignerInformationStore signers = s.getSignerInfos(); Collection c = signers.getSigners(); Iterator it = c.iterator(); while (it.hasNext()) { SignerInformation signer = (SignerInformation)it.next(); Collection certCollection = certStore.getMatches(signer.getSID()); Iterator certIt = certCollection.iterator(); X509CertificateHolder cert = (X509CertificateHolder)certIt.next(); assertEquals(true, signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC).build(cert))); } // // check for CRLs // Collection crls = crlStore.getMatches(null); assertEquals(1, crls.size()); assertTrue(crls.contains(new JcaX509CRLHolder(_signCrl))); // // try using existing signer // gen = new CMSSignedDataGenerator(); gen.addSigners(s.getSignerInfos()); gen.addCertificates(s.getCertificates()); s = gen.generate(msg, true); bIn = new ByteArrayInputStream(s.getEncoded()); aIn = new ASN1InputStream(bIn); s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject())); certStore = s.getCertificates(); signers = s.getSignerInfos(); c = signers.getSigners(); it = c.iterator(); while (it.hasNext()) { SignerInformation signer = (SignerInformation)it.next(); Collection certCollection = certStore.getMatches(signer.getSID()); Iterator certIt = certCollection.iterator(); X509CertificateHolder cert = (X509CertificateHolder)certIt.next(); assertEquals(true, signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC).build(cert))); } checkSignerStoreReplacement(s, signers); } private void encapsulatedTest( KeyPair signaturePair, X509Certificate signatureCert, String signatureAlgorithm) throws Exception { List certList = new ArrayList(); List crlList = new ArrayList(); CMSTypedData msg = new CMSProcessableByteArray("Hello World!".getBytes()); certList.add(signatureCert); certList.add(_origCert); crlList.add(_signCrl); Store certs = new JcaCertStore(certList); Store crlStore = new JcaCRLStore(crlList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithm).setProvider(BC).build(signaturePair.getPrivate()); gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider(BC).build()).build(contentSigner, signatureCert)); gen.addCertificates(certs); CMSSignedData s = gen.generate(msg, true); ByteArrayInputStream bIn = new ByteArrayInputStream(s.getEncoded()); ASN1InputStream aIn = new ASN1InputStream(bIn); s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject())); certs = s.getCertificates(); SignerInformationStore signers = s.getSignerInfos(); Collection c = signers.getSigners(); Iterator it = c.iterator(); while (it.hasNext()) { SignerInformation signer = (SignerInformation)it.next(); Collection certCollection = certs.getMatches(signer.getSID()); Iterator certIt = certCollection.iterator(); X509CertificateHolder cert = (X509CertificateHolder)certIt.next(); assertEquals(true, signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC).build(cert))); } // // check signer information lookup // SignerId sid = new JcaSignerId(signatureCert); Collection collection = signers.getSigners(sid); assertEquals(1, collection.size()); assertTrue(collection.iterator().next() instanceof SignerInformation); // // check for CRLs // Collection crls = crlStore.getMatches(null); assertEquals(1, crls.size()); assertTrue(crls.contains(new JcaX509CRLHolder(_signCrl))); // // try using existing signer // gen = new CMSSignedDataGenerator(); gen.addSigners(s.getSignerInfos()); gen.addCertificates(s.getCertificates()); s = gen.generate(msg, true); bIn = new ByteArrayInputStream(s.getEncoded()); aIn = new ASN1InputStream(bIn); s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject())); certs = s.getCertificates(); signers = s.getSignerInfos(); c = signers.getSigners(); it = c.iterator(); while (it.hasNext()) { SignerInformation signer = (SignerInformation)it.next(); Collection certCollection = certs.getMatches(signer.getSID()); Iterator certIt = certCollection.iterator(); X509CertificateHolder cert = (X509CertificateHolder)certIt.next(); assertEquals(true, signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC).build(cert))); } checkSignerStoreReplacement(s, signers); } // // signerInformation store replacement test. // private void checkSignerStoreReplacement( CMSSignedData orig, SignerInformationStore signers) throws Exception { CMSSignedData s = CMSSignedData.replaceSigners(orig, signers); Store certs = s.getCertificates(); signers = s.getSignerInfos(); Collection c = signers.getSigners(); Iterator it = c.iterator(); while (it.hasNext()) { SignerInformation signer = (SignerInformation)it.next(); Collection certCollection = certs.getMatches(signer.getSID()); Iterator certIt = certCollection.iterator(); X509CertificateHolder cert = (X509CertificateHolder)certIt.next(); assertEquals(true, signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC).build(cert))); } } public void testUnsortedAttributes() throws Exception { CMSSignedData s = new CMSSignedData(new CMSProcessableByteArray(disorderedMessage), disorderedSet); Store certs = s.getCertificates(); SignerInformationStore signers = s.getSignerInfos(); Collection c = signers.getSigners(); Iterator it = c.iterator(); while (it.hasNext()) { SignerInformation signer = (SignerInformation)it.next(); Collection certCollection = certs.getMatches(signer.getSID()); Iterator certIt = certCollection.iterator(); X509CertificateHolder cert = (X509CertificateHolder)certIt.next(); assertEquals(false, signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC).build(cert))); Signature sig = Signature.getInstance("SHA1withRSA", BC); sig.initVerify(new JcaX509CertificateConverter().getCertificate(cert).getPublicKey()); sig.update(signer.toASN1Structure().getAuthenticatedAttributes().getEncoded()); assertEquals(true, sig.verify(signer.getSignature())); } } public void testNullContentWithSigner() throws Exception { List certList = new ArrayList(); certList.add(_origCert); certList.add(_signCert); Store certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(BC).build(_origKP.getPrivate()); gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider(BC).build()).build(sha1Signer, _origCert)); gen.addCertificates(certs); CMSSignedData s = gen.generate(new CMSAbsentContent(), false); ByteArrayInputStream bIn = new ByteArrayInputStream(s.getEncoded()); ASN1InputStream aIn = new ASN1InputStream(bIn); s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject())); verifySignatures(s); } public void testWithAttributeCertificate() throws Exception { List certList = new ArrayList(); CMSTypedData msg = new CMSProcessableByteArray("Hello World!".getBytes()); certList.add(_signDsaCert); Store certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); JcaSignerInfoGeneratorBuilder builder = new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider(BC).build()); ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(BC).build(_origKP.getPrivate()); gen.addSignerInfoGenerator(builder.build(sha1Signer, _origCert)); gen.addCertificates(certs); X509AttributeCertificateHolder attrCert = CMSTestUtil.getAttributeCertificate(); List attrList = new ArrayList(); attrList.add(new X509AttributeCertificateHolder(attrCert.getEncoded())); Store store = new CollectionStore(attrList); gen.addAttributeCertificates(store); CMSSignedData sd = gen.generate(msg); assertEquals(4, sd.getVersion()); store = sd.getAttributeCertificates(); Collection coll = store.getMatches(null); assertEquals(1, coll.size()); assertTrue(coll.contains(new X509AttributeCertificateHolder(attrCert.getEncoded()))); // // create new certstore // certList = new ArrayList(); certList.add(_origCert); certList.add(_signCert); certs = new JcaCertStore(certList); // // replace certs // sd = CMSSignedData.replaceCertificatesAndCRLs(sd, certs, null, null); verifySignatures(sd); } public void testCertStoreReplacement() throws Exception { List certList = new ArrayList(); CMSTypedData msg = new CMSProcessableByteArray("Hello World!".getBytes()); certList.add(_signDsaCert); Store certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(BC).build(_origKP.getPrivate()); gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider(BC).build()).build(sha1Signer, _origCert)); gen.addCertificates(certs); CMSSignedData sd = gen.generate(msg); // // create new certstore // certList = new ArrayList(); certList.add(_origCert); certList.add(_signCert); certs = new JcaCertStore(certList); // // replace certs // sd = CMSSignedData.replaceCertificatesAndCRLs(sd, certs, null, null); verifySignatures(sd); } public void testEncapsulatedCertStoreReplacement() throws Exception { List certList = new ArrayList(); CMSTypedData msg = new CMSProcessableByteArray("Hello World!".getBytes()); certList.add(_signDsaCert); Store certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(BC).build(_origKP.getPrivate()); gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider(BC).build()).build(sha1Signer, _origCert)); gen.addCertificates(certs); CMSSignedData sd = gen.generate(msg, true); // // create new certstore // certList = new ArrayList(); certList.add(_origCert); certList.add(_signCert); certs = new JcaCertStore(certList); // // replace certs // sd = CMSSignedData.replaceCertificatesAndCRLs(sd, certs, null, null); verifySignatures(sd); } public void testCertOrdering1() throws Exception { List certList = new ArrayList(); CMSTypedData msg = new CMSProcessableByteArray("Hello World!".getBytes()); certList.add(_origCert); certList.add(_signCert); certList.add(_signDsaCert); Store certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(BC).build(_origKP.getPrivate()); gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider(BC).build()).build(sha1Signer, _origCert)); gen.addCertificates(certs); CMSSignedData sd = gen.generate(msg, true); certs = sd.getCertificates(); Iterator it = certs.getMatches(null).iterator(); assertEquals(new JcaX509CertificateHolder(_origCert), it.next()); assertEquals(new JcaX509CertificateHolder(_signCert), it.next()); assertEquals(new JcaX509CertificateHolder(_signDsaCert), it.next()); } public void testCertOrdering2() throws Exception { List certList = new ArrayList(); CMSTypedData msg = new CMSProcessableByteArray("Hello World!".getBytes()); certList.add(_signCert); certList.add(_signDsaCert); certList.add(_origCert); Store certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(BC).build(_origKP.getPrivate()); gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider(BC).build()).build(sha1Signer, _origCert)); gen.addCertificates(certs); CMSSignedData sd = gen.generate(msg, true); certs = sd.getCertificates(); Iterator it = certs.getMatches(null).iterator(); assertEquals(new JcaX509CertificateHolder(_signCert), it.next()); assertEquals(new JcaX509CertificateHolder(_signDsaCert), it.next()); assertEquals(new JcaX509CertificateHolder(_origCert), it.next()); } public void testSignerStoreReplacement() throws Exception { List certList = new ArrayList(); CMSTypedData msg = new CMSProcessableByteArray("Hello World!".getBytes()); certList.add(_origCert); certList.add(_signCert); Store certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(BC).build(_origKP.getPrivate()); gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider(BC).build()).build(sha1Signer, _origCert)); gen.addCertificates(certs); CMSSignedData original = gen.generate(msg, true); // // create new Signer // gen = new CMSSignedDataGenerator(); ContentSigner sha224Signer = new JcaContentSignerBuilder("SHA224withRSA").setProvider(BC).build(_origKP.getPrivate()); gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider(BC).build()).build(sha224Signer, _origCert)); gen.addCertificates(certs); CMSSignedData newSD = gen.generate(msg, true); // // replace signer // CMSSignedData sd = CMSSignedData.replaceSigners(original, newSD.getSignerInfos()); SignerInformation signer = (SignerInformation)sd.getSignerInfos().getSigners().iterator().next(); assertEquals(CMSAlgorithm.SHA224.getId(), signer.getDigestAlgOID()); // we use a parser here as it requires the digests to be correct in the digest set, if it // isn't we'll get a NullPointerException CMSSignedDataParser sp = new CMSSignedDataParser(new JcaDigestCalculatorProviderBuilder().setProvider(BC).build(), sd.getEncoded()); sp.getSignedContent().drain(); verifySignatures(sp); } public void testEncapsulatedSamples() throws Exception { testSample("PSSSignDataSHA1Enc.sig"); testSample("PSSSignDataSHA256Enc.sig"); testSample("PSSSignDataSHA512Enc.sig"); } public void testSamples() throws Exception { testSample("PSSSignData.data", "PSSSignDataSHA1.sig"); testSample("PSSSignData.data", "PSSSignDataSHA256.sig"); testSample("PSSSignData.data", "PSSSignDataSHA512.sig"); } public void testNoAttrEncapsulatedSample() throws Exception { CMSSignedData s = new CMSSignedData(noAttrEncData); Store certStore = s.getCertificates(); assertNotNull(certStore); SignerInformationStore signers = s.getSignerInfos(); assertNotNull(signers); Collection c = signers.getSigners(); Iterator it = c.iterator(); while (it.hasNext()) { SignerInformation signer = (SignerInformation)it.next(); Collection certCollection = certStore.getMatches(signer.getSID()); Iterator certIt = certCollection.iterator(); X509CertificateHolder cert = (X509CertificateHolder)certIt.next(); if (!signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC).build(cert))) { fail("Verification FAILED! "); } } } public void testCounterSig() throws Exception { CMSSignedData sig = new CMSSignedData(getInput("counterSig.p7m")); SignerInformationStore ss = sig.getSignerInfos(); Collection signers = ss.getSigners(); SignerInformationStore cs = ((SignerInformation)signers.iterator().next()).getCounterSignatures(); Collection csSigners = cs.getSigners(); assertEquals(1, csSigners.size()); Iterator it = csSigners.iterator(); while (it.hasNext()) { SignerInformation cSigner = (SignerInformation)it.next(); Collection certCollection = sig.getCertificates().getMatches(cSigner.getSID()); Iterator certIt = certCollection.iterator(); X509CertificateHolder cert = (X509CertificateHolder)certIt.next(); assertTrue(cSigner.isCounterSignature()); assertNull(cSigner.getSignedAttributes().get(PKCSObjectIdentifiers.pkcs_9_at_contentType)); assertEquals(true, cSigner.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC).build(cert))); } verifySignatures(sig); } public void testCertificateManagement() throws Exception { CMSSignedDataGenerator sGen = new CMSSignedDataGenerator(); List certList = new ArrayList(); certList.add(_origCert); certList.add(_signCert); Store certs = new JcaCertStore(certList); sGen.addCertificates(certs); CMSSignedData sData = sGen.generate(new CMSAbsentContent(), true); CMSSignedData rsData = new CMSSignedData(sData.getEncoded()); assertEquals(2, rsData.getCertificates().getMatches(null).size()); } private void testSample(String sigName) throws Exception { CMSSignedData sig = new CMSSignedData(getInput(sigName)); verifySignatures(sig); } private void testSample(String messageName, String sigName) throws Exception { CMSSignedData sig = new CMSSignedData(new CMSProcessableByteArray(getInput(messageName)), getInput(sigName)); verifySignatures(sig); } private byte[] getInput(String name) throws IOException { return Streams.readAll(getClass().getResourceAsStream(name)); } public void testForMultipleCounterSignatures() throws Exception { CMSSignedData sd = new CMSSignedData(xtraCounterSig); for (Iterator sI = sd.getSignerInfos().getSigners().iterator(); sI.hasNext();) { SignerInformation sigI = (SignerInformation)sI.next(); SignerInformationStore counter = sigI.getCounterSignatures(); List sigs = new ArrayList(counter.getSigners()); assertEquals(2, sigs.size()); } } private void verifySignatures(CMSSignedDataParser sp) throws Exception { Store certs = sp.getCertificates(); SignerInformationStore signers = sp.getSignerInfos(); Collection c = signers.getSigners(); Iterator it = c.iterator(); while (it.hasNext()) { SignerInformation signer = (SignerInformation)it.next(); Collection certCollection = certs.getMatches(signer.getSID()); Iterator certIt = certCollection.iterator(); X509CertificateHolder cert = (X509CertificateHolder)certIt.next(); assertEquals(true, signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC).build(cert))); } } private class TestCMSSignatureAlgorithmNameGenerator extends DefaultCMSSignatureAlgorithmNameGenerator { void setDigestAlgorithmMapping(ASN1ObjectIdentifier oid, String algName) { super.setSigningDigestAlgorithmMapping(oid, algName); } void setEncryptionAlgorithmMapping(ASN1ObjectIdentifier oid, String algName) { super.setSigningEncryptionAlgorithmMapping(oid, algName); } } }
fixed counter signature method test.
pkix/src/test/java/org/bouncycastle/cms/test/NewSignedDataTest.java
fixed counter signature method test.
Java
mit
dc1d24518ea78ae83dd8ff92b125df9da3659e69
0
mpbagot/Slugterra-Mod
package com.slugterra.gui; import org.lwjgl.opengl.GL11; import com.slugterra.capabilities.ISlugInv; import com.slugterra.capabilities.SlugInventoryProvider; import com.slugterra.inventory.InventorySlug; import com.slugterra.item.BlasterBase; import com.slugterra.item.SlingerArmour; import com.slugterra.lib.Strings; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Gui; import net.minecraft.client.gui.ScaledResolution; import net.minecraft.client.renderer.RenderItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.event.RenderGameOverlayEvent; import net.minecraftforge.client.event.RenderGameOverlayEvent.ElementType; import net.minecraftforge.fml.common.eventhandler.EventPriority; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; public class GuiSlugBeltOverlay extends Gui{ private Minecraft mc; public static int selslot; protected RenderItem itemRenderer; private ISlugInv props; public GuiSlugBeltOverlay(Minecraft mc){ super(); this.mc = mc; this.itemRenderer = mc.getRenderItem(); // this.props = mc.player.getCapability(SlugInventoryProvider.INV_CAP, null); } @SubscribeEvent(priority = EventPriority.NORMAL) public void onRenderExperienceBar(RenderGameOverlayEvent event){ if(event.isCancelable() || event.getType() != ElementType.HOTBAR){ return; } else if (!(this.mc.player.getItemStackFromSlot(EntityEquipmentSlot.CHEST).getItem() instanceof SlingerArmour)) { // If the player isn't using a slinger belt, disable the bar return; } ScaledResolution scaledresolution = new ScaledResolution(this.mc); // int k = scaledresolution.getScaledWidth(); int l = scaledresolution.getScaledHeight(); GL11.glDisable(GL11.GL_LIGHTING); //get player properties props = ((EntityPlayer)this.mc.player).getCapability(SlugInventoryProvider.INV_CAP, null); //rendering bar this.mc.renderEngine.bindTexture(new ResourceLocation(Strings.MODID, "textures/gui/slughotbar2.png")); this.drawTexturedModalRect(2, l/2-90, 0, 0, 24, 133); for (int i1 = 0; i1 < 6; ++i1) { int k1 = l / 2 - 86 + i1 * 22;//change last value to push up or down this.renderInventorySlot(i1, 6, k1); } GL11.glEnable(GL11.GL_BLEND); //rendering selector squares over hotbar if (this.mc.player.getHeldItemOffhand().getItem() instanceof BlasterBase) { this.mc.renderEngine.bindTexture(new ResourceLocation(Strings.MODID, "textures/gui/hotbarsquare.png")); this.drawTexturedModalRect(2, (22 * ((props.getSlot() + 1) % InventorySlug.INV_SIZE)) + (l/2-92)+1, 0, 0, 26, 26); } if (this.mc.player.getHeldItemMainhand().getItem() instanceof BlasterBase) { this.mc.renderEngine.bindTexture(new ResourceLocation(Strings.MODID, "textures/gui/hotbarsquare.png")); this.drawTexturedModalRect(2, (22 * props.getSlot()) + (l/2-92)+1, 0, 0, 26, 26); } } private void renderInventorySlot(int p_73832_1_, int p_73832_2_, int p_73832_3_) { ItemStack itemstack = props.getInventory().getStackInSlot(p_73832_1_); if (itemstack != null) { float f1 = (float)itemstack.getAnimationsToGo(); if (f1 > 0.0F) { GL11.glPushMatrix(); float f2 = 1.0F + f1 / 5.0F; GL11.glTranslatef((float)(p_73832_2_ + 8), (float)(p_73832_3_ + 12), 0.0F); GL11.glScalef(1.0F / f2, (f2 + 1.0F) / 2.0F, 1.0F); GL11.glTranslatef((float)(-(p_73832_2_ + 8)), (float)(-(p_73832_3_ + 12)), 0.0F); } itemRenderer.renderItemAndEffectIntoGUI(itemstack, p_73832_2_, p_73832_3_); if (f1 > 0.0F) { GL11.glPopMatrix(); } itemRenderer.renderItemOverlayIntoGUI(this.mc.fontRendererObj, itemstack, p_73832_2_, p_73832_3_, null); } } }
main/java/com/slugterra/gui/GuiSlugBeltOverlay.java
package com.slugterra.gui; import org.lwjgl.opengl.GL11; import com.slugterra.capabilities.ISlugInv; import com.slugterra.capabilities.SlugInventoryProvider; import com.slugterra.item.SlingerArmour; import com.slugterra.lib.Strings; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Gui; import net.minecraft.client.gui.ScaledResolution; import net.minecraft.client.renderer.RenderItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.event.RenderGameOverlayEvent; import net.minecraftforge.client.event.RenderGameOverlayEvent.ElementType; import net.minecraftforge.fml.common.eventhandler.EventPriority; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; public class GuiSlugBeltOverlay extends Gui{ private Minecraft mc; public static int selslot; protected RenderItem itemRenderer; private ISlugInv props; public GuiSlugBeltOverlay(Minecraft mc){ super(); this.mc = mc; this.itemRenderer = mc.getRenderItem(); // this.props = mc.player.getCapability(SlugInventoryProvider.INV_CAP, null); } @SubscribeEvent(priority = EventPriority.NORMAL) public void onRenderExperienceBar(RenderGameOverlayEvent event){ if(event.isCancelable() || event.getType() != ElementType.HOTBAR){ return; } else if (!(this.mc.player.getItemStackFromSlot(EntityEquipmentSlot.CHEST).getItem() instanceof SlingerArmour)) { // If the player isn't using a slinger belt, disable the bar return; } ScaledResolution scaledresolution = new ScaledResolution(this.mc); // int k = scaledresolution.getScaledWidth(); int l = scaledresolution.getScaledHeight(); GL11.glDisable(GL11.GL_LIGHTING); //get player properties props = ((EntityPlayer)this.mc.player).getCapability(SlugInventoryProvider.INV_CAP, null); //rendering bar this.mc.renderEngine.bindTexture(new ResourceLocation(Strings.MODID, "textures/gui/slughotbar2.png")); this.drawTexturedModalRect(2, l/2-90, 0, 0, 24, 133); for (int i1 = 0; i1 < 6; ++i1) { int k1 = l / 2 - 86 + i1 * 22;//change last value to push up or down this.renderInventorySlot(i1, 6, k1); } GL11.glEnable(GL11.GL_BLEND); //rendering square thing over hotbar this.mc.renderEngine.bindTexture(new ResourceLocation(Strings.MODID, "textures/gui/hotbarsquare.png")); this.drawTexturedModalRect(2, (22 * props.getSlot()) + (l/2-92)+1, 0, 0, 26, 26); } private void renderInventorySlot(int p_73832_1_, int p_73832_2_, int p_73832_3_) { ItemStack itemstack = props.getInventory().getStackInSlot(p_73832_1_); if (itemstack != null) { float f1 = (float)itemstack.getAnimationsToGo(); if (f1 > 0.0F) { GL11.glPushMatrix(); float f2 = 1.0F + f1 / 5.0F; GL11.glTranslatef((float)(p_73832_2_ + 8), (float)(p_73832_3_ + 12), 0.0F); GL11.glScalef(1.0F / f2, (f2 + 1.0F) / 2.0F, 1.0F); GL11.glTranslatef((float)(-(p_73832_2_ + 8)), (float)(-(p_73832_3_ + 12)), 0.0F); } itemRenderer.renderItemAndEffectIntoGUI(itemstack, p_73832_2_, p_73832_3_); if (f1 > 0.0F) { GL11.glPopMatrix(); } itemRenderer.renderItemOverlayIntoGUI(this.mc.fontRendererObj, itemstack, p_73832_2_, p_73832_3_, null); } } }
Show selector squares for both dual-wielded weapons
main/java/com/slugterra/gui/GuiSlugBeltOverlay.java
Show selector squares for both dual-wielded weapons
Java
epl-1.0
611604e5b2efb435c48f8d55163dbe1a85eebb05
0
522986491/controller,mandeepdhami/controller,aryantaheri/monitoring-controller,Johnson-Chou/test,my76128/controller,Sushma7785/OpenDayLight-Load-Balancer,tx1103mark/controller,mandeepdhami/controller,tx1103mark/controller,Sushma7785/OpenDayLight-Load-Balancer,mandeepdhami/controller,opendaylight/controller,aryantaheri/controller,aryantaheri/monitoring-controller,aryantaheri/monitoring-controller,aryantaheri/controller,aryantaheri/controller,inocybe/odl-controller,my76128/controller,Johnson-Chou/test,mandeepdhami/controller,aryantaheri/monitoring-controller,inocybe/odl-controller,tx1103mark/controller,my76128/controller,my76128/controller,tx1103mark/controller,522986491/controller
/* * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.controller.sal.compability; import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeConnector; import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.PortFeatures; import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector; public class ToSalPropertyClassUtils { public static Bandwidth salAdvertisedBandwidthFrom(NodeConnector nodeConnector) { FlowCapableNodeConnector flowCapNodeConn = nodeConnector.getAugmentation(FlowCapableNodeConnector.class); PortFeatures portFeatures = flowCapNodeConn.getAdvertisedFeatures(); return new AdvertisedBandwidth(resolveBandwidth(portFeatures)); } public static Bandwidth salPeerBandwidthFrom(NodeConnector nodeConnector) { FlowCapableNodeConnector flowCapNodeConn = nodeConnector.getAugmentation(FlowCapableNodeConnector.class); PortFeatures portFeatures = flowCapNodeConn.getPeerFeatures(); return new PeerBandwidth(resolveBandwidth(portFeatures)); } public static Bandwidth salSupportedBandwidthFrom(NodeConnector nodeConnector) { FlowCapableNodeConnector flowCapNodeConn = nodeConnector.getAugmentation(FlowCapableNodeConnector.class); PortFeatures portFeatures = flowCapNodeConn.getSupported(); return new SupportedBandwidth(resolveBandwidth(portFeatures)); } public static MacAddress salMacAddressFrom(NodeConnector nodeConnector) { FlowCapableNodeConnector flowCapNodeConn = nodeConnector.getAugmentation(FlowCapableNodeConnector.class); String hwAddress = flowCapNodeConn.getHardwareAddress().getValue(); return new MacAddress(bytesFrom(hwAddress)); } public static Name salNameFrom(NodeConnector nodeConnector) { FlowCapableNodeConnector flowCapNodeConn = nodeConnector.getAugmentation(FlowCapableNodeConnector.class); return new Name(flowCapNodeConn.getName()); } private static byte[] bytesFrom(String hwAddress) { String[] mac = hwAddress.split(":"); byte[] macAddress = new byte[6]; // mac.length == 6 bytes for (int i = 0; i < mac.length; i++) { macAddress[i] = Integer.decode("0x" + mac[i]).byteValue(); } return macAddress; } private static long resolveBandwidth(PortFeatures portFeatures) { if (portFeatures.is_1tbFd()) { return Bandwidth.BW1Tbps; } else if (portFeatures.is_100gbFd()) { return Bandwidth.BW100Gbps; } else if (portFeatures.is_40gbFd()) { return Bandwidth.BW40Gbps; } else if (portFeatures.is_10gbFd()) { return Bandwidth.BW10Gbps; } else if (portFeatures.is_1gbHd() || portFeatures.is_1gbFd()) { return Bandwidth.BW1Gbps; } else if (portFeatures.is_100mbHd() || portFeatures.is_100mbFd()) { return Bandwidth.BW100Mbps; } else if (portFeatures.is_10mbHd() || portFeatures.is_10mbFd()) { return Bandwidth.BW10Mbps; } else { return Bandwidth.BWUNK; } } }
opendaylight/md-sal/sal-compability/src/main/java/org/opendaylight/controller/sal/compability/ToSalPropertyClassUtils.java
/* * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.controller.sal.compability; import org.opendaylight.controller.sal.core.*; import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeConnector; import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.PortFeatures; import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector; public class ToSalPropertyClassUtils { public static Bandwidth salAdvertisedBandwidthFrom(NodeConnector nodeConnector) { FlowCapableNodeConnector flowCapNodeConn = nodeConnector.getAugmentation(FlowCapableNodeConnector.class); PortFeatures portFeatures = flowCapNodeConn.getAdvertisedFeatures(); return new AdvertisedBandwidth(resolveBandwidth(portFeatures)); } public static Bandwidth salPeerBandwidthFrom(NodeConnector nodeConnector) { FlowCapableNodeConnector flowCapNodeConn = nodeConnector.getAugmentation(FlowCapableNodeConnector.class); PortFeatures portFeatures = flowCapNodeConn.getPeerFeatures(); return new PeerBandwidth(resolveBandwidth(portFeatures)); } public static Bandwidth salSupportedBandwidthFrom(NodeConnector nodeConnector) { FlowCapableNodeConnector flowCapNodeConn = nodeConnector.getAugmentation(FlowCapableNodeConnector.class); PortFeatures portFeatures = flowCapNodeConn.getSupported(); return new SupportedBandwidth(resolveBandwidth(portFeatures)); } public static MacAddress salMacAddressFrom(NodeConnector nodeConnector) { FlowCapableNodeConnector flowCapNodeConn = nodeConnector.getAugmentation(FlowCapableNodeConnector.class); String hwAddress = flowCapNodeConn.getHardwareAddress().getValue(); return new MacAddress(bytesFrom(hwAddress)); } public static Name salNameFrom(NodeConnector nodeConnector) { FlowCapableNodeConnector flowCapNodeConn = nodeConnector.getAugmentation(FlowCapableNodeConnector.class); return new Name(flowCapNodeConn.getName()); } private static byte[] bytesFrom(String hwAddress) { String[] mac = hwAddress.split(":"); byte[] macAddress = new byte[6]; // mac.length == 6 bytes for (int i = 0; i < mac.length; i++) { macAddress[i] = Integer.decode("0x" + mac[i]).byteValue(); } return macAddress; } private static long resolveBandwidth(PortFeatures portFeatures) { if (portFeatures.is_1tbFd()) { return Bandwidth.BW1Tbps; } else if (portFeatures.is_100gbFd()) { return Bandwidth.BW100Gbps; } else if (portFeatures.is_40gbFd()) { return Bandwidth.BW40Gbps; } else if (portFeatures.is_10gbFd()) { return Bandwidth.BW10Gbps; } else if (portFeatures.is_1gbHd() || portFeatures.is_1gbFd()) { return Bandwidth.BW1Gbps; } else if (portFeatures.is_100mbHd() || portFeatures.is_100mbFd()) { return Bandwidth.BW100Mbps; } else if (portFeatures.is_10mbHd() || portFeatures.is_10mbFd()) { return Bandwidth.BW10Mbps; } else { return Bandwidth.BWUNK; } } }
BUG-272: fix sal-compatibility FIxes a single issue in sal-compatibility Change-Id: Iafae27bca3d1266b0b4f4492b152cd73d0314641 Signed-off-by: Robert Varga <[email protected]>
opendaylight/md-sal/sal-compability/src/main/java/org/opendaylight/controller/sal/compability/ToSalPropertyClassUtils.java
BUG-272: fix sal-compatibility
Java
epl-1.0
6eb426ab610c33ea287fffd08eebfb735e4bb6d9
0
zy881228/SOEN6441
warGame/CampaignModelTest1.java
package warGame; import java.io.IOException; import java.util.ArrayList; import junit.framework.TestCase; public class CampaignModelTest1 extends TestCase{ WarGameCampaignModel campaignModel = new WarGameCampaignModel(); public void setUp() throws Exception { System.out.println("Campaign Test1 begins"); campaignModel.loadCampaign("Camapaign1"); } public void tearDown() throws Exception { System.out.println("Campaign Test1 ends"); System.out.println(); } public void testEditCampaign() throws IOException{ System.out.println("Test edit campaign"); String changeBefore = new String(); String changeAfter = new String(); String itemID = campaignModel.getCampaignID(); String newCampaign = "Map5"; ArrayList<String> campaignList = campaignModel.getCampaignList(); ArrayList<String> campaignList_reLoad = new ArrayList(); campaignList.add(newCampaign); campaignModel.editCampaign(itemID,campaignList); campaignModel.loadCampaign("Campaign"+itemID); campaignList_reLoad = campaignModel.getCampaignList(); assertEquals(campaignList, campaignList_reLoad); } }
Delete CampaignModelTest1.java
warGame/CampaignModelTest1.java
Delete CampaignModelTest1.java
Java
agpl-3.0
5229482a34a07db9d602b9fde6d03a97ddfcfb4f
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
bab573ce-2e60-11e5-9284-b827eb9e62be
hello.java
baafee5e-2e60-11e5-9284-b827eb9e62be
bab573ce-2e60-11e5-9284-b827eb9e62be
hello.java
bab573ce-2e60-11e5-9284-b827eb9e62be
Java
lgpl-2.1
91bf4fbe04cc6b42ff8c16d5ffba3b965a5e3345
0
exedio/copernica,exedio/copernica,exedio/copernica
/* * Copyright (C) 2004-2005 exedio GmbH (www.exedio.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.exedio.cope; import java.sql.Connection; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.Arrays; import java.util.HashSet; import java.util.Random; import oracle.jdbc.OracleStatement; import bak.pcj.IntIterator; import bak.pcj.list.IntList; import bak.pcj.map.IntKeyChainedHashMap; import com.exedio.dsmf.Column; import com.exedio.dsmf.OracleDriver; import com.exedio.dsmf.SQLRuntimeException; import com.exedio.dsmf.Schema; import com.exedio.dsmf.Table; final class OracleDatabase extends Database implements DatabaseColumnTypesDefinable, DatabaseTimestampCapable { static { try { Class.forName(oracle.jdbc.driver.OracleDriver.class.getName()); } catch(ClassNotFoundException e) { throw new NestingRuntimeException(e); } } protected OracleDatabase(final Properties properties) { super(new OracleDriver(properties.getDatabaseUser().toUpperCase()), properties); } String getIntegerType(final int precision) { return "NUMBER(" + precision + ')'; } String getDoubleType(final int precision) { return "NUMBER(" + precision + ",8)"; } String getStringType(final int maxLength) { return "NVARCHAR2("+(maxLength!=Integer.MAX_VALUE ? maxLength : 2000)+")"; } String getDayType() { return "DATE"; } public String getDateTimestampType() { return "TIMESTAMP(3)"; } boolean appendLimitClause(final Statement bf, final int start, final int count) { // TODO: ROWNUMs cannot be supported through the interface of this method return false; } protected boolean supportsEmptyStrings() { return false; } private String extractConstraintName(final SQLException e, final int vendorCode, final String start, final String end) { if(e.getErrorCode()!=vendorCode) return null; final String m = e.getMessage(); if(m.startsWith(start) && m.endsWith(end)) { final int pos = m.indexOf('.', start.length()); return m.substring(pos+1, m.length()-end.length()); } else return null; } protected String extractUniqueConstraintName(final SQLException e) { return extractConstraintName(e, 1, "ORA-00001: unique constraint (", ") violated\n"); } public void defineColumnTypes(final IntList columnTypes, final java.sql.Statement statement) throws SQLException { //System.out.println("defineColumnTypes: "+columnTypes); final OracleStatement s = (OracleStatement)statement; int columnIndex = 1; for(IntIterator i = columnTypes.iterator(); i.hasNext(); columnIndex++) { final int columnType = i.next(); s.defineColumnType(columnIndex, columnType); } } protected void completeSchema(final Schema schema) { final Table planTable = new Table(schema, "PLAN_TABLE"); planTable.makeDefensive(); new Column(planTable, STATEMENT_ID, "VARCHAR2(30)"); new Column(planTable, "TIMESTAMP", "DATE"); new Column(planTable, "REMARKS", "VARCHAR2(80)"); new Column(planTable, OPERATION, "VARCHAR2(30)"); new Column(planTable, OPTIONS, "VARCHAR2(30)"); new Column(planTable, "OBJECT_NODE", "VARCHAR2(128)"); new Column(planTable, "OBJECT_OWNER", "VARCHAR2(30)"); new Column(planTable, OBJECT_NAME, "VARCHAR2(30)"); new Column(planTable, OBJECT_INSTANCE, "NUMBER(22)"); new Column(planTable, OBJECT_TYPE, "VARCHAR2(30)"); new Column(planTable, "OPTIMIZER", "VARCHAR2(255)"); new Column(planTable, "SEARCH_COLUMNS", "NUMBER(22)"); new Column(planTable, ID, "NUMBER(22)"); new Column(planTable, PARENT_ID, "NUMBER(22)"); new Column(planTable, "POSITION", "NUMBER(22)"); new Column(planTable, "COST", "NUMBER(22)"); new Column(planTable, "CARDINALITY", "NUMBER(22)"); new Column(planTable, "BYTES", "NUMBER(22)"); new Column(planTable, "OTHER_TAG", "VARCHAR2(255)"); new Column(planTable, "OTHER", "LONG"); } protected StatementInfo makeStatementInfo(final Statement statement, final Connection connection) { final StatementInfo result = super.makeStatementInfo(statement, connection); final StatementInfo planInfo = makePlanInfo(statement, connection); if(planInfo!=null) result.addChild(planInfo); return result; } private static final Random statementIDCounter = new Random(); private static final String PLAN_TABLE = "PLAN_TABLE"; private static final String STATEMENT_ID = "STATEMENT_ID"; private static final String OPERATION = "OPERATION"; private static final String OPTIONS = "OPTIONS"; private static final String OBJECT_NAME = "OBJECT_NAME"; private static final String OBJECT_INSTANCE = "OBJECT_INSTANCE"; private static final String OBJECT_TYPE = "OBJECT_TYPE"; private static final String ID = "ID"; private static final String PARENT_ID = "PARENT_ID"; private static final String STATEMENT_ID_PREFIX = "cope"; private static final HashSet skippedColumnNames = new HashSet(Arrays.asList(new String[]{ STATEMENT_ID, OPERATION, OPTIONS, "TIMESTAMP", "OBJECT_OWNER", OBJECT_NAME, OBJECT_INSTANCE, OBJECT_TYPE, ID, PARENT_ID, "POSITION", })); private StatementInfo makePlanInfo(final Statement statement, final Connection connection) { final String statementText = statement.getText(); if(statementText.startsWith("alter table ")) return null; final int statementID; synchronized(statementIDCounter) { statementID = Math.abs(statementIDCounter.nextInt()); } final StatementInfo root; { final Statement explainStatement = createStatement(); explainStatement. append("explain plan set "+STATEMENT_ID+"='"+STATEMENT_ID_PREFIX). append(Integer.toString(statementID)). // TODO use placeholders for prepared statements append("' for "). append(statementText); java.sql.Statement sqlExplainStatement = null; try { // TODO: use executeSQLUpdate sqlExplainStatement = connection.createStatement(); sqlExplainStatement.executeUpdate(explainStatement.getText()); } catch(SQLException e) { throw new SQLRuntimeException(e, explainStatement.toString()); } finally { if(sqlExplainStatement!=null) { try { sqlExplainStatement.close(); } catch(SQLException e) { // exception is already thrown } } } } { final Statement fetchStatement = createStatement(); fetchStatement. append( "select * from "+PLAN_TABLE+' ' + "where "+STATEMENT_ID+"='"+STATEMENT_ID_PREFIX). append(Integer.toString(statementID)). // TODO use placeholders for prepared statements append("' order by "+ID); final PlanResultSetHandler handler = new PlanResultSetHandler(); executeSQLQuery(connection, fetchStatement, handler, false); root = handler.root; } if(root==null) throw new RuntimeException(); final StatementInfo result = new StatementInfo("execution plan statement_id = " + STATEMENT_ID_PREFIX + statementID); result.addChild(root); //System.out.println("######################"); //System.out.println(statement.getText()); //root.print(System.out); //System.out.println("######################"); return result; } private static class PlanResultSetHandler implements ResultSetHandler { StatementInfo root; public void run(final ResultSet resultSet) throws SQLException { final IntKeyChainedHashMap infos = new IntKeyChainedHashMap(); final ResultSetMetaData metaData = resultSet.getMetaData(); final int columnCount = metaData.getColumnCount(); while(resultSet.next()) { final String operation = resultSet.getString(OPERATION); final String options = resultSet.getString(OPTIONS); final String objectName = resultSet.getString(OBJECT_NAME); final int objectInstance = resultSet.getInt(OBJECT_INSTANCE); final String objectType = resultSet.getString(OBJECT_TYPE); final int id = resultSet.getInt(ID); final Number parentID = (Number)resultSet.getObject(PARENT_ID); final StringBuffer bf = new StringBuffer(operation); if(options!=null) bf.append(" (").append(options).append(')'); if(objectName!=null) bf.append(" on ").append(objectName); if(objectInstance!=0) bf.append('[').append(objectInstance).append(']'); if(objectType!=null) bf.append('[').append(objectType).append(']'); for(int i = 1; i<=columnCount; i++) { final String columnName = metaData.getColumnName(i); if(!skippedColumnNames.contains(columnName)) { final Object value = resultSet.getObject(i); if(value!=null) { bf.append(' '). append(columnName.toLowerCase()). append('='). append(value.toString()); } } } final StatementInfo info = new StatementInfo(bf.toString()); if(parentID==null) { if(root!=null) throw new RuntimeException(String.valueOf(id)); root = info; } else { final StatementInfo parent = (StatementInfo)infos.get(parentID.intValue()); if(parent==null) throw new RuntimeException(); parent.addChild(info); } infos.put(id, info); } } } }
lib/oraclesrc/com/exedio/cope/OracleDatabase.java
/* * Copyright (C) 2004-2005 exedio GmbH (www.exedio.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.exedio.cope; import java.sql.Connection; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.Arrays; import java.util.HashSet; import java.util.Random; import oracle.jdbc.OracleStatement; import bak.pcj.IntIterator; import bak.pcj.list.IntList; import bak.pcj.map.IntKeyChainedHashMap; import com.exedio.dsmf.Column; import com.exedio.dsmf.OracleDriver; import com.exedio.dsmf.SQLRuntimeException; import com.exedio.dsmf.Schema; import com.exedio.dsmf.Table; final class OracleDatabase extends Database implements DatabaseColumnTypesDefinable, DatabaseTimestampCapable { static { try { Class.forName(oracle.jdbc.driver.OracleDriver.class.getName()); } catch(ClassNotFoundException e) { throw new NestingRuntimeException(e); } } protected OracleDatabase(final Properties properties) { super(new OracleDriver(properties.getDatabaseUser().toUpperCase()), properties); } String getIntegerType(final int precision) { return "NUMBER(" + precision + ')'; } String getDoubleType(final int precision) { return "NUMBER(" + precision + ",8)"; } String getStringType(final int maxLength) { return "NVARCHAR2("+(maxLength!=Integer.MAX_VALUE ? maxLength : 2000)+")"; } String getDayType() { return "DATE"; } public String getDateTimestampType() { return "TIMESTAMP(3)"; } boolean appendLimitClause(final Statement bf, final int start, final int count) { // TODO: ROWNUMs cannot be supported through the interface of this method return false; } protected boolean supportsEmptyStrings() { return false; } private String extractConstraintName(final SQLException e, final int vendorCode, final String start, final String end) { if(e.getErrorCode()!=vendorCode) return null; final String m = e.getMessage(); if(m.startsWith(start) && m.endsWith(end)) { final int pos = m.indexOf('.', start.length()); return m.substring(pos+1, m.length()-end.length()); } else return null; } protected String extractUniqueConstraintName(final SQLException e) { return extractConstraintName(e, 1, "ORA-00001: unique constraint (", ") violated\n"); } public void defineColumnTypes(final IntList columnTypes, final java.sql.Statement statement) throws SQLException { //System.out.println("defineColumnTypes: "+columnTypes); final OracleStatement s = (OracleStatement)statement; int columnIndex = 1; for(IntIterator i = columnTypes.iterator(); i.hasNext(); columnIndex++) { final int columnType = i.next(); s.defineColumnType(columnIndex, columnType); } } protected void completeSchema(final Schema schema) { final Table planTable = new Table(schema, "PLAN_TABLE"); planTable.makeDefensive(); new Column(planTable, STATEMENT_ID, "VARCHAR2(30)"); new Column(planTable, "TIMESTAMP", "DATE"); new Column(planTable, "REMARKS", "VARCHAR2(80)"); new Column(planTable, OPERATION, "VARCHAR2(30)"); new Column(planTable, OPTIONS, "VARCHAR2(30)"); new Column(planTable, "OBJECT_NODE", "VARCHAR2(128)"); new Column(planTable, "OBJECT_OWNER", "VARCHAR2(30)"); new Column(planTable, OBJECT_NAME, "VARCHAR2(30)"); new Column(planTable, OBJECT_INSTANCE, "NUMBER(22)"); new Column(planTable, OBJECT_TYPE, "VARCHAR2(30)"); new Column(planTable, "OPTIMIZER", "VARCHAR2(255)"); new Column(planTable, "SEARCH_COLUMNS", "NUMBER(22)"); new Column(planTable, ID, "NUMBER(22)"); new Column(planTable, PARENT_ID, "NUMBER(22)"); new Column(planTable, "POSITION", "NUMBER(22)"); new Column(planTable, "COST", "NUMBER(22)"); new Column(planTable, "CARDINALITY", "NUMBER(22)"); new Column(planTable, "BYTES", "NUMBER(22)"); new Column(planTable, "OTHER_TAG", "VARCHAR2(255)"); new Column(planTable, "OTHER", "LONG"); } protected StatementInfo makeStatementInfo(final Statement statement, final Connection connection) { final StatementInfo result = super.makeStatementInfo(statement, connection); final StatementInfo planInfo = makePlanInfo(statement, connection); if(planInfo!=null) result.addChild(planInfo); return result; } private static final Random statementIDCounter = new Random(); private static final String PLAN_TABLE = "PLAN_TABLE"; private static final String STATEMENT_ID = "STATEMENT_ID"; private static final String OPERATION = "OPERATION"; private static final String OPTIONS = "OPTIONS"; private static final String OBJECT_NAME = "OBJECT_NAME"; private static final String OBJECT_INSTANCE = "OBJECT_INSTANCE"; private static final String OBJECT_TYPE = "OBJECT_TYPE"; private static final String ID = "ID"; private static final String PARENT_ID = "PARENT_ID"; private static final String STATEMENT_ID_PREFIX = "cope"; private static final HashSet skippedColumnNames = new HashSet(Arrays.asList(new String[]{ STATEMENT_ID, OPERATION, OPTIONS, "TIMESTAMP", "OBJECT_OWNER", OBJECT_NAME, OBJECT_INSTANCE, OBJECT_TYPE, ID, PARENT_ID, "POSITION", })); private StatementInfo makePlanInfo(final Statement statement, final Connection connection) { final String statementText = statement.getText(); if(statementText.startsWith("alter table ")) return null; final int statementID; synchronized(statementIDCounter) { statementID = Math.abs(statementIDCounter.nextInt()); } final StatementInfo root; { final Statement explainStatement = createStatement(); explainStatement. append("explain plan set "+STATEMENT_ID+"='"+STATEMENT_ID_PREFIX). append(Integer.toString(statementID)). // TODO use placeholders for prepared statements append("' for "). append(statementText); java.sql.Statement sqlExplainStatement = null; try { // TODO: use executeSQLUpdate sqlExplainStatement = connection.createStatement(); sqlExplainStatement.executeUpdate(explainStatement.getText()); } catch(SQLException e) { throw new SQLRuntimeException(e, explainStatement.toString()); } finally { if(sqlExplainStatement!=null) { try { sqlExplainStatement.close(); } catch(SQLException e) { // exception is already thrown } } } } { final Statement fetchStatement = createStatement(); fetchStatement. append( "select * from "+PLAN_TABLE+' ' + "where "+STATEMENT_ID+"='"+STATEMENT_ID_PREFIX). append(Integer.toString(statementID)). // TODO use placeholders for prepared statements append("' order by "+ID); final PlanResultSetHandler handler = new PlanResultSetHandler(); executeSQLQuery(connection, fetchStatement, handler, false); root = handler.root; } if(root==null) throw new RuntimeException(); final StatementInfo result = new StatementInfo("execution plan statement_id = " + STATEMENT_ID_PREFIX + statementID); result.addChild(root); //System.out.println("######################"); //System.out.println(statement.getText()); //root.print(System.out); //System.out.println("######################"); return result; } private static class PlanResultSetHandler implements ResultSetHandler { StatementInfo root; public void run(final ResultSet sqlFetchResultSet) throws SQLException { final IntKeyChainedHashMap infos = new IntKeyChainedHashMap(); final ResultSetMetaData metaData = sqlFetchResultSet.getMetaData(); final int columnCount = metaData.getColumnCount(); while(sqlFetchResultSet.next()) { final String operation = sqlFetchResultSet.getString(OPERATION); final String options = sqlFetchResultSet.getString(OPTIONS); final String objectName = sqlFetchResultSet.getString(OBJECT_NAME); final int objectInstance = sqlFetchResultSet.getInt(OBJECT_INSTANCE); final String objectType = sqlFetchResultSet.getString(OBJECT_TYPE); final int id = sqlFetchResultSet.getInt(ID); final Number parentID = (Number)sqlFetchResultSet.getObject(PARENT_ID); final StringBuffer bf = new StringBuffer(operation); if(options!=null) bf.append(" (").append(options).append(')'); if(objectName!=null) bf.append(" on ").append(objectName); if(objectInstance!=0) bf.append('[').append(objectInstance).append(']'); if(objectType!=null) bf.append('[').append(objectType).append(']'); for(int i = 1; i<=columnCount; i++) { final String columnName = metaData.getColumnName(i); if(!skippedColumnNames.contains(columnName)) { final Object value = sqlFetchResultSet.getObject(i); if(value!=null) { bf.append(' '). append(columnName.toLowerCase()). append('='). append(value.toString()); } } } final StatementInfo info = new StatementInfo(bf.toString()); if(parentID==null) { if(root!=null) throw new RuntimeException(String.valueOf(id)); root = info; } else { final StatementInfo parent = (StatementInfo)infos.get(parentID.intValue()); if(parent==null) throw new RuntimeException(); parent.addChild(info); } infos.put(id, info); } } } }
rename sqlFetchResultSet to resultSet git-svn-id: 9dbc6da3594b32e13bcf3b3752e372ea5bc7c2cc@3712 e7d4fc99-c606-0410-b9bf-843393a9eab7
lib/oraclesrc/com/exedio/cope/OracleDatabase.java
rename sqlFetchResultSet to resultSet
Java
lgpl-2.1
eda477180fafce39acd80d2fde4e0ea398394850
0
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
// // $Id$ // // Narya library - tools for developing networked games // Copyright (C) 2002-2004 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/narya/ // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.parlor.game.client; import java.awt.event.ActionEvent; import com.threerings.presents.dobj.AttributeChangeListener; import com.threerings.presents.dobj.AttributeChangedEvent; import com.threerings.crowd.client.PlaceController; import com.threerings.crowd.client.PlaceControllerDelegate; import com.threerings.crowd.data.BodyObject; import com.threerings.crowd.data.PlaceConfig; import com.threerings.crowd.data.PlaceObject; import com.threerings.crowd.util.CrowdContext; import com.threerings.parlor.Log; import com.threerings.parlor.game.data.GameCodes; import com.threerings.parlor.game.data.GameConfig; import com.threerings.parlor.game.data.GameObject; import com.threerings.parlor.game.data.PartyGameConfig; import com.threerings.parlor.util.ParlorContext; /** * The game controller manages the flow and control of a game on the * client side. This class serves as the root of a hierarchy of controller * classes that aim to provide functionality shared between various * similar games. The base controller provides functionality for starting * and ending the game and for calculating ratings adjustements when a * game ends normally. It also handles the basic house keeping like * subscription to the game object and dispatch of commands and * distributed object events. */ public abstract class GameController extends PlaceController implements AttributeChangeListener { /** * Initializes this game controller with the game configuration that * was established during the match making process. Derived classes * may want to override this method to initialize themselves with * game-specific configuration parameters but they should be sure to * call <code>super.init</code> in such cases. * * @param ctx the client context. * @param config the configuration of the game we are intended to * control. */ public void init (CrowdContext ctx, PlaceConfig config) { // cast our references before we call super.init() so that when // super.init() calls createPlaceView(), we have our casted // references already in place _ctx = (ParlorContext)ctx; _config = (GameConfig)config; super.init(ctx, config); } /** * Adds this controller as a listener to the game object (thus derived * classes need not do so) and lets the game manager know that we are * now ready to go. */ public void willEnterPlace (PlaceObject plobj) { super.willEnterPlace(plobj); // obtain a casted reference _gobj = (GameObject)plobj; // if this place object is not our current location we'll need to // add it as an auxiliary chat source BodyObject bobj = (BodyObject)_ctx.getClient().getClientObject(); if (bobj.location != plobj.getOid()) { _ctx.getChatDirector().addAuxiliarySource( _gobj, GameCodes.GAME_CHAT_TYPE); } // and add ourselves as a listener _gobj.addListener(this); // we don't want to claim to be finished until any derived classes // that overrode this method have executed, so we'll queue up a // runnable here that will let the game manager know that we're // ready on the next pass through the distributed event loop Log.info("Entering game " + _gobj.which() + "."); if (_gobj.getPlayerIndex(bobj.username) != -1) { _ctx.getClient().getRunQueue().postRunnable(new Runnable() { public void run () { // finally let the game manager know that we're ready // to roll Log.info("Reporting ready " + _gobj.which() + "."); _gobj.gameService.playerReady(_ctx.getClient()); } }); } } /** * Removes our listener registration from the game object and cleans * house. */ public void didLeavePlace (PlaceObject plobj) { super.didLeavePlace(plobj); _ctx.getChatDirector().removeAuxiliarySource(_gobj); // unlisten to the game object _gobj.removeListener(this); _gobj = null; } /** * Returns whether the game is over. */ public boolean isGameOver () { boolean gameOver = ((_gobj != null) ? (_gobj.state != GameObject.IN_PLAY) : true); return (_gameOver || gameOver); } /** * Sets the client game over override. This is used in situations * where we determine that the game is over before the server has * informed us of such. */ public void setGameOver (boolean gameOver) { _gameOver = gameOver; } /** * Calls {@link #gameWillReset}, ends the current game (locally, it * does not tell the server to end the game), and waits to receive a * reset notification (which is simply an event setting the game state * to <code>IN_PLAY</code> even though it's already set to * <code>IN_PLAY</code>) from the server which will start up a new * game. Derived classes should override {@link #gameWillReset} to * perform any game-specific animations. */ public void resetGame () { // let derived classes do their thing gameWillReset(); // end the game until we receive a new board setGameOver(true); } /** * Returns the unique round identifier for the current round. */ public int getRoundId () { return (_gobj == null) ? -1 : _gobj.roundId; } /** * Handles basic game controller action events. Derived classes should * be sure to call <code>super.handleAction</code> for events they * don't specifically handle. */ public boolean handleAction (ActionEvent action) { return super.handleAction(action); } /** * A way for controllers to display a game-related system message. */ public void systemMessage (String bundle, String msg) { _ctx.getChatDirector().displayInfo( bundle, msg, GameCodes.GAME_CHAT_TYPE); } // documentation inherited public void attributeChanged (AttributeChangedEvent event) { // deal with game state changes if (event.getName().equals(GameObject.STATE)) { if (!handleStateChange(event.getIntValue())) { Log.warning("Game transitioned to unknown state " + "[gobj=" + _gobj + ", state=" + event.getIntValue() + "]."); } } } /** * Derived classes can override this method if they add additional * game states and should handle transitions to those states, * returning true to indicate they were handled and calling super for * the normal game states. */ protected boolean handleStateChange (int state) { switch (state) { case GameObject.IN_PLAY: gameDidStart(); return true; case GameObject.GAME_OVER: gameDidEnd(); return true; case GameObject.CANCELLED: gameWasCancelled(); return true; } return false; } /** * Called when the game transitions to the <code>IN_PLAY</code> * state. This happens when all of the players have arrived and the * server starts the game. */ protected void gameDidStart () { if (_gobj == null) { Log.info("Received gameDidStart() after leaving game room."); return; } // clear out our game over flag setGameOver(false); // let our delegates do their business applyToDelegates(new DelegateOp() { public void apply (PlaceControllerDelegate delegate) { ((GameControllerDelegate)delegate).gameDidStart(); } }); } /** * Called when the game transitions to the <code>GAME_OVER</code> * state. This happens when the game reaches some end condition by * normal means (is not cancelled or aborted). */ protected void gameDidEnd () { // let our delegates do their business applyToDelegates(new DelegateOp() { public void apply (PlaceControllerDelegate delegate) { ((GameControllerDelegate)delegate).gameDidEnd(); } }); } /** * Called when the game was cancelled for some reason. */ protected void gameWasCancelled () { // let our delegates do their business applyToDelegates(new DelegateOp() { public void apply (PlaceControllerDelegate delegate) { ((GameControllerDelegate)delegate).gameWasCancelled(); } }); } /** * Called to give derived classes a chance to display animations, send * a final packet, or do any other business they care to do when the * game is about to reset. */ protected void gameWillReset () { // let our delegates do their business applyToDelegates(new DelegateOp() { public void apply (PlaceControllerDelegate delegate) { ((GameControllerDelegate)delegate).gameWillReset(); } }); } /** * Used to determine if this game is a party game. */ protected boolean isPartyGame () { return ((_config instanceof PartyGameConfig) && ((PartyGameConfig)_config).isPartyGame()); } /** A reference to the active parlor context. */ protected ParlorContext _ctx; /** Our game configuration information. */ protected GameConfig _config; /** A reference to the game object for the game that we're * controlling. */ protected GameObject _gobj; /** A local flag overriding the game over state for situations where * the client knows the game is over before the server has * transitioned the game object accordingly. */ protected boolean _gameOver; }
src/java/com/threerings/parlor/game/client/GameController.java
// // $Id$ // // Narya library - tools for developing networked games // Copyright (C) 2002-2004 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/narya/ // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.parlor.game.client; import java.awt.event.ActionEvent; import com.threerings.presents.dobj.AttributeChangeListener; import com.threerings.presents.dobj.AttributeChangedEvent; import com.threerings.crowd.client.PlaceController; import com.threerings.crowd.client.PlaceControllerDelegate; import com.threerings.crowd.data.BodyObject; import com.threerings.crowd.data.PlaceConfig; import com.threerings.crowd.data.PlaceObject; import com.threerings.crowd.util.CrowdContext; import com.threerings.parlor.Log; import com.threerings.parlor.game.data.GameCodes; import com.threerings.parlor.game.data.GameConfig; import com.threerings.parlor.game.data.GameObject; import com.threerings.parlor.game.data.PartyGameConfig; import com.threerings.parlor.util.ParlorContext; /** * The game controller manages the flow and control of a game on the * client side. This class serves as the root of a hierarchy of controller * classes that aim to provide functionality shared between various * similar games. The base controller provides functionality for starting * and ending the game and for calculating ratings adjustements when a * game ends normally. It also handles the basic house keeping like * subscription to the game object and dispatch of commands and * distributed object events. */ public abstract class GameController extends PlaceController implements AttributeChangeListener { /** * Initializes this game controller with the game configuration that * was established during the match making process. Derived classes * may want to override this method to initialize themselves with * game-specific configuration parameters but they should be sure to * call <code>super.init</code> in such cases. * * @param ctx the client context. * @param config the configuration of the game we are intended to * control. */ public void init (CrowdContext ctx, PlaceConfig config) { // cast our references before we call super.init() so that when // super.init() calls createPlaceView(), we have our casted // references already in place _ctx = (ParlorContext)ctx; _config = (GameConfig)config; super.init(ctx, config); } /** * Adds this controller as a listener to the game object (thus derived * classes need not do so) and lets the game manager know that we are * now ready to go. */ public void willEnterPlace (PlaceObject plobj) { super.willEnterPlace(plobj); // obtain a casted reference _gobj = (GameObject)plobj; // if this place object is not our current location we'll need to // add it as an auxiliary chat source BodyObject bobj = (BodyObject)_ctx.getClient().getClientObject(); if (bobj.location != plobj.getOid()) { _ctx.getChatDirector().addAuxiliarySource( _gobj, GameCodes.GAME_CHAT_TYPE); } // and add ourselves as a listener _gobj.addListener(this); // we don't want to claim to be finished until any derived classes // that overrode this method have executed, so we'll queue up a // runnable here that will let the game manager know that we're // ready on the next pass through the distributed event loop Log.info("Entering game " + _gobj.which() + "."); if (_gobj.getPlayerIndex(bobj.username) != -1) { _ctx.getClient().getRunQueue().postRunnable(new Runnable() { public void run () { // finally let the game manager know that we're ready // to roll Log.info("Reporting ready " + _gobj.which() + "."); _gobj.gameService.playerReady(_ctx.getClient()); } }); } } /** * Removes our listener registration from the game object and cleans * house. */ public void didLeavePlace (PlaceObject plobj) { super.didLeavePlace(plobj); _ctx.getChatDirector().removeAuxiliarySource(_gobj); // unlisten to the game object _gobj.removeListener(this); _gobj = null; } /** * Returns whether the game is over. */ public boolean isGameOver () { boolean gameOver = ((_gobj != null) ? (_gobj.state != GameObject.IN_PLAY) : true); return (_gameOver || gameOver); } /** * Sets the client game over override. This is used in situations * where we determine that the game is over before the server has * informed us of such. */ public void setGameOver (boolean gameOver) { _gameOver = gameOver; } /** * Calls {@link #gameWillReset}, ends the current game (locally, it * does not tell the server to end the game), and waits to receive a * reset notification (which is simply an event setting the game state * to <code>IN_PLAY</code> even though it's already set to * <code>IN_PLAY</code>) from the server which will start up a new * game. Derived classes should override {@link #gameWillReset} to * perform any game-specific animations. */ public void resetGame () { // let derived classes do their thing gameWillReset(); // end the game until we receive a new board setGameOver(true); } /** * Returns the unique round identifier for the current round. */ public int getRoundId () { return (_gobj == null) ? -1 : _gobj.roundId; } /** * Handles basic game controller action events. Derived classes should * be sure to call <code>super.handleAction</code> for events they * don't specifically handle. */ public boolean handleAction (ActionEvent action) { return super.handleAction(action); } /** * A way for controllers to display a game-related system message. */ public void systemMessage (String bundle, String msg) { _ctx.getChatDirector().displayInfo( bundle, msg, GameCodes.GAME_CHAT_TYPE); } // documentation inherited public void attributeChanged (AttributeChangedEvent event) { // deal with game state changes if (event.getName().equals(GameObject.STATE)) { switch (event.getIntValue()) { case GameObject.IN_PLAY: gameDidStart(); break; case GameObject.GAME_OVER: gameDidEnd(); break; case GameObject.CANCELLED: gameWasCancelled(); break; default: Log.warning("Game transitioned to unknown state " + "[gobj=" + _gobj + ", state=" + event.getIntValue() + "]."); break; } } } /** * Called when the game transitions to the <code>IN_PLAY</code> * state. This happens when all of the players have arrived and the * server starts the game. */ protected void gameDidStart () { if (_gobj == null) { Log.info("Received gameDidStart() after leaving game room."); return; } // clear out our game over flag setGameOver(false); // let our delegates do their business applyToDelegates(new DelegateOp() { public void apply (PlaceControllerDelegate delegate) { ((GameControllerDelegate)delegate).gameDidStart(); } }); } /** * Called when the game transitions to the <code>GAME_OVER</code> * state. This happens when the game reaches some end condition by * normal means (is not cancelled or aborted). */ protected void gameDidEnd () { // let our delegates do their business applyToDelegates(new DelegateOp() { public void apply (PlaceControllerDelegate delegate) { ((GameControllerDelegate)delegate).gameDidEnd(); } }); } /** * Called when the game was cancelled for some reason. */ protected void gameWasCancelled () { // let our delegates do their business applyToDelegates(new DelegateOp() { public void apply (PlaceControllerDelegate delegate) { ((GameControllerDelegate)delegate).gameWasCancelled(); } }); } /** * Called to give derived classes a chance to display animations, send * a final packet, or do any other business they care to do when the * game is about to reset. */ protected void gameWillReset () { // let our delegates do their business applyToDelegates(new DelegateOp() { public void apply (PlaceControllerDelegate delegate) { ((GameControllerDelegate)delegate).gameWillReset(); } }); } /** * Used to determine if this game is a party game. */ protected boolean isPartyGame () { return ((_config instanceof PartyGameConfig) && ((PartyGameConfig)_config).isPartyGame()); } /** A reference to the active parlor context. */ protected ParlorContext _ctx; /** Our game configuration information. */ protected GameConfig _config; /** A reference to the game object for the game that we're * controlling. */ protected GameObject _gobj; /** A local flag overriding the game over state for situations where * the client knows the game is over before the server has * transitioned the game object accordingly. */ protected boolean _gameOver; }
Allow additional game states. git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@3485 542714f4-19e9-0310-aa3c-eee0fc999fb1
src/java/com/threerings/parlor/game/client/GameController.java
Allow additional game states.
Java
lgpl-2.1
6179ca71a234381e086adb6cf06644faf5a26e0e
0
sewe/spotbugs,spotbugs/spotbugs,KengoTODA/spotbugs,spotbugs/spotbugs,KengoTODA/spotbugs,johnscancella/spotbugs,sewe/spotbugs,sewe/spotbugs,spotbugs/spotbugs,spotbugs/spotbugs,KengoTODA/spotbugs,johnscancella/spotbugs,KengoTODA/spotbugs,spotbugs/spotbugs,johnscancella/spotbugs,johnscancella/spotbugs,sewe/spotbugs
/* * Bytecode Analysis Framework * Copyright (C) 2003, University of Maryland * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package edu.umd.cs.daveho.ba; import java.util.*; // We require BCEL 5.0 or later. import org.apache.bcel.*; import org.apache.bcel.classfile.*; import org.apache.bcel.generic.*; /** * An accurate CFGBuilder. This implementation of CFGBuilder is intended * to produce CFGs that are accurate with respect to exceptions. * Specifically, exception edges are always inserted <em>before</em> * potentially excepting instructions (PEIs). In general, it is useful and * accurate to view the occurance of an exception as precluding the * execution of the instruction throwing the exception. * * <p> TODO: ATHROW should really have exception edges both before * (NullPointerException if TOS has the null value) and after (the thrown exception) * the instruction. Right now we only have after. * * <p> Because of the accurate treatment of exceptions, CFGs produced with this * CFGBuilder can be used to perform dataflow analysis on. Assuming that the * Java source-to-bytecode compiler generated good code, all dataflow values * should merge successfully at control joins. * * @see CFG * @see CFGBuilder * @see Dataflow * @author David Hovemeyer */ public class BetterCFGBuilder implements CFGBuilder, EdgeTypes { private static final boolean DEBUG = Boolean.getBoolean("cfgbuilder.debug"); /* ---------------------------------------------------------------------- * Helper classes * ---------------------------------------------------------------------- */ private static class WorkListItem { public final InstructionHandle start; public final BasicBlock basicBlock; public final LinkedList<InstructionHandle> jsrStack; public boolean handledPEI; public WorkListItem(InstructionHandle start, BasicBlock basicBlock, LinkedList<InstructionHandle> jsrStack, boolean handledPEI) { this.start = start; this.basicBlock = basicBlock; this.jsrStack = jsrStack; this.handledPEI = handledPEI; } } /* ---------------------------------------------------------------------- * Constants * ---------------------------------------------------------------------- */ // Reasons for why a basic block was ended. private static final int BRANCH = 0; private static final int MERGE = 1; private static final int NEXT_IS_PEI = 2; /* ---------------------------------------------------------------------- * Data members * ---------------------------------------------------------------------- */ private MethodGen methodGen; private ConstantPoolGen cpg; private CFG cfg; private LinkedList<WorkListItem> workList; private IdentityHashMap<InstructionHandle, BasicBlock> basicBlockMap; private IdentityHashMap<InstructionHandle, BasicBlock> allHandlesToBasicBlockMap; private ExceptionHandlerMap exceptionHandlerMap; /* ---------------------------------------------------------------------- * Public methods * ---------------------------------------------------------------------- */ public BetterCFGBuilder(MethodGen methodGen) { this.methodGen = methodGen; this.cpg = methodGen.getConstantPool(); this.cfg = new CFG(); this.workList = new LinkedList<WorkListItem>(); this.basicBlockMap = new IdentityHashMap<InstructionHandle, BasicBlock>(); this.allHandlesToBasicBlockMap = new IdentityHashMap<InstructionHandle, BasicBlock>(); this.exceptionHandlerMap = new ExceptionHandlerMap(methodGen); } public void setMode(int mode) { } public void build() { getBlock(methodGen.getInstructionList().getStart(), new LinkedList<InstructionHandle>()); workListLoop: while (!workList.isEmpty()) { WorkListItem item = workList.removeFirst(); InstructionHandle start = item.start; BasicBlock basicBlock = item.basicBlock; LinkedList<InstructionHandle> jsrStack = item.jsrStack; boolean handledPEI = item.handledPEI; if (DEBUG) System.out.println("START BLOCK " + basicBlock.getId()); // If the start instruction is a PEI which we haven't handled yet, then // this block is an Exception Thrower Block (ETB). if (isPEI(start) && !handledPEI) { // This block is an ETB. basicBlock.setExceptionThrower(true); // Add handled exception edges. addExceptionEdges(start, basicBlock, jsrStack); // Add fall through edge. Note that we add the work list item for the // new block by hand, because getBlock() // (1) sets handledPEI to false, and // (2) maps the start instruction to the new block; the ETB is // the correct block for the start instruction, not the // fall through block BasicBlock nextBasicBlock = cfg.allocate(); addEdge(basicBlock, nextBasicBlock, FALL_THROUGH_EDGE); WorkListItem nextItem = new WorkListItem(start, nextBasicBlock, jsrStack, true); workList.add(nextItem); continue workListLoop; } InstructionHandle handle = start; InstructionHandle next = null; TargetEnumeratingVisitor visitor = null; int endBlockMode; // Add instructions to the basic block scanInstructionsLoop: while (true) { // Add the instruction to the block basicBlock.addInstruction(handle); if (DEBUG) System.out.println("** Add " + handle + (isPEI(handle) ? " [PEI]" : "")); // Except for instructions in JSR subroutines, no instruction should be // in more than one basic block. if (allHandlesToBasicBlockMap.get(handle) != null && jsrStack.isEmpty()) throw new IllegalStateException("Instruction in multiple blocks: " + handle); allHandlesToBasicBlockMap.put(handle, basicBlock); // PEIs should always be the first instruction in the basic block if (isPEI(handle) && handle != basicBlock.getFirstInstruction()) throw new IllegalStateException("PEI is not first instruction in block!"); // This will be assigned if the potential next instruction in the // basic block is something other than what would be returned // by handle.getNext(). This only happens for JSR and RET instructions. next = null; Instruction ins = handle.getInstruction(); // Handle JSR, RET, and explicit branches. if (ins instanceof JsrInstruction) { // Remember where we came from jsrStack.addLast(handle); // Transfer control to the subroutine JsrInstruction jsr = (JsrInstruction) ins; next = jsr.getTarget(); } else if (ins instanceof RET) { // Return control to instruction after JSR next = jsrStack.removeLast().getNext(); } else if ((visitor = new TargetEnumeratingVisitor(handle, cpg)).isEndOfBasicBlock()) { // Basic block ends with explicit branch. endBlockMode = BRANCH; break scanInstructionsLoop; } // If control gets here, then the current instruction was not cause // for ending the basic block. Check the next instruction, which may // be cause for ending the block. if (next == null) next = handle.getNext(); if (next == null) throw new IllegalStateException("Falling off end of method: " + handle); // Control merge? if (isMerge(next)) { endBlockMode = MERGE; break scanInstructionsLoop; } // Next instruction is a PEI? if (isPEI(next)) { endBlockMode = NEXT_IS_PEI; break scanInstructionsLoop; } // The basic block definitely continues to the next instruction. handle = next; } if (DEBUG) dumpBlock(basicBlock); // Depending on how the basic block ended, add appropriate edges to the CFG. if (next != null) { // There is a successor instruction, meaning that this // is a control merge, or the block was ended because of a PEI. // In either case, just fall through to the successor. if (endBlockMode != MERGE && endBlockMode != NEXT_IS_PEI) throw new IllegalStateException("next != null, but not merge or PEI"); BasicBlock nextBlock = getBlock(next, jsrStack); addEdge(basicBlock, nextBlock, FALL_THROUGH_EDGE); } else { // There is no successor instruction, meaning that the block ended // in an explicit branch of some sort. if (endBlockMode != BRANCH) throw new IllegalStateException("next == null, but not branch"); if (visitor.instructionIsThrow()) { // Explicit ATHROW instruction. Add exception edges, // and mark the block as an ETB. addExceptionEdges(handle, basicBlock, jsrStack); basicBlock.setExceptionThrower(true); } else if (visitor.instructionIsReturn() || visitor.instructionIsExit()) { // Return or call to System.exit(). In either case, // add a return edge. addEdge(basicBlock, cfg.getExit(), RETURN_EDGE); } else { // The TargetEnumeratingVisitor takes care of telling us what the targets are. // (This includes the fall through edges for IF branches.) Iterator<Target> i = visitor.targetIterator(); while (i.hasNext()) { Target target = i.next(); BasicBlock targetBlock = getBlock(target.getTargetInstruction(), jsrStack); addEdge(basicBlock, targetBlock, target.getEdgeType()); } } } } } public CFG getCFG() { return cfg; } /* ---------------------------------------------------------------------- * Private methods * ---------------------------------------------------------------------- */ private boolean isPEI(InstructionHandle handle) { Instruction ins = handle.getInstruction(); //return (ins instanceof ExceptionThrower) && !(ins instanceof ATHROW); if (!(ins instanceof ExceptionThrower)) return false; if (ins instanceof ATHROW) return false; if (ins instanceof ReturnInstruction && !methodGen.isSynchronized()) return false; return true; } private BasicBlock getBlock(InstructionHandle start, LinkedList<InstructionHandle> jsrStack) { BasicBlock basicBlock = basicBlockMap.get(start); if (basicBlock == null) { basicBlock = cfg.allocate(); basicBlockMap.put(start, basicBlock); WorkListItem item = new WorkListItem(start, basicBlock, cloneJsrStack(jsrStack), false); workList.add(item); } return basicBlock; } private void addExceptionEdges(InstructionHandle handle, BasicBlock sourceBlock, LinkedList<InstructionHandle> jsrStack) { List<CodeExceptionGen> exceptionHandlerList = exceptionHandlerMap.getHandlerList(handle); if (exceptionHandlerList == null) return; Iterator<CodeExceptionGen> i = exceptionHandlerList.iterator(); while (i.hasNext()) { CodeExceptionGen exceptionHandler = i.next(); BasicBlock handlerBlock = getBlock(exceptionHandler.getHandlerPC(), jsrStack); addEdge(sourceBlock, handlerBlock, HANDLED_EXCEPTION_EDGE); } } private LinkedList<InstructionHandle> cloneJsrStack(LinkedList<InstructionHandle> jsrStack) { LinkedList<InstructionHandle> dup = new LinkedList<InstructionHandle>(); dup.addAll(jsrStack); return dup; } private boolean isMerge(InstructionHandle handle) { if (handle.hasTargeters()) { // Check all targeters of this handle to see if any // of them are branches. Note that we don't consider JSR // instructions to be branches, since we inline JSR subroutines. InstructionTargeter[] targeterList = handle.getTargeters(); for (int i = 0; i < targeterList.length; ++i) { InstructionTargeter targeter = targeterList[i]; if (targeter instanceof BranchInstruction && !(targeter instanceof JsrInstruction)) { return true; } } } return false; } private void addEdge(BasicBlock sourceBlock, BasicBlock destBlock, int edgeType) { if (DEBUG) System.out.println("Add edge: " + sourceBlock.getId() + " -> " + destBlock.getId() + ": " + Edge.edgeTypeToString(edgeType)); cfg.addEdge(sourceBlock, destBlock, edgeType); } private void dumpBlock(BasicBlock basicBlock) { System.out.println("BLOCK " + basicBlock.getId()); Iterator<InstructionHandle> i = basicBlock.instructionIterator(); while (i.hasNext()) { InstructionHandle handle = i.next(); System.out.println(handle.toString()); } System.out.println("END"); } } // vim:ts=4
findbugs/src/java/edu/umd/cs/findbugs/ba/BetterCFGBuilder.java
/* * Bytecode Analysis Framework * Copyright (C) 2003, University of Maryland * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package edu.umd.cs.daveho.ba; import java.util.*; // We require BCEL 5.0 or later. import org.apache.bcel.*; import org.apache.bcel.classfile.*; import org.apache.bcel.generic.*; public class BetterCFGBuilder implements CFGBuilder, EdgeTypes { private static final boolean DEBUG = Boolean.getBoolean("cfgbuilder.debug"); /* ---------------------------------------------------------------------- * Helper classes * ---------------------------------------------------------------------- */ private static class WorkListItem { public final InstructionHandle start; public final BasicBlock basicBlock; public final LinkedList<InstructionHandle> jsrStack; public boolean handledPEI; public WorkListItem(InstructionHandle start, BasicBlock basicBlock, LinkedList<InstructionHandle> jsrStack, boolean handledPEI) { this.start = start; this.basicBlock = basicBlock; this.jsrStack = jsrStack; this.handledPEI = handledPEI; } } /* ---------------------------------------------------------------------- * Constants * ---------------------------------------------------------------------- */ // Reasons for why a basic block was ended. private static final int BRANCH = 0; private static final int MERGE = 1; private static final int NEXT_IS_PEI = 2; /* ---------------------------------------------------------------------- * Data members * ---------------------------------------------------------------------- */ private MethodGen methodGen; private ConstantPoolGen cpg; private CFG cfg; private LinkedList<WorkListItem> workList; private IdentityHashMap<InstructionHandle, BasicBlock> basicBlockMap; private IdentityHashMap<InstructionHandle, BasicBlock> allHandlesToBasicBlockMap; private ExceptionHandlerMap exceptionHandlerMap; /* ---------------------------------------------------------------------- * Public methods * ---------------------------------------------------------------------- */ public BetterCFGBuilder(MethodGen methodGen) { this.methodGen = methodGen; this.cpg = methodGen.getConstantPool(); this.cfg = new CFG(); this.workList = new LinkedList<WorkListItem>(); this.basicBlockMap = new IdentityHashMap<InstructionHandle, BasicBlock>(); this.allHandlesToBasicBlockMap = new IdentityHashMap<InstructionHandle, BasicBlock>(); this.exceptionHandlerMap = new ExceptionHandlerMap(methodGen); } public void setMode(int mode) { } public void build() { getBlock(methodGen.getInstructionList().getStart(), new LinkedList<InstructionHandle>()); workListLoop: while (!workList.isEmpty()) { WorkListItem item = workList.removeFirst(); InstructionHandle start = item.start; BasicBlock basicBlock = item.basicBlock; LinkedList<InstructionHandle> jsrStack = item.jsrStack; boolean handledPEI = item.handledPEI; if (DEBUG) System.out.println("START BLOCK " + basicBlock.getId()); // If the start instruction is a PEI which we haven't handled yet, then // this block is an Exception Thrower Block (ETB). if (isPEI(start) && !handledPEI) { // This block is an ETB. basicBlock.setExceptionThrower(true); // Add handled exception edges. addExceptionEdges(start, basicBlock, jsrStack); // Add fall through edge. Note that we add the work list item for the // new block by hand, because getBlock() // (1) sets handledPEI to false, and // (2) maps the start instruction to the new block; the ETB is // the correct block for the start instruction, not the // fall through block BasicBlock nextBasicBlock = cfg.allocate(); addEdge(basicBlock, nextBasicBlock, FALL_THROUGH_EDGE); WorkListItem nextItem = new WorkListItem(start, nextBasicBlock, jsrStack, true); workList.add(nextItem); continue workListLoop; } InstructionHandle handle = start; InstructionHandle next = null; TargetEnumeratingVisitor visitor = null; int endBlockMode; // Add instructions to the basic block scanInstructionsLoop: while (true) { // Add the instruction to the block basicBlock.addInstruction(handle); if (DEBUG) System.out.println("** Add " + handle + (isPEI(handle) ? " [PEI]" : "")); // Except for instructions in JSR subroutines, no instruction should be // in more than one basic block. if (allHandlesToBasicBlockMap.get(handle) != null && jsrStack.isEmpty()) throw new IllegalStateException("Instruction in multiple blocks: " + handle); allHandlesToBasicBlockMap.put(handle, basicBlock); // PEIs should always be the first instruction in the basic block if (isPEI(handle) && handle != basicBlock.getFirstInstruction()) throw new IllegalStateException("PEI is not first instruction in block!"); // This will be assigned if the potential next instruction in the // basic block is something other than what would be returned // by handle.getNext(). This only happens for JSR and RET instructions. next = null; Instruction ins = handle.getInstruction(); // Handle JSR, RET, and explicit branches. if (ins instanceof JsrInstruction) { // Remember where we came from jsrStack.addLast(handle); // Transfer control to the subroutine JsrInstruction jsr = (JsrInstruction) ins; next = jsr.getTarget(); } else if (ins instanceof RET) { // Return control to instruction after JSR next = jsrStack.removeLast().getNext(); } else if ((visitor = new TargetEnumeratingVisitor(handle, cpg)).isEndOfBasicBlock()) { // Basic block ends with explicit branch. endBlockMode = BRANCH; break scanInstructionsLoop; } // If control gets here, then the current instruction was not cause // for ending the basic block. Check the next instruction, which may // be cause for ending the block. if (next == null) next = handle.getNext(); if (next == null) throw new IllegalStateException("Falling off end of method: " + handle); // Control merge? if (isMerge(next)) { endBlockMode = MERGE; break scanInstructionsLoop; } // Next instruction is a PEI? if (isPEI(next)) { endBlockMode = NEXT_IS_PEI; break scanInstructionsLoop; } // The basic block definitely continues to the next instruction. handle = next; } if (DEBUG) dumpBlock(basicBlock); // Depending on how the basic block ended, add appropriate edges to the CFG. if (next != null) { // There is a successor instruction, meaning that this // is a control merge, or the block was ended because of a PEI. // In either case, just fall through to the successor. if (endBlockMode != MERGE && endBlockMode != NEXT_IS_PEI) throw new IllegalStateException("next != null, but not merge or PEI"); BasicBlock nextBlock = getBlock(next, jsrStack); addEdge(basicBlock, nextBlock, FALL_THROUGH_EDGE); } else { // There is no successor instruction, meaning that the block ended // in an explicit branch of some sort. if (endBlockMode != BRANCH) throw new IllegalStateException("next == null, but not branch"); if (visitor.instructionIsThrow()) { // Explicit ATHROW instruction. Add exception edges, // and mark the block as an ETB. addExceptionEdges(handle, basicBlock, jsrStack); basicBlock.setExceptionThrower(true); } else if (visitor.instructionIsReturn() || visitor.instructionIsExit()) { // Return or call to System.exit(). In either case, // add a return edge. addEdge(basicBlock, cfg.getExit(), RETURN_EDGE); } else { // The TargetEnumeratingVisitor takes care of telling us what the targets are. // (This includes the fall through edges for IF branches.) Iterator<Target> i = visitor.targetIterator(); while (i.hasNext()) { Target target = i.next(); BasicBlock targetBlock = getBlock(target.getTargetInstruction(), jsrStack); addEdge(basicBlock, targetBlock, target.getEdgeType()); } } } } } public CFG getCFG() { return cfg; } /* ---------------------------------------------------------------------- * Private methods * ---------------------------------------------------------------------- */ private boolean isPEI(InstructionHandle handle) { Instruction ins = handle.getInstruction(); //return (ins instanceof ExceptionThrower) && !(ins instanceof ATHROW); if (!(ins instanceof ExceptionThrower)) return false; if (ins instanceof ATHROW) return false; if (ins instanceof ReturnInstruction && !methodGen.isSynchronized()) return false; return true; } private BasicBlock getBlock(InstructionHandle start, LinkedList<InstructionHandle> jsrStack) { BasicBlock basicBlock = basicBlockMap.get(start); if (basicBlock == null) { basicBlock = cfg.allocate(); basicBlockMap.put(start, basicBlock); WorkListItem item = new WorkListItem(start, basicBlock, cloneJsrStack(jsrStack), false); workList.add(item); } return basicBlock; } private void addExceptionEdges(InstructionHandle handle, BasicBlock sourceBlock, LinkedList<InstructionHandle> jsrStack) { List<CodeExceptionGen> exceptionHandlerList = exceptionHandlerMap.getHandlerList(handle); if (exceptionHandlerList == null) return; Iterator<CodeExceptionGen> i = exceptionHandlerList.iterator(); while (i.hasNext()) { CodeExceptionGen exceptionHandler = i.next(); BasicBlock handlerBlock = getBlock(exceptionHandler.getHandlerPC(), jsrStack); addEdge(sourceBlock, handlerBlock, HANDLED_EXCEPTION_EDGE); } } private LinkedList<InstructionHandle> cloneJsrStack(LinkedList<InstructionHandle> jsrStack) { LinkedList<InstructionHandle> dup = new LinkedList<InstructionHandle>(); dup.addAll(jsrStack); return dup; } private boolean isMerge(InstructionHandle handle) { if (handle.hasTargeters()) { // Check all targeters of this handle to see if any // of them are branches. Note that we don't consider JSR // instructions to be branches, since we inline JSR subroutines. InstructionTargeter[] targeterList = handle.getTargeters(); for (int i = 0; i < targeterList.length; ++i) { InstructionTargeter targeter = targeterList[i]; if (targeter instanceof BranchInstruction && !(targeter instanceof JsrInstruction)) { return true; } } } return false; } private void addEdge(BasicBlock sourceBlock, BasicBlock destBlock, int edgeType) { if (DEBUG) System.out.println("Add edge: " + sourceBlock.getId() + " -> " + destBlock.getId() + ": " + Edge.edgeTypeToString(edgeType)); cfg.addEdge(sourceBlock, destBlock, edgeType); } private void dumpBlock(BasicBlock basicBlock) { System.out.println("BLOCK " + basicBlock.getId()); Iterator<InstructionHandle> i = basicBlock.instructionIterator(); while (i.hasNext()) { InstructionHandle handle = i.next(); System.out.println(handle.toString()); } System.out.println("END"); } } // vim:ts=4
Added javadoc class header comment. git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@379 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3
findbugs/src/java/edu/umd/cs/findbugs/ba/BetterCFGBuilder.java
Added javadoc class header comment.
Java
lgpl-2.1
6c90056cdb572e466c5ea4751d35a06bb7f7101e
0
CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine
/* * jETeL/CloverETL - Java based ETL application framework. * Copyright (c) Javlin, a.s. ([email protected]) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.jetel.graph.runtime; import java.lang.management.ManagementFactory; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import java.util.concurrent.BlockingQueue; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.Callable; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import javax.management.InstanceAlreadyExistsException; import javax.management.MBeanRegistrationException; import javax.management.MBeanServer; import javax.management.MalformedObjectNameException; import javax.management.NotCompliantMBeanException; import javax.management.ObjectName; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.log4j.MDC; import org.jetel.exception.ComponentNotReadyException; import org.jetel.graph.ContextProvider; import org.jetel.graph.GraphElement; import org.jetel.graph.IGraphElement; import org.jetel.graph.Node; import org.jetel.graph.Phase; import org.jetel.graph.Result; import org.jetel.graph.TransactionMethod; import org.jetel.graph.TransformationGraph; import org.jetel.graph.runtime.jmx.CloverJMX; import org.jetel.util.primitive.DuplicateKeyMap; import org.jetel.util.string.StringUtils; /** * Description of the Class * * @author dpavlis * @since July 29, 2002 * @revision $Revision$ */ public class WatchDog implements Callable<Result>, CloverPost { /** * This lock object guards currentPhase variable and watchDogStatus. */ private final Lock CURRENT_PHASE_LOCK = new ReentrantLock(); private final Object ABORT_MONITOR = new Object(); private boolean abortFinished = false; public final static String MBEAN_NAME_PREFIX = "CLOVERJMX_"; public final static long WAITTIME_FOR_STOP_SIGNAL = 5000; //miliseconds private static final long ABORT_TIMEOUT = 5000L; private static final long ABORT_WAIT = 2400L; private int[] _MSG_LOCK=new int[0]; private static Log logger = LogFactory.getLog(WatchDog.class); /** * Thread manager is used to run nodes as threads. */ private IThreadManager threadManager; private volatile Result watchDogStatus; private TransformationGraph graph; private Phase currentPhase; private BlockingQueue <Message<?>> inMsgQueue; private DuplicateKeyMap outMsgMap; private volatile Throwable causeException; private volatile IGraphElement causeGraphElement; private CloverJMX cloverJMX; // private volatile boolean runIt; private boolean provideJMX = true; private boolean finishJMX = true; //whether the JMX mbean should be unregistered on the graph finish private final GraphRuntimeContext runtimeContext; static private MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); private ObjectName jmxObjectName; /** *Constructor for the WatchDog object * * @param graph Description of the Parameter * @param phases Description of the Parameter * @since September 02, 2003 */ public WatchDog(TransformationGraph graph, GraphRuntimeContext runtimeContext) { graph.setWatchDog(this); this.graph = graph; this.runtimeContext = runtimeContext; currentPhase = null; watchDogStatus = Result.N_A; inMsgQueue=new LinkedBlockingQueue<Message<?>>(); outMsgMap=new DuplicateKeyMap(Collections.synchronizedMap(new HashMap())); //is JMX turned on? provideJMX = runtimeContext.useJMX(); //passes a password from context to the running graph graph.setPassword(runtimeContext.getPassword()); } /** * WatchDog initialization. */ public void init() { //at least simple thread manager will be used if(threadManager == null) { threadManager = new SimpleThreadManager(); } //start up JMX cloverJMX = new CloverJMX(this); if(provideJMX) { registerTrackingMBean(cloverJMX); } //watchdog is now ready to use watchDogStatus = Result.READY; } private void finishJMX() { if(provideJMX) { try { mbs.unregisterMBean(jmxObjectName); } catch (Exception e) { logger.error("JMX error - ObjectName cannot be unregistered.", e); } } } /** Main processing method for the WatchDog object */ public Result call() { CURRENT_PHASE_LOCK.lock(); try { //we have to register current watchdog's thread to context provider - from now all //ContextProvider.getGraph() invocations return proper transformation graph ContextProvider.registerGraph(graph); MDC.put("runId", runtimeContext.getRunId()); long startTimestamp = System.currentTimeMillis(); //print graph properties graph.getGraphProperties().print(logger, "Graph properties:"); //print initial dictionary content graph.getDictionary().printContent(logger, "Initial dictionary content:"); if (runtimeContext.isVerboseMode()) { // this can be called only after graph.init() graph.dumpGraphConfiguration(); } watchDogStatus = Result.RUNNING; // runIt = true; //creates tracking logger for cloverJMX mbean TrackingLogger.track(cloverJMX); cloverJMX.graphStarted(); //pre-execute initialization of graph try { graph.preExecute(); } catch (ComponentNotReadyException e) { causeException = e; causeGraphElement = e.getGraphElement(); watchDogStatus = Result.ERROR; logger.error("Graph pre-execute initialization faild.", e); } //run all phases if (watchDogStatus == Result.RUNNING) { Phase[] phases = graph.getPhases(); Result phaseResult = Result.N_A; for (int currentPhaseNum = 0; currentPhaseNum < phases.length; currentPhaseNum++) { //if the graph runs in synchronized mode we need to wait for synchronization event to process next phase if (runtimeContext.isSynchronizedRun()) { logger.info("Waiting for phase " + phases[currentPhaseNum] + " approval..."); watchDogStatus = Result.WAITING; CURRENT_PHASE_LOCK.unlock(); synchronized (cloverJMX) { while (cloverJMX.getApprovedPhaseNumber() < phases[currentPhaseNum].getPhaseNum() && watchDogStatus == Result.WAITING) { //graph was maybe aborted try { cloverJMX.wait(); } catch (InterruptedException e) { throw new RuntimeException("WatchDog was interrupted while was waiting for phase synchronization event."); } } } CURRENT_PHASE_LOCK.lock(); //watchdog was aborted while was waiting for next phase approval if (watchDogStatus == Result.ABORTED) { logger.warn("!!! Graph execution aborted !!!"); break; } else { watchDogStatus = Result.RUNNING; } } cloverJMX.phaseStarted(phases[currentPhaseNum]); //execute phase phaseResult = executePhase(phases[currentPhaseNum]); if(phaseResult == Result.ABORTED) { cloverJMX.phaseAborted(); logger.warn("!!! Phase execution aborted !!!"); break; } else if(phaseResult == Result.ERROR) { cloverJMX.phaseError(getErrorMessage()); logger.error("!!! Phase finished with error - stopping graph run !!!"); break; } cloverJMX.phaseFinished(); } //aborted graph does not follow last phase status if (watchDogStatus == Result.RUNNING) { watchDogStatus = phaseResult; } } //print initial dictionary content graph.getDictionary().printContent(logger, "Final dictionary content:"); sendFinalJmxNotification(); if(finishJMX) { finishJMX(); } logger.info("WatchDog thread finished - total execution time: " + (System.currentTimeMillis() - startTimestamp) / 1000 + " (sec)"); } catch (RuntimeException e) { causeException = e; causeGraphElement = null; watchDogStatus = Result.ERROR; logger.error("Fatal error watchdog execution", e); throw e; } finally { //we have to unregister current watchdog's thread from context provider ContextProvider.unregister(); CURRENT_PHASE_LOCK.unlock(); MDC.remove("runId"); } return watchDogStatus; } private void sendFinalJmxNotification() { sendFinalJmxNotification0(); //is there anyone who is really interested in to be informed about the graph is really finished? - at least our clover designer runs graphs with this option if (runtimeContext.isWaitForJMXClient()) { //wait for a JMX client (GUI) to download all tracking information long startWaitingTime = System.currentTimeMillis(); synchronized (cloverJMX) { while (WAITTIME_FOR_STOP_SIGNAL > (System.currentTimeMillis() - startWaitingTime) && !cloverJMX.canCloseServer()) { try { cloverJMX.wait(10); sendFinalJmxNotification0(); } catch (InterruptedException e) { throw new RuntimeException("WatchDog was interrupted while was waiting for close signal."); } } } } //if the graph was aborted, now the aborting thread is waiting for final notification - this is the way how to send him word about the graph finished right now synchronized (ABORT_MONITOR) { abortFinished = true; ABORT_MONITOR.notifyAll(); } } private void sendFinalJmxNotification0() { switch (watchDogStatus) { case FINISHED_OK: cloverJMX.graphFinished(); break; case ABORTED: cloverJMX.graphAborted(); break; case ERROR: cloverJMX.graphError(getErrorMessage()); break; } } /** * Register given jmx mbean. */ private void registerTrackingMBean(CloverJMX cloverJMX) { String mbeanId = graph.getId(); // Construct the ObjectName for the MBean we will register try { String name = createMBeanName(mbeanId != null ? mbeanId : graph.getName(), this.getGraphRuntimeContext().getRunId()); jmxObjectName = new ObjectName( name ); logger.info("register MBean with name:"+name); // Register the MBean mbs.registerMBean(cloverJMX, jmxObjectName); } catch (MalformedObjectNameException e) { logger.error(e); } catch (InstanceAlreadyExistsException e) { logger.error(e); } catch (MBeanRegistrationException e) { logger.error(e); } catch (NotCompliantMBeanException e) { logger.error(e); } } /** * Creates identifier for shared JMX mbean. * @param defaultMBeanName * @return */ public static String createMBeanName(String mbeanIdentifier) { return createMBeanName(mbeanIdentifier, 0); } /** * Creates identifier for shared JMX mbean. * @param mbeanIdentifier * @param runId * @return */ public static String createMBeanName(String mbeanIdentifier, long runId) { return "org.jetel.graph.runtime:type=" + MBEAN_NAME_PREFIX + (mbeanIdentifier != null ? mbeanIdentifier : "") + "_" + runId; } /** * Execute transformation - start-up all Nodes & watch them running * * @param phase Description of the Parameter * @param leafNodes Description of the Parameter * @return Description of the Return Value * @since July 29, 2002 */ @edu.umd.cs.findbugs.annotations.SuppressWarnings("UL") private Result watch(Phase phase) throws InterruptedException { Message<?> message; Set<Node> phaseNodes; // let's create a copy of leaf nodes - we will watch them phaseNodes = new HashSet<Node>(phase.getNodes().values()); // is there any node running ? - this test is necessary for phases without nodes - empty phase if (phaseNodes.isEmpty()) { return watchDogStatus != Result.ABORTED ? Result.FINISHED_OK : Result.ABORTED; } // entering the loop awaiting completion of work by all leaf nodes while (true) { // wait on error message queue CURRENT_PHASE_LOCK.unlock(); try { message = inMsgQueue.poll(runtimeContext.getTrackingInterval(), TimeUnit.MILLISECONDS); } finally { CURRENT_PHASE_LOCK.lock(); } if (message != null) { switch(message.getType()){ case ERROR: causeException = ((ErrorMsgBody) message.getBody()).getSourceException(); causeGraphElement = message.getSender(); logger.error("Graph execution finished with error"); logger.error("Node " + message.getSender().getId() + " finished with status: " + ((ErrorMsgBody) message.getBody()) .getErrorMessage() + (causeException != null ? " caused by: " + causeException.getMessage() : "")); logger.error("Node " + message.getSender().getId() + " error details:", causeException); return Result.ERROR; case MESSAGE: synchronized (_MSG_LOCK) { outMsgMap.put(message.getRecipient(), message); } break; case NODE_FINISHED: phaseNodes.remove(message.getSender()); break; default: // do nothing, just wake up } } // is there any node running ? if (phaseNodes.isEmpty()) { return watchDogStatus != Result.ABORTED ? Result.FINISHED_OK : Result.ABORTED; } // gather graph tracking if (message == null) { cloverJMX.gatherTrackingDetails(); } } } /** * Gets the Status of the WatchDog * * @return Result of WatchDog run-time * @since July 30, 2002 * @see org.jetel.graph.Result */ public Result getStatus() { return watchDogStatus; } /** * aborts execution of current phase * * @since July 29, 2002 */ public void abort() { CURRENT_PHASE_LOCK.lock(); //only running or waiting graph can be aborted if (watchDogStatus != Result.RUNNING && watchDogStatus != Result.WAITING) { CURRENT_PHASE_LOCK.unlock(); return; } try { //if the phase is running broadcast all nodes in the phase they should be aborted if (watchDogStatus == Result.RUNNING) { watchDogStatus = Result.ABORTED; // iterate through all the nodes and stop them for(Node node : currentPhase.getNodes().values()) { node.abort(); logger.warn("Interrupted node: " + node.getId()); } } //if the graph is waiting on a phase synchronization point the watchdog is woken up with current status ABORTED if (watchDogStatus == Result.WAITING) { watchDogStatus = Result.ABORTED; synchronized (cloverJMX) { cloverJMX.notifyAll(); } } } finally { synchronized (ABORT_MONITOR) { CURRENT_PHASE_LOCK.unlock(); long startAbort = System.currentTimeMillis(); while (!abortFinished) { long interval = System.currentTimeMillis() - startAbort; if (interval > ABORT_TIMEOUT) { throw new IllegalStateException("Graph aborting error! Timeout "+ABORT_TIMEOUT+"ms exceeded!"); } try { //the aborting thread try to wait for end of graph run ABORT_MONITOR.wait(ABORT_WAIT); } catch (InterruptedException ignore) { }// catch }// while }// synchronized }// finally } /** * Description of the Method * * @param nodesIterator Description of Parameter * @param leafNodesList Description of Parameter * @since July 31, 2002 */ private void startUpNodes(Phase phase) { synchronized(threadManager) { while(threadManager.getFreeThreadsCount() < phase.getNodes().size()) { //it is sufficient, not necessary condition - so we have to time to time wake up and check it again try { threadManager.wait(); //from time to time thread is woken up to check the condition again } catch (InterruptedException e) { throw new RuntimeException("WatchDog was interrupted while was waiting for free workers for nodes in phase " + phase.getPhaseNum()); } } if (phase.getNodes().size() > 0) { //this barrier can be broken only when all components and wathdog is waiting there CyclicBarrier preExecuteBarrier = new CyclicBarrier(phase.getNodes().size() + 1); //this barrier is used for synchronization of all components between pre-execute and execute //it is necessary to finish all pre-execute's before execution CyclicBarrier executeBarrier = new CyclicBarrier(phase.getNodes().size()); for(Node node: phase.getNodes().values()) { node.setPreExecuteBarrier(preExecuteBarrier); node.setExecuteBarrier(executeBarrier); threadManager.executeNode(node); logger.debug(node.getId()+ " ... starting"); } try { //now we will wait for all components are really alive - node.getNodeThread() return non-null value preExecuteBarrier.await(); logger.debug("All components are ready to start."); } catch (InterruptedException e) { throw new RuntimeException("WatchDog was interrupted while was waiting for workers startup in phase " + phase.getPhaseNum()); } catch (BrokenBarrierException e) { throw new RuntimeException("WatchDog or a worker was interrupted while was waiting for nodes tartup in phase " + phase.getPhaseNum()); } } } } /** * Description of the Method * * @param phase Description of the Parameter * @return Description of the Return Value */ private Result executePhase(Phase phase) { currentPhase = phase; //preExecute() invocation try { phase.preExecute(); } catch (ComponentNotReadyException e) { logger.error("Phase pre-execute initialization failed with reason: " + e.getMessage(), e); causeException = e; causeGraphElement = e.getGraphElement(); return Result.ERROR; } logger.info("Starting up all nodes in phase [" + phase.getPhaseNum() + "]"); startUpNodes(phase); logger.info("Successfully started all nodes in phase!"); // watch running nodes in phase Result phaseStatus = Result.N_A; try{ phaseStatus = watch(phase); }catch(InterruptedException ex){ phaseStatus = Result.ABORTED; } finally { //now we can notify all waiting phases for free threads synchronized(threadManager) { threadManager.releaseNodeThreads(phase.getNodes().size()); ///////////////// //is this code really necessary? why? for (Node node : phase.getNodes().values()) { synchronized (node) { //this is the guard of Node.nodeThread variable Thread t = node.getNodeThread(); long runId = this.getGraphRuntimeContext().getRunId(); if (t == null) { continue; } t.setName("exNode_"+runId+"_"+node.getId()); // explicit interruption of threads of failed graph; (some nodes may be still running) if (node.getResultCode() == Result.RUNNING) { node.abort(); } } }// for ///////////////// threadManager.notifyAll(); } //specify transaction mode for postExecute() TransactionMethod transactionMethod = TransactionMethod.DEFAULT; if (runtimeContext.isTransactionMode()) { switch (phaseStatus) { case FINISHED_OK: transactionMethod = TransactionMethod.COMMIT; break; default: transactionMethod = TransactionMethod.ROLLBACK; } } //postExecute() invocation try { phase.postExecute(transactionMethod); } catch (ComponentNotReadyException e) { logger.error("Phase post-execute finalization [transaction method=" + transactionMethod + "] failed with reason: " + e.getMessage(), e); causeException = e; causeGraphElement = e.getGraphElement(); phaseStatus = Result.ERROR; } } phase.setResult(phaseStatus); return phaseStatus; } public void sendMessage(Message msg) { inMsgQueue.add(msg); } public Message[] receiveMessage(GraphElement recipient, @SuppressWarnings("unused") final long wait) { Message[] msg = null; synchronized (_MSG_LOCK) { msg=(Message[])outMsgMap.getAll(recipient, new Message[0]); if (msg!=null) { outMsgMap.remove(recipient); } } return msg; } public boolean hasMessage(GraphElement recipient) { synchronized (_MSG_LOCK ){ return outMsgMap.containsKey(recipient); } } /** * Returns exception (reported by Node) which caused * graph to stop processing.<br> * * @return the causeException * @since 7.1.2007 */ public Throwable getCauseException() { return causeException; } /** * Returns ID of Node which caused * graph to stop processing. * * @return the causeNodeID * @since 7.1.2007 */ public IGraphElement getCauseGraphElement() { return causeGraphElement; } public String getErrorMessage() { StringBuilder message = new StringBuilder(); IGraphElement graphElement = getCauseGraphElement(); if (graphElement != null) { message.append(graphElement.getId() + ": "); } Throwable throwable = getCauseException(); if (throwable != null && !StringUtils.isEmpty(throwable.getMessage())) { message.append(throwable.getMessage()); } else { message.append("<unknown>"); } return message.toString(); } /** * @return the graph * @since 26.2.2007 */ public TransformationGraph getTransformationGraph() { return graph; } public void setUseJMX(boolean useJMX) { this.provideJMX = useJMX; } public GraphRuntimeContext getGraphRuntimeContext() { return runtimeContext; } public CloverJMX getCloverJmx() { return cloverJMX; } public boolean isFinishJMX() { return finishJMX; } public void setFinishJMX(boolean finishJMX) { this.finishJMX = finishJMX; } public IThreadManager getThreadManager() { return threadManager; } public void setThreadManager(IThreadManager threadManager) { this.threadManager = threadManager; } public TransformationGraph getGraph() { return graph; } public IAuthorityProxy getAuthorityProxy() { return getGraph().getAuthorityProxy(); } }
cloveretl.engine/src/org/jetel/graph/runtime/WatchDog.java
/* * jETeL/CloverETL - Java based ETL application framework. * Copyright (c) Javlin, a.s. ([email protected]) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.jetel.graph.runtime; import java.lang.management.ManagementFactory; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import java.util.concurrent.BlockingQueue; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.Callable; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import javax.management.InstanceAlreadyExistsException; import javax.management.MBeanRegistrationException; import javax.management.MBeanServer; import javax.management.MalformedObjectNameException; import javax.management.NotCompliantMBeanException; import javax.management.ObjectName; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.log4j.MDC; import org.jetel.exception.ComponentNotReadyException; import org.jetel.graph.ContextProvider; import org.jetel.graph.GraphElement; import org.jetel.graph.IGraphElement; import org.jetel.graph.Node; import org.jetel.graph.Phase; import org.jetel.graph.Result; import org.jetel.graph.TransactionMethod; import org.jetel.graph.TransformationGraph; import org.jetel.graph.runtime.jmx.CloverJMX; import org.jetel.util.primitive.DuplicateKeyMap; import org.jetel.util.string.StringUtils; /** * Description of the Class * * @author dpavlis * @since July 29, 2002 * @revision $Revision$ */ public class WatchDog implements Callable<Result>, CloverPost { /** * This lock object guards currentPhase variable and watchDogStatus. */ private final Lock CURRENT_PHASE_LOCK = new ReentrantLock(); private final Object ABORT_MONITOR = new Object(); private boolean abortFinished = false; public final static String MBEAN_NAME_PREFIX = "CLOVERJMX_"; public final static long WAITTIME_FOR_STOP_SIGNAL = 5000; //miliseconds private static final long ABORT_TIMEOUT = 5000L; private static final long ABORT_WAIT = 2400L; private int[] _MSG_LOCK=new int[0]; private static Log logger = LogFactory.getLog(WatchDog.class); /** * Thread manager is used to run nodes as threads. */ private IThreadManager threadManager; private volatile Result watchDogStatus; private TransformationGraph graph; private Phase currentPhase; private BlockingQueue <Message<?>> inMsgQueue; private DuplicateKeyMap outMsgMap; private volatile Throwable causeException; private volatile IGraphElement causeGraphElement; private CloverJMX cloverJMX; // private volatile boolean runIt; private boolean provideJMX = true; private boolean finishJMX = true; //whether the JMX mbean should be unregistered on the graph finish private final GraphRuntimeContext runtimeContext; static private MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); private ObjectName jmxObjectName; /** *Constructor for the WatchDog object * * @param graph Description of the Parameter * @param phases Description of the Parameter * @since September 02, 2003 */ public WatchDog(TransformationGraph graph, GraphRuntimeContext runtimeContext) { graph.setWatchDog(this); this.graph = graph; this.runtimeContext = runtimeContext; currentPhase = null; watchDogStatus = Result.N_A; inMsgQueue=new LinkedBlockingQueue<Message<?>>(); outMsgMap=new DuplicateKeyMap(Collections.synchronizedMap(new HashMap())); //is JMX turned on? provideJMX = runtimeContext.useJMX(); //passes a password from context to the running graph graph.setPassword(runtimeContext.getPassword()); } /** * WatchDog initialization. */ public void init() { //at least simple thread manager will be used if(threadManager == null) { threadManager = new SimpleThreadManager(); } //start up JMX cloverJMX = new CloverJMX(this); if(provideJMX) { registerTrackingMBean(cloverJMX); } //watchdog is now ready to use watchDogStatus = Result.READY; } private void finishJMX() { if(provideJMX) { try { mbs.unregisterMBean(jmxObjectName); } catch (Exception e) { logger.error("JMX error - ObjectName cannot be unregistered.", e); } } } /** Main processing method for the WatchDog object */ public Result call() { CURRENT_PHASE_LOCK.lock(); try { //we have to register current watchdog's thread to context provider - from now all //ContextProvider.getGraph() invocations return proper transformation graph ContextProvider.registerGraph(graph); MDC.put("runId", runtimeContext.getRunId()); long startTimestamp = System.currentTimeMillis(); //print graph properties graph.getGraphProperties().print(logger, "Graph properties:"); //print initial dictionary content graph.getDictionary().printContent(logger, "Initial dictionary content:"); if (runtimeContext.isVerboseMode()) { // this can be called only after graph.init() graph.dumpGraphConfiguration(); } watchDogStatus = Result.RUNNING; // runIt = true; //creates tracking logger for cloverJMX mbean TrackingLogger.track(cloverJMX); cloverJMX.graphStarted(); //pre-execute initialization of graph try { graph.preExecute(); } catch (ComponentNotReadyException e) { causeException = e; causeGraphElement = e.getGraphElement(); watchDogStatus = Result.ERROR; logger.error("Graph pre-execute initialization faild.", e); } //run all phases if (watchDogStatus == Result.RUNNING) { Phase[] phases = graph.getPhases(); Result phaseResult = Result.N_A; for (int currentPhaseNum = 0; currentPhaseNum < phases.length; currentPhaseNum++) { //if the graph runs in synchronized mode we need to wait for synchronization event to process next phase if (runtimeContext.isSynchronizedRun()) { logger.info("Waiting for phase " + phases[currentPhaseNum] + " approval..."); watchDogStatus = Result.WAITING; CURRENT_PHASE_LOCK.unlock(); synchronized (cloverJMX) { while (cloverJMX.getApprovedPhaseNumber() < phases[currentPhaseNum].getPhaseNum() && watchDogStatus == Result.WAITING) { //graph was maybe aborted try { cloverJMX.wait(); } catch (InterruptedException e) { throw new RuntimeException("WatchDog was interrupted while was waiting for phase synchronization event."); } } } CURRENT_PHASE_LOCK.lock(); //watchdog was aborted while was waiting for next phase approval if (watchDogStatus == Result.ABORTED) { logger.warn("!!! Graph execution aborted !!!"); break; } else { watchDogStatus = Result.RUNNING; } } cloverJMX.phaseStarted(phases[currentPhaseNum]); //execute phase phaseResult = executePhase(phases[currentPhaseNum]); if(phaseResult == Result.ABORTED) { cloverJMX.phaseAborted(); logger.warn("!!! Phase execution aborted !!!"); break; } else if(phaseResult == Result.ERROR) { cloverJMX.phaseError(getErrorMessage()); logger.error("!!! Phase finished with error - stopping graph run !!!"); break; } cloverJMX.phaseFinished(); } //aborted graph does not follow last phase status if (watchDogStatus == Result.RUNNING) { watchDogStatus = phaseResult; } } //print initial dictionary content graph.getDictionary().printContent(logger, "Final dictionary content:"); sendFinalJmxNotification(); if(finishJMX) { finishJMX(); } logger.info("WatchDog thread finished - total execution time: " + (System.currentTimeMillis() - startTimestamp) / 1000 + " (sec)"); } catch (RuntimeException e) { causeException = e; causeGraphElement = null; watchDogStatus = Result.ERROR; logger.error("Fatal error watchdog execution", e); throw e; } finally { //we have to unregister current watchdog's thread from context provider ContextProvider.unregister(); CURRENT_PHASE_LOCK.unlock(); MDC.remove("runId"); } return watchDogStatus; } private void sendFinalJmxNotification() { sendFinalJmxNotification0(); //is there anyone who is really interested in to be informed about the graph is really finished? - at least our clover designer runs graphs with this option if (runtimeContext.isWaitForJMXClient()) { //wait for a JMX client (GUI) to download all tracking information long startWaitingTime = System.currentTimeMillis(); synchronized (cloverJMX) { while (WAITTIME_FOR_STOP_SIGNAL > (System.currentTimeMillis() - startWaitingTime) && !cloverJMX.canCloseServer()) { try { cloverJMX.wait(10); sendFinalJmxNotification0(); } catch (InterruptedException e) { throw new RuntimeException("WatchDog was interrupted while was waiting for close signal."); } } } } //if the graph was aborted, now the aborting thread is waiting for final notification - this is the way how to send him word about the graph finished right now synchronized (ABORT_MONITOR) { abortFinished = true; ABORT_MONITOR.notifyAll(); } } private void sendFinalJmxNotification0() { switch (watchDogStatus) { case FINISHED_OK: cloverJMX.graphFinished(); break; case ABORTED: cloverJMX.graphAborted(); break; case ERROR: cloverJMX.graphError(getErrorMessage()); break; } } /** * Register given jmx mbean. */ private void registerTrackingMBean(CloverJMX cloverJMX) { String mbeanId = graph.getId(); // Construct the ObjectName for the MBean we will register try { String name = createMBeanName(mbeanId != null ? mbeanId : graph.getName(), this.getGraphRuntimeContext().getRunId()); jmxObjectName = new ObjectName( name ); logger.info("register MBean with name:"+name); // Register the MBean mbs.registerMBean(cloverJMX, jmxObjectName); } catch (MalformedObjectNameException e) { logger.error(e); } catch (InstanceAlreadyExistsException e) { logger.error(e); } catch (MBeanRegistrationException e) { logger.error(e); } catch (NotCompliantMBeanException e) { logger.error(e); } } /** * Creates identifier for shared JMX mbean. * @param defaultMBeanName * @return */ public static String createMBeanName(String mbeanIdentifier) { return createMBeanName(mbeanIdentifier, 0); } /** * Creates identifier for shared JMX mbean. * @param mbeanIdentifier * @param runId * @return */ public static String createMBeanName(String mbeanIdentifier, long runId) { return "org.jetel.graph.runtime:type=" + MBEAN_NAME_PREFIX + (mbeanIdentifier != null ? mbeanIdentifier : "") + "_" + runId; } /** * Execute transformation - start-up all Nodes & watch them running * * @param phase Description of the Parameter * @param leafNodes Description of the Parameter * @return Description of the Return Value * @since July 29, 2002 */ @edu.umd.cs.findbugs.annotations.SuppressWarnings("UL") private Result watch(Phase phase) throws InterruptedException { Message<?> message; Set<Node> phaseNodes; // let's create a copy of leaf nodes - we will watch them phaseNodes = new HashSet<Node>(phase.getNodes().values()); // is there any node running ? - this test is necessary for phases without nodes - empty phase if (phaseNodes.isEmpty()) { return watchDogStatus != Result.ABORTED ? Result.FINISHED_OK : Result.ABORTED; } // entering the loop awaiting completion of work by all leaf nodes while (true) { // wait on error message queue CURRENT_PHASE_LOCK.unlock(); try { message = inMsgQueue.poll(runtimeContext.getTrackingInterval(), TimeUnit.MILLISECONDS); } finally { CURRENT_PHASE_LOCK.lock(); } if (message != null) { switch(message.getType()){ case ERROR: causeException = ((ErrorMsgBody) message.getBody()).getSourceException(); causeGraphElement = message.getSender(); logger.error("Graph execution finished with error"); logger.error("Node " + message.getSender().getId() + " finished with status: " + ((ErrorMsgBody) message.getBody()) .getErrorMessage() + (causeException != null ? " caused by: " + causeException.getMessage() : "")); logger.error("Node " + message.getSender().getId() + " error details:", causeException); return Result.ERROR; case MESSAGE: synchronized (_MSG_LOCK) { outMsgMap.put(message.getRecipient(), message); } break; case NODE_FINISHED: phaseNodes.remove(message.getSender()); break; default: // do nothing, just wake up } } // is there any node running ? if (phaseNodes.isEmpty()) { return watchDogStatus != Result.ABORTED ? Result.FINISHED_OK : Result.ABORTED; } // gather graph tracking if (message == null) { cloverJMX.gatherTrackingDetails(); } } } /** * Gets the Status of the WatchDog * * @return Result of WatchDog run-time * @since July 30, 2002 * @see org.jetel.graph.Result */ public Result getStatus() { return watchDogStatus; } /** * aborts execution of current phase * * @since July 29, 2002 */ public void abort() { CURRENT_PHASE_LOCK.lock(); //only running or waiting graph can be aborted if (watchDogStatus != Result.RUNNING && watchDogStatus != Result.WAITING) { CURRENT_PHASE_LOCK.unlock(); return; } try { //if the phase is running broadcast all nodes in the phase they should be aborted if (watchDogStatus == Result.RUNNING) { watchDogStatus = Result.ABORTED; // iterate through all the nodes and stop them for(Node node : currentPhase.getNodes().values()) { node.abort(); logger.warn("Interrupted node: " + node.getId()); } } //if the graph is waiting on a phase synchronization point the watchdog is woken up with current status ABORTED if (watchDogStatus == Result.WAITING) { watchDogStatus = Result.ABORTED; synchronized (cloverJMX) { cloverJMX.notifyAll(); } } } finally { synchronized (ABORT_MONITOR) { CURRENT_PHASE_LOCK.unlock(); long startAbort = System.currentTimeMillis(); while (!abortFinished) { long interval = System.currentTimeMillis() - startAbort; if (interval > ABORT_TIMEOUT) { throw new IllegalStateException("Graph aborting error! Timeout "+ABORT_TIMEOUT+"ms exceeded!"); } try { //the aborting thread try to wait for end of graph run ABORT_MONITOR.wait(ABORT_WAIT); } catch (InterruptedException ignore) { }// catch }// while }// synchronized }// finally } /** * Description of the Method * * @param nodesIterator Description of Parameter * @param leafNodesList Description of Parameter * @since July 31, 2002 */ private void startUpNodes(Phase phase) { synchronized(threadManager) { while(threadManager.getFreeThreadsCount() < phase.getNodes().size()) { //it is sufficient, not necessary condition - so we have to time to time wake up and check it again try { threadManager.wait(); //from time to time thread is woken up to check the condition again } catch (InterruptedException e) { throw new RuntimeException("WatchDog was interrupted while was waiting for free workers for nodes in phase " + phase.getPhaseNum()); } } if (phase.getNodes().size() > 0) { //this barrier can be broken only when all components and wathdog is waiting there CyclicBarrier preExecuteBarrier = new CyclicBarrier(phase.getNodes().size() + 1); //this barrier is used for synchronization of all components between pre-execute and execute //it is necessary to finish all pre-execute's before execution CyclicBarrier executeBarrier = new CyclicBarrier(phase.getNodes().size()); for(Node node: phase.getNodes().values()) { node.setPreExecuteBarrier(preExecuteBarrier); node.setExecuteBarrier(executeBarrier); threadManager.executeNode(node); logger.debug(node.getId()+ " ... starting"); } try { //now we will wait for all components are really alive - node.getNodeThread() return non-null value preExecuteBarrier.await(); logger.debug("All components are ready to start."); } catch (InterruptedException e) { throw new RuntimeException("WatchDog was interrupted while was waiting for workers startup in phase " + phase.getPhaseNum()); } catch (BrokenBarrierException e) { throw new RuntimeException("WatchDog or a worker was interrupted while was waiting for nodes tartup in phase " + phase.getPhaseNum()); } } } } /** * Description of the Method * * @param phase Description of the Parameter * @return Description of the Return Value */ private Result executePhase(Phase phase) { currentPhase = phase; //preExecute() invocation try { phase.preExecute(); } catch (ComponentNotReadyException e) { logger.error("Phase pre-execute initialization failed with reason: " + e.getMessage(), e); causeException = e; causeGraphElement = e.getGraphElement(); return Result.ERROR; } logger.info("Starting up all nodes in phase [" + phase.getPhaseNum() + "]"); startUpNodes(phase); logger.info("Successfully started all nodes in phase!"); // watch running nodes in phase Result phaseStatus = Result.N_A; try{ phaseStatus = watch(phase); }catch(InterruptedException ex){ phaseStatus = Result.ABORTED; } finally { //now we can notify all waiting phases for free threads synchronized(threadManager) { threadManager.releaseNodeThreads(phase.getNodes().size()); ///////////////// //is this code really necessary? why? for (Node node : phase.getNodes().values()) { synchronized (node) { //this is the guard of Node.nodeThread variable Thread t = node.getNodeThread(); long runId = this.getGraphRuntimeContext().getRunId(); if (t == null) { continue; } t.setName("exNode_"+runId+"_"+node.getId()); // explicit interruption of threads of failed graph; (some nodes may be still running) if (node.getResultCode() == Result.RUNNING) { node.abort(); } } }// for ///////////////// threadManager.notifyAll(); } //specify transaction mode for postExecute() TransactionMethod transactionMethod = TransactionMethod.DEFAULT; if (runtimeContext.isTransactionMode()) { switch (phaseStatus) { case FINISHED_OK: transactionMethod = TransactionMethod.COMMIT; break; default: transactionMethod = TransactionMethod.ROLLBACK; } } //postExecute() invocation try { phase.postExecute(transactionMethod); } catch (ComponentNotReadyException e) { logger.error("Phase post-execute finalization [transaction method=" + transactionMethod + "] failed with reason: " + e.getMessage(), e); causeException = e; causeGraphElement = e.getGraphElement(); return Result.ERROR; } } phase.setResult(phaseStatus); return phaseStatus; } public void sendMessage(Message msg) { inMsgQueue.add(msg); } public Message[] receiveMessage(GraphElement recipient, @SuppressWarnings("unused") final long wait) { Message[] msg = null; synchronized (_MSG_LOCK) { msg=(Message[])outMsgMap.getAll(recipient, new Message[0]); if (msg!=null) { outMsgMap.remove(recipient); } } return msg; } public boolean hasMessage(GraphElement recipient) { synchronized (_MSG_LOCK ){ return outMsgMap.containsKey(recipient); } } /** * Returns exception (reported by Node) which caused * graph to stop processing.<br> * * @return the causeException * @since 7.1.2007 */ public Throwable getCauseException() { return causeException; } /** * Returns ID of Node which caused * graph to stop processing. * * @return the causeNodeID * @since 7.1.2007 */ public IGraphElement getCauseGraphElement() { return causeGraphElement; } public String getErrorMessage() { StringBuilder message = new StringBuilder(); IGraphElement graphElement = getCauseGraphElement(); if (graphElement != null) { message.append(graphElement.getId() + ": "); } Throwable throwable = getCauseException(); if (throwable != null && !StringUtils.isEmpty(throwable.getMessage())) { message.append(throwable.getMessage()); } else { message.append("<unknown>"); } return message.toString(); } /** * @return the graph * @since 26.2.2007 */ public TransformationGraph getTransformationGraph() { return graph; } public void setUseJMX(boolean useJMX) { this.provideJMX = useJMX; } public GraphRuntimeContext getGraphRuntimeContext() { return runtimeContext; } public CloverJMX getCloverJmx() { return cloverJMX; } public boolean isFinishJMX() { return finishJMX; } public void setFinishJMX(boolean finishJMX) { this.finishJMX = finishJMX; } public IThreadManager getThreadManager() { return threadManager; } public void setThreadManager(IThreadManager threadManager) { this.threadManager = threadManager; } public TransformationGraph getGraph() { return graph; } public IAuthorityProxy getAuthorityProxy() { return getGraph().getAuthorityProxy(); } }
FIX: better error handling git-svn-id: 7003860f782148507aa0d02fa3b12992383fb6a5@8803 a09ad3ba-1a0f-0410-b1b9-c67202f10d70
cloveretl.engine/src/org/jetel/graph/runtime/WatchDog.java
FIX: better error handling
Java
apache-2.0
8a8df3550eb1edd0c29b13018cac111a4c1faf42
0
ascrutae/sky-walking,apache/skywalking,apache/skywalking,ascrutae/sky-walking,apache/skywalking,OpenSkywalking/skywalking,ascrutae/sky-walking,apache/skywalking,apache/skywalking,OpenSkywalking/skywalking,ascrutae/sky-walking,apache/skywalking,apache/skywalking
/* * 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.skywalking.apm.commons.datacarrier.consumer; import java.util.ArrayList; import java.util.List; import org.apache.skywalking.apm.commons.datacarrier.buffer.Channels; import org.apache.skywalking.apm.commons.datacarrier.buffer.QueueBuffer; /** * MultipleChannelsConsumer represent a single consumer thread, but support multiple channels with their {@link * IConsumer}s */ public class MultipleChannelsConsumer extends Thread { private volatile boolean running; private volatile ArrayList<Group> consumeTargets; private volatile long size; private final long consumeCycle; public MultipleChannelsConsumer(String threadName, long consumeCycle) { super(threadName); this.consumeTargets = new ArrayList<Group>(); this.consumeCycle = consumeCycle; } @Override public void run() { running = true; final List consumeList = new ArrayList(2000); while (running) { boolean hasData = false; for (Group target : consumeTargets) { boolean consume = consume(target, consumeList); hasData = hasData || consume; } if (!hasData) { try { Thread.sleep(consumeCycle); } catch (InterruptedException e) { } } } // consumer thread is going to stop // consume the last time for (Group target : consumeTargets) { consume(target, consumeList); target.consumer.onExit(); } } private boolean consume(Group target, List consumeList) { for (int i = 0; i < target.channels.getChannelSize(); i++) { QueueBuffer buffer = target.channels.getBuffer(i); buffer.obtain(consumeList); } if (!consumeList.isEmpty()) { try { target.consumer.consume(consumeList); } catch (Throwable t) { target.consumer.onError(consumeList, t); } finally { consumeList.clear(); } return true; } return false; } /** * Add a new target channels. */ public void addNewTarget(Channels channels, IConsumer consumer) { Group group = new Group(channels, consumer); // Recreate the new list to avoid change list while the list is used in consuming. ArrayList<Group> newList = new ArrayList<Group>(); for (Group target : consumeTargets) { newList.add(target); } newList.add(group); consumeTargets = newList; size += channels.size(); } public long size() { return size; } void shutdown() { running = false; } private static class Group { private Channels channels; private IConsumer consumer; public Group(Channels channels, IConsumer consumer) { this.channels = channels; this.consumer = consumer; } } }
apm-commons/apm-datacarrier/src/main/java/org/apache/skywalking/apm/commons/datacarrier/consumer/MultipleChannelsConsumer.java
/* * 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.skywalking.apm.commons.datacarrier.consumer; import java.util.ArrayList; import java.util.List; import org.apache.skywalking.apm.commons.datacarrier.buffer.Channels; import org.apache.skywalking.apm.commons.datacarrier.buffer.QueueBuffer; /** * MultipleChannelsConsumer represent a single consumer thread, but support multiple channels with their {@link * IConsumer}s */ public class MultipleChannelsConsumer extends Thread { private volatile boolean running; private volatile ArrayList<Group> consumeTargets; private volatile long size; private final long consumeCycle; public MultipleChannelsConsumer(String threadName, long consumeCycle) { super(threadName); this.consumeTargets = new ArrayList<Group>(); this.consumeCycle = consumeCycle; } @Override public void run() { running = true; final List consumeList = new ArrayList(2000); while (running) { boolean hasData = false; for (Group target : consumeTargets) { boolean consume = consume(target, consumeList); hasData = hasData || consume; } if (!hasData) { try { Thread.sleep(consumeCycle); } catch (InterruptedException e) { } } } // consumer thread is going to stop // consume the last time for (Group target : consumeTargets) { consume(target, consumeList); target.consumer.onExit(); } } private boolean consume(Group target, List consumeList) { for (int i = 0; i < target.channels.getChannelSize(); i++) { QueueBuffer buffer = target.channels.getBuffer(i); buffer.obtain(consumeList); } if (!consumeList.isEmpty()) { try { target.consumer.consume(consumeList); } catch (Throwable t) { target.consumer.onError(consumeList, t); } finally { consumeList.clear(); } return true; } return false; } /** * Add a new target channels. */ public void addNewTarget(Channels channels, IConsumer consumer) { Group group = new Group(channels, consumer); // Recreate the new list to avoid change list while the list is used in consuming. ArrayList<Group> newList = new ArrayList<Group>(); for (Group target : consumeTargets) { newList.add(target); } newList.add(group); consumeTargets = newList; size += channels.size(); } public long size() { return size; } void shutdown() { running = false; } private class Group { private Channels channels; private IConsumer consumer; public Group(Channels channels, IConsumer consumer) { this.channels = channels; this.consumer = consumer; } } }
fix Classcanbestatic (#5597) Inner class is non-static but does not reference enclosing class ref: https://errorprone.info/bugpattern/ClassCanBeStatic Co-authored-by: 吴晟 Wu Sheng <[email protected]>
apm-commons/apm-datacarrier/src/main/java/org/apache/skywalking/apm/commons/datacarrier/consumer/MultipleChannelsConsumer.java
fix Classcanbestatic (#5597)
Java
apache-2.0
a26f2d31ca159749fd1ffd23b501c9e07ff2cfb0
0
metaborg/mb-rep,metaborg/mb-rep
package org.spoofax.interpreter.library.language.spxlang.index.data; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.UUID; import org.spoofax.interpreter.library.language.spxlang.index.SpxSemanticIndexFacade; import org.spoofax.interpreter.terms.IStrategoAppl; import org.spoofax.interpreter.terms.IStrategoConstructor; import org.spoofax.interpreter.terms.IStrategoList; import org.spoofax.interpreter.terms.IStrategoTerm; import org.spoofax.interpreter.terms.ITermFactory; import org.spoofax.terms.attachments.TermAttachmentSerializer; public class SpxSymbol extends SpxBaseSymbol implements Serializable{ private static final long serialVersionUID = -5293805213473800423L; private String _data; private String _type; private NamespaceUri _namespace; // refer to the namespace uri . public SpxSymbol (IStrategoTerm id){super(id);} public SpxSymbol (IStrategoTerm id , String type){ this(id) ; _type = type; } public String type() { assert _type != null : "Non-Null _type is expected. "; return _type; } public String getDataString () {return _data;} public NamespaceUri namespaceUri() { return _namespace; } void setType(String type) { _type = type; } IStrategoTerm deserializedDataToTerm(ITermFactory fac , TermAttachmentSerializer serializer) { IStrategoTerm deserializedAtermWithAnnotation = fac.parseFromString(_data); IStrategoTerm deserializedAterm = serializer.fromAnnotations(deserializedAtermWithAnnotation, true); return deserializedAterm; } void serializerDataString(TermAttachmentSerializer serializer, IStrategoTerm data) throws IOException { IStrategoTerm annotatedTerm = serializer.toAnnotations(data); StringBuilder sb = new StringBuilder(); annotatedTerm.writeAsString(sb ,Integer.MAX_VALUE); _data = sb.toString(); } public IStrategoConstructor typeCons(SpxSemanticIndexFacade facade){ return facade.getConstructor( type() , 0); } public void setNamespace(NamespaceUri id){ _namespace = id;} public boolean equalType (IStrategoConstructor term) { return _type.equals(term.getName()); } /** * Return symbols that has type equals expectedType. In case of expectedType equals null, * it returns all the symbols. * * @param expectedType * @param symbols * @return {@link List} of {@link SpxSymbol} */ public static List<SpxSymbol> filterByType(IStrategoConstructor expectedType , Iterable<SpxSymbol> symbols){ List<SpxSymbol> retSymbols = new ArrayList<SpxSymbol>(); if( symbols != null){ for(SpxSymbol s : symbols){ if( (expectedType==null) || s.equalType(expectedType) ){ retSymbols.add(s) ;} } } return retSymbols; } public IStrategoTerm toTerm (SpxSemanticIndexFacade facade) throws SpxSymbolTableException{ final ITermFactory termFactory = facade.getTermFactory(); //Type IStrategoConstructor spxTypeCtor = this.typeCons(facade); IStrategoAppl spxTypeCtorAppl = termFactory.makeAppl(spxTypeCtor); //Data IStrategoTerm deserializedDataToTerm = this.deserializedDataToTerm(termFactory, facade.getTermAttachmentSerializer()); //Enclosing Namespace IStrategoConstructor qnameCons = facade.getQNameCon(); IStrategoAppl nsQNameAppl = this.namespaceUri().resolve(facade.persistenceManager().spxSymbolTable()).toTypedQualifiedName(facade); //ID/Key IStrategoTerm id = this.Id(termFactory); //TODO : It might require term conversion. return (IStrategoTerm)termFactory.makeAppl( facade.getSymbolTableEntryDefCon(), nsQNameAppl, //ns qname spxTypeCtorAppl, // type id, //id deserializedDataToTerm ) ; } public static IStrategoTerm toTerms(SpxSemanticIndexFacade facade , Set<SpxSymbol> symbols) throws SpxSymbolTableException{ IStrategoList result = facade.getTermFactory().makeList(); if( symbols != null){ Object[] arrSymbols = symbols.toArray() ; for( int i = arrSymbols.length-1 ; i>= 0 ; i--) { result = facade.getTermFactory().makeListCons( ((SpxSymbol) arrSymbols[i]).toTerm(facade), result); } } return result; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((_data == null) ? 0 : _data.hashCode()); result = prime * result + ((_namespace == null) ? 0 : _namespace.hashCode()); result = prime * result + ((_type == null) ? 0 : _type.hashCode()); return result; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; SpxSymbol other = (SpxSymbol) obj; if (_data == null) { if (other._data != null) return false; } else if (!_data.equals(other._data)) return false; if (_namespace == null) { if (other._namespace != null) return false; } else if (!_namespace.equals(other._namespace)) return false; if (_type == null) { if (other._type != null) return false; } else if (!_type.equals(other._type)) return false; return true; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "SpxSymbol [ Id : " + this.getId() + " Type= " + _type + ", Namespace=" + _namespace + "]"; } public String printSymbol(){ return "\t\tId = " + this.getId() + "| Type = " + _type + "| Namespace = "+ _namespace+"\n"; } }
org.spoofax.interpreter.library.language/src/org/spoofax/interpreter/library/language/spxlang/index/data/SpxSymbol.java
package org.spoofax.interpreter.library.language.spxlang.index.data; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.UUID; import org.spoofax.interpreter.library.language.spxlang.index.SpxSemanticIndexFacade; import org.spoofax.interpreter.terms.IStrategoAppl; import org.spoofax.interpreter.terms.IStrategoConstructor; import org.spoofax.interpreter.terms.IStrategoList; import org.spoofax.interpreter.terms.IStrategoTerm; import org.spoofax.interpreter.terms.ITermFactory; import org.spoofax.terms.attachments.TermAttachmentSerializer; public class SpxSymbol extends SpxBaseSymbol implements Serializable{ private static final long serialVersionUID = -5293805213473800423L; private String _data; private String _type; private NamespaceUri _namespace; // refer to the namespace uri . public SpxSymbol (IStrategoTerm id){super(id);} public SpxSymbol (IStrategoTerm id , String type){ this(id) ; _type = type; } public String type() { assert _type != null : "Non-Null _type is expected. "; return _type; } public String getDataString () {return _data;} public NamespaceUri namespaceUri() { return _namespace; } void setType(String type) { _type = type; } IStrategoTerm deserializedDataToTerm(ITermFactory fac , TermAttachmentSerializer serializer) { IStrategoTerm deserializedAtermWithAnnotation = fac.parseFromString(_data); IStrategoTerm deserializedAterm = serializer.fromAnnotations(deserializedAtermWithAnnotation, true); return deserializedAterm; } void serializerDataString(TermAttachmentSerializer serializer, IStrategoTerm data) throws IOException { IStrategoTerm annotatedTerm = serializer.toAnnotations(data); StringBuilder sb = new StringBuilder(); annotatedTerm.writeAsString(sb ,Integer.MAX_VALUE); _data = sb.toString(); } public IStrategoConstructor typeCons(SpxSemanticIndexFacade facade){ return facade.getConstructor( type() , 0); } public void setNamespace(NamespaceUri id){ _namespace = id;} public boolean equalType (IStrategoConstructor term) { return _type.equals(term.getName()); } /** * Return symbols that has type equals expectedType. In case of expectedType equals null, * it returns all the symbols. * * @param expectedType * @param symbols * @return {@link List} of {@link SpxSymbol} */ public static List<SpxSymbol> filterByType(IStrategoConstructor expectedType , Iterable<SpxSymbol> symbols){ List<SpxSymbol> retSymbols = new ArrayList<SpxSymbol>(); if( symbols != null){ for(SpxSymbol s : symbols){ if( (expectedType==null) || s.equalType(expectedType) ){ retSymbols.add(s) ;} } } return retSymbols; } public IStrategoTerm toTerm (SpxSemanticIndexFacade facade) throws SpxSymbolTableException{ final ITermFactory termFactory = facade.getTermFactory(); //Type IStrategoConstructor spxTypeCtor = this.typeCons(facade); IStrategoAppl spxTypeCtorAppl = termFactory.makeAppl(spxTypeCtor); //Data IStrategoTerm deserializedDataToTerm = this.deserializedDataToTerm(termFactory, facade.getTermAttachmentSerializer()); //Enclosing Namespace IStrategoConstructor qnameCons = facade.getQNameCon(); IStrategoAppl nsQNameAppl = this.namespaceUri().resolve(facade.persistenceManager().spxSymbolTable()).toTypedQualifiedName(facade); //ID/Key IStrategoTerm id = this.Id(termFactory); //TODO : It might require term conversion. return (IStrategoTerm)termFactory.makeAppl( facade.getSymbolTableEntryDefCon(), nsQNameAppl, //ns qname spxTypeCtorAppl, // type id, //id deserializedDataToTerm ) ; } public static IStrategoTerm toTerms(SpxSemanticIndexFacade facade , Set<SpxSymbol> symbols) throws SpxSymbolTableException{ IStrategoList result = facade.getTermFactory().makeList(); Object[] arrSymbols = symbols.toArray() ; if( symbols != null) for( int i = arrSymbols.length-1 ; i>= 0 ; i--) { result = facade.getTermFactory().makeListCons( ((SpxSymbol) arrSymbols[i]).toTerm(facade), result); } return result; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((_data == null) ? 0 : _data.hashCode()); result = prime * result + ((_namespace == null) ? 0 : _namespace.hashCode()); result = prime * result + ((_type == null) ? 0 : _type.hashCode()); return result; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; SpxSymbol other = (SpxSymbol) obj; if (_data == null) { if (other._data != null) return false; } else if (!_data.equals(other._data)) return false; if (_namespace == null) { if (other._namespace != null) return false; } else if (!_namespace.equals(other._namespace)) return false; if (_type == null) { if (other._type != null) return false; } else if (!_type.equals(other._type)) return false; return true; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "SpxSymbol [ Id : " + this.getId() + " Type= " + _type + ", Namespace=" + _namespace + "]"; } public String printSymbol(){ return "\t\tId = " + this.getId() + "| Type = " + _type + "| Namespace = "+ _namespace+"\n"; } }
svn path=/spoofax/trunk/spoofax/org.spoofax.interpreter.library.language/; revision=23468
org.spoofax.interpreter.library.language/src/org/spoofax/interpreter/library/language/spxlang/index/data/SpxSymbol.java
Java
apache-2.0
d00c2080e41fc90a75343c7c1b1e5f59edfefc2f
0
googleinterns/gpay-virtual-queue,googleinterns/gpay-virtual-queue,googleinterns/gpay-virtual-queue
/* Copyright 2020 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.google.gpay.virtualqueue.backendservice.repository; import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import com.google.gpay.virtualqueue.backendservice.model.Shop; import com.google.gpay.virtualqueue.backendservice.model.Token; import com.google.gpay.virtualqueue.backendservice.model.Shop.ShopStatus; import com.google.gpay.virtualqueue.backendservice.model.Token.Status; import com.google.gpay.virtualqueue.backendservice.proto.CreateShopRequest; import com.google.gpay.virtualqueue.backendservice.proto.UpdateShopStatusRequest; import com.google.gpay.virtualqueue.backendservice.proto.UpdateShopStatusResponse; import com.google.gpay.virtualqueue.backendservice.proto.UpdateTokenStatusRequest; import com.google.gpay.virtualqueue.backendservice.proto.UpdateTokenStatusResponse; import static com.google.gpay.virtualqueue.backendservice.repository.InMemoryVirtualQueueRepository.WAITING_TIME_MINS; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; @SpringBootTest @RunWith(SpringRunner.class) @ContextConfiguration(classes = InMemoryVirtualQueueRepository.class) public class InMemoryVirtualQueueRepositoryTest { InMemoryVirtualQueueRepository inMemoryVirtualQueueRepository = new InMemoryVirtualQueueRepository(); private static final String SHOP_OWNER_ID = "uid"; private static final String SHOP_NAME = "shopName"; private static final String SHOP_ADDRESS = "address"; private static final String PHONE_NUMBER = "+919012192800"; private static final String SHOP_TYPE = "shopType"; @BeforeEach public void setUp() { inMemoryVirtualQueueRepository.getTokenMap().clear(); inMemoryVirtualQueueRepository.getShopMap().clear(); inMemoryVirtualQueueRepository.getShopIdToListOfTokensMap().clear(); inMemoryVirtualQueueRepository.getShopIdToLastAllotedTokenMap().clear(); inMemoryVirtualQueueRepository.getShopOwnerMap().clear(); } @Test public void testCreateShop_success() throws Exception { // Arrange. CreateShopRequest shop = new CreateShopRequest(SHOP_OWNER_ID, SHOP_NAME, SHOP_ADDRESS, PHONE_NUMBER, SHOP_TYPE); // Act. UUID shopId = inMemoryVirtualQueueRepository.createShop(shop); // Assert. assertEquals("Size of shopMap", 1, inMemoryVirtualQueueRepository.getShopMap().size()); assertEquals("Shop Owner Id ", SHOP_OWNER_ID, inMemoryVirtualQueueRepository.getShopMap().get(shopId).getShopOwnerId()); assertEquals("Shop Name ", SHOP_NAME, inMemoryVirtualQueueRepository.getShopMap().get(shopId).getShopName()); assertEquals("Shop Address ", SHOP_ADDRESS, inMemoryVirtualQueueRepository.getShopMap().get(shopId).getAddress()); assertEquals("Shop Phone Number ", PHONE_NUMBER, inMemoryVirtualQueueRepository.getShopMap().get(shopId).getPhoneNumber()); assertEquals("Shop Type ", SHOP_TYPE, inMemoryVirtualQueueRepository.getShopMap().get(shopId).getShopType()); } @Test public void testGetWaitingTime() throws Exception { long waitingTime = inMemoryVirtualQueueRepository.getWaitingTime(); assertEquals("Waiting Time per customer is", WAITING_TIME_MINS, waitingTime); } @Test public void testGetNewToken_success() throws Exception { // Arrange. UUID shopId = addShopToRepository(SHOP_OWNER_ID, SHOP_NAME, SHOP_ADDRESS, PHONE_NUMBER, SHOP_TYPE); addTokenListToShop(shopId); // Act. Token newToken = inMemoryVirtualQueueRepository.getNewToken(shopId); // Assert. UUID tokenId = newToken.getTokenId(); int expectedTokenMapSize = 1; Integer expectedTokenNumber = 1; UUID expectedShopId = inMemoryVirtualQueueRepository.getTokenMap().get(tokenId).getShopId(); assertEquals("Size of tokenMap", inMemoryVirtualQueueRepository.getTokenMap().size(), expectedTokenMapSize); assertEquals("Token number is", inMemoryVirtualQueueRepository.getTokenMap().get(tokenId).getTokenNumber(), expectedTokenNumber); assertEquals("Shop id is", shopId, expectedShopId); } @Test public void testGetTokensForShop_success() throws Exception { // Arrange. UUID shopId = addShopToRepository(SHOP_OWNER_ID, SHOP_NAME, SHOP_ADDRESS, PHONE_NUMBER, SHOP_TYPE); addTokenListToShop(shopId); // Act. List<Token> getTokensResponseList = inMemoryVirtualQueueRepository.getTokens(shopId); // Assert. assertEquals("Size of token list", getTokensResponseList.size(), inMemoryVirtualQueueRepository.getShopIdToListOfTokensMap().get(shopId).size()); } @Test public void testUpdateToken_success() throws Exception { // Arrange. UUID tokenId = addTokenToTokenMap(); UpdateTokenStatusRequest updateTokenStatusRequest = new UpdateTokenStatusRequest(tokenId, Status.CANCELLED_BY_CUSTOMER); // Act. UpdateTokenStatusResponse updateTokenStatusResponse = inMemoryVirtualQueueRepository.updateToken(updateTokenStatusRequest); // Assert. assertEquals("token map status is", inMemoryVirtualQueueRepository.getTokenMap().get(tokenId).getStatus(), updateTokenStatusResponse.getUpdatedToken().getStatus()); } @Test public void testUpdateShop_success() throws Exception { // Arrange. UUID shopId = addShopToRepository(SHOP_OWNER_ID, SHOP_NAME, SHOP_ADDRESS, PHONE_NUMBER, SHOP_TYPE); addTokenListToShop(shopId); UpdateShopStatusRequest updateShopStatusRequest = new UpdateShopStatusRequest(shopId, ShopStatus.DELETED); // Act. UpdateShopStatusResponse updateShopStatusResponse = inMemoryVirtualQueueRepository.updateShop(updateShopStatusRequest); // Assert. assertEquals("Shop status is", inMemoryVirtualQueueRepository.getShopMap().get(shopId).getStatus(), updateShopStatusResponse.getShop().getStatus()); } @Test public void testGetCustomersAhead_success() throws Exception { // Arrange. UUID tokenId = addTokenToTokenMap(); UUID shopId = inMemoryVirtualQueueRepository.getTokenMap().get(tokenId).getShopId(); addTokenListToShop(shopId); // Act. long customersAhead = inMemoryVirtualQueueRepository.getCustomersAhead(tokenId); // Assert. List<Token> expectedTokensList = inMemoryVirtualQueueRepository.getShopIdToListOfTokensMap().get(shopId).stream().takeWhile(token -> !token.getTokenId().equals(tokenId)).collect(Collectors.toList()); assertEquals("Number of customers ahead is", expectedTokensList.stream().filter(token -> Status.ACTIVE.equals(token.getStatus())).count(), customersAhead); } @Test public void testGetShop_success() { // Arrange. UUID shopId = addShopToRepository(SHOP_OWNER_ID, SHOP_NAME, SHOP_ADDRESS, PHONE_NUMBER, SHOP_TYPE); // Act. Shop newShop = inMemoryVirtualQueueRepository.getShop(shopId); // Assert. assertEquals("Shop Owner Id ", SHOP_OWNER_ID, newShop.getShopOwnerId()); assertEquals("Shop Name ", SHOP_NAME, newShop.getShopName()); assertEquals("Shop Address ", SHOP_ADDRESS, newShop.getAddress()); assertEquals("Shop Phone Number ", PHONE_NUMBER, newShop.getPhoneNumber()); assertEquals("Shop Type ", SHOP_TYPE, newShop.getShopType()); } private UUID addShopToRepository(String shopOwnerId, String shopName, String shopAddress, String phoneNumber, String ShopType) { Shop shop = new Shop(shopOwnerId, shopName, shopAddress, phoneNumber, ShopType); shop.setStatus(ShopStatus.ACTIVE); UUID shopId = UUID.randomUUID(); inMemoryVirtualQueueRepository.getShopMap().put(shopId, shop); inMemoryVirtualQueueRepository.getShopIdToLastAllotedTokenMap().put(shopId, new AtomicInteger(0)); return shopId; } private void addTokenListToShop(UUID shopId) { List<Token> tokens = new ArrayList<>(); tokens.add(new Token(UUID.randomUUID(), shopId, 1, Status.ACTIVE)); inMemoryVirtualQueueRepository.getShopIdToListOfTokensMap().put(shopId, tokens); } private UUID addTokenToTokenMap() { UUID tokenId = UUID.randomUUID(); UUID shopId = UUID.randomUUID(); Token token = new Token(tokenId, shopId, 1); token.setStatus(Status.ACTIVE); inMemoryVirtualQueueRepository.getTokenMap().put(tokenId, token); return tokenId; } }
backendservice/src/test/java/com/google/gpay/virtualqueue/backendservice/repository/InMemoryVirtualQueueRepositoryTest.java
/* Copyright 2020 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.google.gpay.virtualqueue.backendservice.repository; import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; import com.google.gpay.virtualqueue.backendservice.model.Shop; import com.google.gpay.virtualqueue.backendservice.model.Token; import com.google.gpay.virtualqueue.backendservice.model.Shop.ShopStatus; import com.google.gpay.virtualqueue.backendservice.model.Token.Status; import com.google.gpay.virtualqueue.backendservice.proto.CreateShopRequest; import com.google.gpay.virtualqueue.backendservice.proto.UpdateShopStatusRequest; import com.google.gpay.virtualqueue.backendservice.proto.UpdateShopStatusResponse; import com.google.gpay.virtualqueue.backendservice.proto.UpdateTokenStatusRequest; import com.google.gpay.virtualqueue.backendservice.proto.UpdateTokenStatusResponse; import static com.google.gpay.virtualqueue.backendservice.repository.InMemoryVirtualQueueRepository.WAITING_TIME_MINS; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; @SpringBootTest @RunWith(SpringRunner.class) @ContextConfiguration(classes = InMemoryVirtualQueueRepository.class) public class InMemoryVirtualQueueRepositoryTest { InMemoryVirtualQueueRepository inMemoryVirtualQueueRepository = new InMemoryVirtualQueueRepository(); private static final String SHOP_OWNER_ID = "uid"; private static final String SHOP_NAME = "shopName"; private static final String SHOP_ADDRESS = "address"; private static final String PHONE_NUMBER = "+919012192800"; private static final String SHOP_TYPE = "shopType"; @BeforeEach public void setUp() { inMemoryVirtualQueueRepository.getTokenMap().clear(); inMemoryVirtualQueueRepository.getShopMap().clear(); inMemoryVirtualQueueRepository.getShopIdToListOfTokensMap().clear(); inMemoryVirtualQueueRepository.getShopIdToLastAllotedTokenMap().clear(); inMemoryVirtualQueueRepository.getShopOwnerMap().clear(); } @Test public void testCreateShop_success() throws Exception { // Arrange. CreateShopRequest shop = new CreateShopRequest(SHOP_OWNER_ID, SHOP_NAME, SHOP_ADDRESS, PHONE_NUMBER, SHOP_TYPE); // Act. UUID shopId = inMemoryVirtualQueueRepository.createShop(shop); // Assert. assertEquals("Size of shopMap", 1, inMemoryVirtualQueueRepository.getShopMap().size()); assertEquals("Shop Owner Id ", SHOP_OWNER_ID, inMemoryVirtualQueueRepository.getShopMap().get(shopId).getShopOwnerId()); assertEquals("Shop Name ", SHOP_NAME, inMemoryVirtualQueueRepository.getShopMap().get(shopId).getShopName()); assertEquals("Shop Address ", SHOP_ADDRESS, inMemoryVirtualQueueRepository.getShopMap().get(shopId).getAddress()); assertEquals("Shop Phone Number ", PHONE_NUMBER, inMemoryVirtualQueueRepository.getShopMap().get(shopId).getPhoneNumber()); assertEquals("Shop Type ", SHOP_TYPE, inMemoryVirtualQueueRepository.getShopMap().get(shopId).getShopType()); } @Test public void testGetWaitingTime() throws Exception { long waitingTime = inMemoryVirtualQueueRepository.getWaitingTime(); assertEquals("Waiting Time per customer is", WAITING_TIME_MINS, waitingTime); } @Test public void testGetNewToken_success() throws Exception { // Arrange. UUID shopId = addShopToRepository(SHOP_OWNER_ID, SHOP_NAME, SHOP_ADDRESS, PHONE_NUMBER, SHOP_TYPE); addTokenListToShop(shopId); // Act. Token newToken = inMemoryVirtualQueueRepository.getNewToken(shopId); // Assert. UUID tokenId = newToken.getTokenId(); int expectedTokenMapSize = 1; Integer expectedTokenNumber = 1; UUID expectedShopId = inMemoryVirtualQueueRepository.getTokenMap().get(tokenId).getShopId(); assertEquals("Size of tokenMap", inMemoryVirtualQueueRepository.getTokenMap().size(), expectedTokenMapSize); assertEquals("Token number is", inMemoryVirtualQueueRepository.getTokenMap().get(tokenId).getTokenNumber(), expectedTokenNumber); assertEquals("Shop id is", shopId, expectedShopId); } @Test public void testGetTokensForShop_success() throws Exception { // Arrange. UUID shopId = addShopToRepository(SHOP_OWNER_ID, SHOP_NAME, SHOP_ADDRESS, PHONE_NUMBER, SHOP_TYPE); addTokenListToShop(shopId); // Act. List<Token> getTokensResponseList = inMemoryVirtualQueueRepository.getTokens(shopId); // Assert. assertEquals("Size of token list", getTokensResponseList.size(), inMemoryVirtualQueueRepository.getShopIdToListOfTokensMap().get(shopId).size()); } @Test public void testUpdateToken_success() throws Exception { // Arrange. UUID tokenId = addTokenToTokenMap(); UpdateTokenStatusRequest updateTokenStatusRequest = new UpdateTokenStatusRequest(tokenId, Status.CANCELLED_BY_CUSTOMER); // Act. UpdateTokenStatusResponse updateTokenStatusResponse = inMemoryVirtualQueueRepository.updateToken(updateTokenStatusRequest); // Assert. assertEquals("token map status is", inMemoryVirtualQueueRepository.getTokenMap().get(tokenId).getStatus(), updateTokenStatusResponse.getUpdatedToken().getStatus()); } @Test public void testUpdateShop_success() throws Exception { // Arrange. UUID shopId = addShopToRepository(SHOP_OWNER_ID, SHOP_NAME, SHOP_ADDRESS, PHONE_NUMBER, SHOP_TYPE); addTokenListToShop(shopId); UpdateShopStatusRequest updateShopStatusRequest = new UpdateShopStatusRequest(shopId, ShopStatus.DELETED); // Act. UpdateShopStatusResponse updateShopStatusResponse = inMemoryVirtualQueueRepository.updateShop(updateShopStatusRequest); // Assert. assertEquals("Shop status is", inMemoryVirtualQueueRepository.getShopMap().get(shopId).getStatus(), updateShopStatusResponse.getShop().getStatus()); } @Test public void testGetShop_success() { // Arrange. UUID shopId = addShopToRepository(SHOP_OWNER_ID, SHOP_NAME, SHOP_ADDRESS, PHONE_NUMBER, SHOP_TYPE); // Act. Shop newShop = inMemoryVirtualQueueRepository.getShop(shopId); // Assert. assertEquals("Shop Owner Id ", SHOP_OWNER_ID, newShop.getShopOwnerId()); assertEquals("Shop Name ", SHOP_NAME, newShop.getShopName()); assertEquals("Shop Address ", SHOP_ADDRESS, newShop.getAddress()); assertEquals("Shop Phone Number ", PHONE_NUMBER, newShop.getPhoneNumber()); assertEquals("Shop Type ", SHOP_TYPE, newShop.getShopType()); } private UUID addShopToRepository(String shopOwnerId, String shopName, String shopAddress, String phoneNumber, String ShopType) { Shop shop = new Shop(shopOwnerId, shopName, shopAddress, phoneNumber, ShopType); shop.setStatus(ShopStatus.ACTIVE); UUID shopId = UUID.randomUUID(); inMemoryVirtualQueueRepository.getShopMap().put(shopId, shop); inMemoryVirtualQueueRepository.getShopIdToLastAllotedTokenMap().put(shopId, new AtomicInteger(0)); return shopId; } private void addTokenListToShop(UUID shopId) { List<Token> tokens = new ArrayList<>(); tokens.add(new Token(UUID.randomUUID(), shopId, 1, Status.ACTIVE)); inMemoryVirtualQueueRepository.getShopIdToListOfTokensMap().put(shopId, tokens); } private UUID addTokenToTokenMap() { UUID tokenId = UUID.randomUUID(); UUID shopId = UUID.randomUUID(); Token token = new Token(tokenId, shopId, 1); token.setStatus(Status.ACTIVE); inMemoryVirtualQueueRepository.getTokenMap().put(tokenId, token); return tokenId; } }
add testGetCustomersAhead_success()
backendservice/src/test/java/com/google/gpay/virtualqueue/backendservice/repository/InMemoryVirtualQueueRepositoryTest.java
add testGetCustomersAhead_success()
Java
apache-2.0
d56e50e78a8aa1c78869aae77670bae0048f8f3a
0
BrunoEberhard/minimal-j,BrunoEberhard/minimal-j,BrunoEberhard/minimal-j
package ch.openech.mj.edit; import ch.openech.mj.edit.Editor.EditorFinishedListener; import ch.openech.mj.edit.form.IForm; import ch.openech.mj.page.Page; import ch.openech.mj.page.PageContext; import ch.openech.mj.toolkit.ClientToolkit; import ch.openech.mj.toolkit.IComponent; import ch.openech.mj.toolkit.ProgressListener; public class EditorPage extends Page { private final Editor<?> editor; private final IComponent layout; private boolean finished = false; public EditorPage(PageContext context, String[] editorClassAndArguments) { this(context, createEditor(editorClassAndArguments)); } public EditorPage(PageContext context, Class<?> editorClass, String[] arguments) { this(context, createEditor(editorClass, arguments)); } public EditorPage(PageContext context, String editorClass) { this(context, createEditor(editorClass)); } static Editor<?> createEditor(String... editorClassAndArguments) { try { Class<?> clazz = Class.forName(editorClassAndArguments[0]); if (editorClassAndArguments.length > 1) { Class<?>[] argumentClasses = new Class[editorClassAndArguments.length - 1]; Object[] arguments = new Object[editorClassAndArguments.length - 1]; for (int i = 0; i<argumentClasses.length; i++) { argumentClasses[i] = String.class; arguments[i] = editorClassAndArguments[i + 1]; } return (Editor<?>) clazz.getConstructor(argumentClasses).newInstance(arguments); } else { return (Editor<?>) clazz.newInstance(); } } catch (Exception x) { throw new RuntimeException("EditorPage Erstellung fehlgeschlagen", x); } } static Editor<?> createEditor(Class<?> editorClass, String... arguments) { try { if (arguments.length > 0) { Class<?>[] argumentClasses = new Class[arguments.length]; for (int i = 0; i<argumentClasses.length; i++) { argumentClasses[i] = String.class; } return (Editor<?>) editorClass.getConstructor(argumentClasses).newInstance(arguments); } else { return (Editor<?>) editorClass.newInstance(); } } catch (Exception x) { throw new RuntimeException("EditorPage Erstellung fehlgeschlagen", x); } } protected EditorPage(PageContext context, Editor<?> editor) { super(context); this.editor = editor; IForm<?> form = editor.startEditor(context); layout = ClientToolkit.getToolkit().createEditorLayout(form.getComponent(), editor.getActions()); editor.setEditorFinishedListener(new EditorFinishedListener() { private ProgressListener progressListener; @Override public void finished(String followLink) { finished = true; if (followLink != null) { getPageContext().show(followLink); } else { getPageContext().closeTab(); } if (progressListener != null) { progressListener.showProgress(100, 100); } } @Override public void progress(int value, int maximum) { if (progressListener == null) { progressListener = ClientToolkit.getToolkit().showProgress(getPageContext().getComponent(), "Save"); } progressListener.showProgress(value, maximum); } }); } @Override public String getTitle() { return editor.getTitle(); } @Override protected void setTitle(String title) { throw new IllegalStateException("setTitle on EditorPage not allowed"); } @Override public boolean isExclusive() { return !finished; } @Override public IComponent getPanel() { return layout; } public void checkedClose() { editor.checkedClose(); } }
Minimal-J/src/main/java/ch/openech/mj/edit/EditorPage.java
package ch.openech.mj.edit; import ch.openech.mj.edit.Editor.EditorFinishedListener; import ch.openech.mj.edit.form.IForm; import ch.openech.mj.page.Page; import ch.openech.mj.page.PageContext; import ch.openech.mj.toolkit.ClientToolkit; import ch.openech.mj.toolkit.IComponent; import ch.openech.mj.toolkit.ProgressListener; public class EditorPage extends Page { private final Editor<?> editor; private final IComponent layout; private boolean finished = false; public EditorPage(PageContext context, String[] editorClassAndArguments) { this(context, createEditor(editorClassAndArguments)); } public EditorPage(PageContext context, Class<?> editorClass, String[] arguments) { this(context, createEditor(editorClass, arguments)); } public EditorPage(PageContext context, String editorClass) { this(context, createEditor(editorClass)); } static Editor<?> createEditor(String... editorClassAndArguments) { try { Class<?> clazz = Class.forName(editorClassAndArguments[0]); if (editorClassAndArguments.length > 1) { Class<?>[] argumentClasses = new Class[editorClassAndArguments.length - 1]; Object[] arguments = new Object[editorClassAndArguments.length - 1]; for (int i = 0; i<argumentClasses.length; i++) { argumentClasses[i] = String.class; arguments[i] = editorClassAndArguments[i + 1]; } return (Editor<?>) clazz.getConstructor(argumentClasses).newInstance(arguments); } else { return (Editor<?>) clazz.newInstance(); } } catch (Exception x) { throw new RuntimeException("EditorPage Erstellung fehlgeschlagen", x); } } static Editor<?> createEditor(Class<?> editorClass, String... arguments) { try { if (arguments.length > 0) { Class<?>[] argumentClasses = new Class[arguments.length]; for (int i = 0; i<argumentClasses.length; i++) { argumentClasses[i] = String.class; } return (Editor<?>) editorClass.getConstructor(argumentClasses).newInstance(arguments); } else { return (Editor<?>) editorClass.newInstance(); } } catch (Exception x) { throw new RuntimeException("EditorPage Erstellung fehlgeschlagen", x); } } protected EditorPage(PageContext context, Editor<?> editor) { super(context); this.editor = editor; IForm<?> form = editor.startEditor(context); layout = ClientToolkit.getToolkit().createEditorLayout(form.getComponent(), editor.getActions()); setTitle(editor.getTitle()); editor.setEditorFinishedListener(new EditorFinishedListener() { private ProgressListener progressListener; @Override public void finished(String followLink) { finished = true; if (followLink != null) { getPageContext().show(followLink); } else { getPageContext().closeTab(); } if (progressListener != null) { progressListener.showProgress(100, 100); } } @Override public void progress(int value, int maximum) { if (progressListener == null) { progressListener = ClientToolkit.getToolkit().showProgress(getPageContext().getComponent(), "Save"); } progressListener.showProgress(value, maximum); } }); } @Override public boolean isExclusive() { return !finished; } @Override public IComponent getPanel() { return layout; } public void checkedClose() { editor.checkedClose(); } }
EditorPage: fix for new tab on exclusive tab
Minimal-J/src/main/java/ch/openech/mj/edit/EditorPage.java
EditorPage: fix for new tab on exclusive tab
Java
apache-2.0
f681f1ec6ca39895a8769c8a985309f76bf62342
0
paulcwarren/spring-content,paulcwarren/spring-content,paulcwarren/spring-content
package internal.org.springframework.content.rest.boot.autoconfigure; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration; import org.springframework.content.rest.config.HypermediaConfiguration; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration; @Configuration @ConditionalOnBean(RepositoryRestMvcConfiguration.class) @AutoConfigureAfter({ RepositoryRestMvcAutoConfiguration.class }) @Import(HypermediaConfiguration.class) public class HypermediaAutoConfiguration { // }
spring-content-rest-boot-starter/src/main/java/internal/org/springframework/content/rest/boot/autoconfigure/HypermediaAutoConfiguration.java
package internal.org.springframework.content.rest.boot.autoconfigure; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration; import org.springframework.content.rest.config.HypermediaConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration; @Configuration @ConditionalOnBean(RepositoryRestMvcConfiguration.class) @AutoConfigureAfter({ RepositoryRestMvcAutoConfiguration.class }) @Import(HypermediaConfiguration.class) public class HypermediaAutoConfiguration { @Bean public Object aBean() { return new Object(); } }
Remove unrequired bean
spring-content-rest-boot-starter/src/main/java/internal/org/springframework/content/rest/boot/autoconfigure/HypermediaAutoConfiguration.java
Remove unrequired bean
Java
apache-2.0
cee705ec353265ea38ceb5445910f15b581ff21c
0
allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.icons; import com.intellij.openapi.util.IconLoader; import javax.swing.*; /** * NOTE THIS FILE IS AUTO-GENERATED * DO NOT EDIT IT BY HAND, run "Generate icon classes" configuration instead */ public class AllIcons { public final static class Actions { /** 16x16 */ public static final Icon AddMulticaret = IconLoader.getIcon("/actions/AddMulticaret.svg"); /** 16x16 */ public static final Icon Annotate = IconLoader.getIcon("/actions/annotate.svg"); /** 16x16 */ public static final Icon Back = IconLoader.getIcon("/actions/back.svg"); /** 16x16 */ public static final Icon Cancel = IconLoader.getIcon("/actions/cancel.svg"); /** 16x16 */ public static final Icon ChangeView = IconLoader.getIcon("/actions/changeView.svg"); /** 12x12 */ public static final Icon Checked = IconLoader.getIcon("/actions/checked.svg"); /** 12x12 */ public static final Icon Checked_selected = IconLoader.getIcon("/actions/checked_selected.svg"); /** 16x16 */ public static final Icon CheckMulticaret = IconLoader.getIcon("/actions/CheckMulticaret.svg"); /** 16x16 */ public static final Icon CheckOut = IconLoader.getIcon("/actions/checkOut.svg"); /** 16x16 */ public static final Icon Close = IconLoader.getIcon("/actions/close.svg"); /** 16x16 */ public static final Icon CloseHovered = IconLoader.getIcon("/actions/closeHovered.svg"); /** 16x16 */ public static final Icon Collapseall = IconLoader.getIcon("/actions/collapseall.svg"); /** 16x16 */ public static final Icon Colors = IconLoader.getIcon("/actions/colors.svg"); /** 16x16 */ public static final Icon Commit = IconLoader.getIcon("/actions/commit.svg"); /** 16x16 */ public static final Icon Compile = IconLoader.getIcon("/actions/compile.svg"); /** 16x16 */ public static final Icon Copy = IconLoader.getIcon("/actions/copy.svg"); /** 16x16 */ public static final Icon DiagramDiff = IconLoader.getIcon("/actions/diagramDiff.svg"); /** 16x16 */ public static final Icon Diff = IconLoader.getIcon("/actions/diff.svg"); /** 16x16 */ public static final Icon DiffWithClipboard = IconLoader.getIcon("/actions/diffWithClipboard.svg"); /** 16x16 */ public static final Icon Download = IconLoader.getIcon("/actions/download.svg"); /** 16x16 */ public static final Icon Dump = IconLoader.getIcon("/actions/dump.svg"); /** 16x16 */ public static final Icon Edit = IconLoader.getIcon("/actions/edit.svg"); /** 16x16 */ public static final Icon EditSource = IconLoader.getIcon("/actions/editSource.svg"); /** 16x16 */ public static final Icon Execute = IconLoader.getIcon("/actions/execute.svg"); /** 16x16 */ public static final Icon Exit = IconLoader.getIcon("/actions/exit.svg"); /** 16x16 */ public static final Icon Expandall = IconLoader.getIcon("/actions/expandall.svg"); /** 16x16 */ public static final Icon Find = IconLoader.getIcon("/actions/find.svg"); /** 16x16 */ public static final Icon ForceRefresh = IconLoader.getIcon("/actions/forceRefresh.svg"); /** 16x16 */ public static final Icon Forward = IconLoader.getIcon("/actions/forward.svg"); /** 16x16 */ public static final Icon GC = IconLoader.getIcon("/actions/gc.svg"); /** 16x16 */ public static final Icon GroupBy = IconLoader.getIcon("/actions/groupBy.svg"); /** 16x16 */ public static final Icon GroupByClass = IconLoader.getIcon("/actions/GroupByClass.svg"); /** 16x16 */ public static final Icon GroupByFile = IconLoader.getIcon("/actions/GroupByFile.svg"); /** 16x16 */ public static final Icon GroupByMethod = IconLoader.getIcon("/actions/groupByMethod.svg"); /** 16x16 */ public static final Icon GroupByModule = IconLoader.getIcon("/actions/GroupByModule.svg"); /** 16x16 */ public static final Icon GroupByModuleGroup = IconLoader.getIcon("/actions/GroupByModuleGroup.svg"); /** 16x16 */ public static final Icon GroupByPackage = IconLoader.getIcon("/actions/GroupByPackage.svg"); /** 16x16 */ public static final Icon GroupByPrefix = IconLoader.getIcon("/actions/GroupByPrefix.svg"); /** 16x16 */ public static final Icon GroupByTestProduction = IconLoader.getIcon("/actions/groupByTestProduction.svg"); /** 16x16 */ public static final Icon Help = IconLoader.getIcon("/actions/help.svg"); /** 16x16 */ public static final Icon Highlighting = IconLoader.getIcon("/actions/highlighting.svg"); /** 16x16 */ public static final Icon Install = IconLoader.getIcon("/actions/install.svg"); /** 16x16 */ public static final Icon IntentionBulb = IconLoader.getIcon("/actions/intentionBulb.svg"); /** 16x16 */ public static final Icon Lightning = IconLoader.getIcon("/actions/lightning.svg"); /** 16x16 */ public static final Icon ListChanges = IconLoader.getIcon("/actions/listChanges.svg"); /** 16x16 */ public static final Icon ListFiles = IconLoader.getIcon("/actions/listFiles.svg"); /** 16x16 */ public static final Icon Menu_cut = IconLoader.getIcon("/actions/menu-cut.svg"); /** 16x16 */ public static final Icon Menu_open = IconLoader.getIcon("/actions/menu-open.svg"); /** 16x16 */ public static final Icon Menu_paste = IconLoader.getIcon("/actions/menu-paste.svg"); /** 16x16 */ public static final Icon Menu_saveall = IconLoader.getIcon("/actions/menu-saveall.svg"); /** 16x16 */ public static final Icon ModuleDirectory = IconLoader.getIcon("/actions/moduleDirectory.svg"); /** 16x16 */ public static final Icon More = IconLoader.getIcon("/actions/more.svg"); /** 12x12 */ public static final Icon Move_to_button = IconLoader.getIcon("/actions/move-to-button.svg"); /** 16x16 */ public static final Icon MoveDown = IconLoader.getIcon("/actions/moveDown.svg"); /** 16x16 */ public static final Icon MoveTo2 = IconLoader.getIcon("/actions/MoveTo2.svg"); /** 16x16 */ public static final Icon MoveToBottomLeft = IconLoader.getIcon("/actions/moveToBottomLeft.svg"); /** 16x16 */ public static final Icon MoveToBottomRight = IconLoader.getIcon("/actions/moveToBottomRight.svg"); /** 16x16 */ public static final Icon MoveToLeftBottom = IconLoader.getIcon("/actions/moveToLeftBottom.svg"); /** 16x16 */ public static final Icon MoveToLeftTop = IconLoader.getIcon("/actions/moveToLeftTop.svg"); /** 16x16 */ public static final Icon MoveToRightBottom = IconLoader.getIcon("/actions/moveToRightBottom.svg"); /** 16x16 */ public static final Icon MoveToRightTop = IconLoader.getIcon("/actions/moveToRightTop.svg"); /** 16x16 */ public static final Icon MoveToTopLeft = IconLoader.getIcon("/actions/moveToTopLeft.svg"); /** 16x16 */ public static final Icon MoveToTopRight = IconLoader.getIcon("/actions/moveToTopRight.svg"); /** 16x16 */ public static final Icon MoveUp = IconLoader.getIcon("/actions/moveUp.svg"); /** 16x16 */ public static final Icon New = IconLoader.getIcon("/actions/new.svg"); /** 16x16 */ public static final Icon NewFolder = IconLoader.getIcon("/actions/newFolder.svg"); /** 16x16 */ public static final Icon NextOccurence = IconLoader.getIcon("/actions/nextOccurence.svg"); /** 16x16 */ public static final Icon OfflineMode = IconLoader.getIcon("/actions/offlineMode.svg"); /** 16x16 */ public static final Icon OpenNewTab = IconLoader.getIcon("/actions/openNewTab.svg"); /** 16x16 */ public static final Icon Pause = IconLoader.getIcon("/actions/pause.svg"); /** 16x16 */ public static final Icon Play_back = IconLoader.getIcon("/actions/play_back.svg"); /** 16x16 */ public static final Icon Play_first = IconLoader.getIcon("/actions/play_first.svg"); /** 16x16 */ public static final Icon Play_forward = IconLoader.getIcon("/actions/play_forward.svg"); /** 16x16 */ public static final Icon Play_last = IconLoader.getIcon("/actions/play_last.svg"); /** 16x16 */ public static final Icon PopFrame = IconLoader.getIcon("/actions/popFrame.svg"); /** 16x16 */ public static final Icon Preview = IconLoader.getIcon("/actions/preview.svg"); /** 16x16 */ public static final Icon PreviewDetails = IconLoader.getIcon("/actions/previewDetails.svg"); /** 16x16 */ public static final Icon PreviewDetailsVertically = IconLoader.getIcon("/actions/previewDetailsVertically.svg"); /** 16x16 */ public static final Icon PreviousOccurence = IconLoader.getIcon("/actions/previousOccurence.svg"); /** 16x16 */ public static final Icon Profile = IconLoader.getIcon("/actions/profile.svg"); /** 16x16 */ public static final Icon ProfileBlue = IconLoader.getIcon("/actions/profileBlue.svg"); /** 16x16 */ public static final Icon ProfileCPU = IconLoader.getIcon("/actions/profileCPU.svg"); /** 16x16 */ public static final Icon ProfileMemory = IconLoader.getIcon("/actions/profileMemory.svg"); /** 16x16 */ public static final Icon ProfileRed = IconLoader.getIcon("/actions/profileRed.svg"); /** 16x16 */ public static final Icon ProfileYellow = IconLoader.getIcon("/actions/profileYellow.svg"); /** 16x16 */ public static final Icon ProjectDirectory = IconLoader.getIcon("/actions/projectDirectory.svg"); /** 16x16 */ public static final Icon Properties = IconLoader.getIcon("/actions/properties.svg"); /** 16x16 */ public static final Icon QuickfixBulb = IconLoader.getIcon("/actions/quickfixBulb.svg"); /** 16x16 */ public static final Icon QuickfixOffBulb = IconLoader.getIcon("/actions/quickfixOffBulb.svg"); /** 16x16 */ public static final Icon RealIntentionBulb = IconLoader.getIcon("/actions/realIntentionBulb.svg"); /** 16x16 */ public static final Icon Redo = IconLoader.getIcon("/actions/redo.svg"); /** 16x16 */ public static final Icon RefactoringBulb = IconLoader.getIcon("/actions/refactoringBulb.svg"); /** 16x16 */ public static final Icon Refresh = IconLoader.getIcon("/actions/refresh.svg"); /** 16x16 */ public static final Icon RemoveMulticaret = IconLoader.getIcon("/actions/RemoveMulticaret.svg"); /** 16x16 */ public static final Icon Replace = IconLoader.getIcon("/actions/replace.svg"); /** 16x16 */ public static final Icon Rerun = IconLoader.getIcon("/actions/rerun.svg"); /** 16x16 */ public static final Icon Restart = IconLoader.getIcon("/actions/restart.svg"); /** 16x16 */ public static final Icon RestartDebugger = IconLoader.getIcon("/actions/restartDebugger.svg"); /** 16x16 */ public static final Icon Resume = IconLoader.getIcon("/actions/resume.svg"); /** 16x16 */ public static final Icon Rollback = IconLoader.getIcon("/actions/rollback.svg"); /** 16x16 */ public static final Icon Run_anything = IconLoader.getIcon("/actions/run_anything.svg"); /** 16x16 */ public static final Icon RunToCursor = IconLoader.getIcon("/actions/runToCursor.svg"); /** 16x16 */ public static final Icon Scratch = IconLoader.getIcon("/actions/scratch.svg"); /** 16x16 */ public static final Icon Search = IconLoader.getIcon("/actions/search.svg"); /** 16x16 */ public static final Icon SearchNewLine = IconLoader.getIcon("/actions/searchNewLine.svg"); /** 16x16 */ public static final Icon SearchNewLineHover = IconLoader.getIcon("/actions/searchNewLineHover.svg"); /** 16x16 */ public static final Icon SearchWithHistory = IconLoader.getIcon("/actions/searchWithHistory.svg"); /** 16x16 */ public static final Icon Selectall = IconLoader.getIcon("/actions/selectall.svg"); /** 16x16 */ public static final Icon SetDefault = IconLoader.getIcon("/actions/setDefault.svg"); /** 14x14 */ public static final Icon Share = IconLoader.getIcon("/actions/share.png"); /** 16x16 */ public static final Icon ShortcutFilter = IconLoader.getIcon("/actions/shortcutFilter.svg"); /** 16x16 */ public static final Icon Show = IconLoader.getIcon("/actions/show.svg"); /** 16x16 */ public static final Icon ShowAsTree = IconLoader.getIcon("/actions/showAsTree.svg"); /** 16x16 */ public static final Icon ShowHiddens = IconLoader.getIcon("/actions/showHiddens.svg"); /** 16x16 */ public static final Icon ShowImportStatements = IconLoader.getIcon("/actions/showImportStatements.svg"); /** 16x16 */ public static final Icon ShowReadAccess = IconLoader.getIcon("/actions/showReadAccess.svg"); /** 16x16 */ public static final Icon ShowWriteAccess = IconLoader.getIcon("/actions/showWriteAccess.svg"); /** 16x16 */ public static final Icon SplitHorizontally = IconLoader.getIcon("/actions/splitHorizontally.svg"); /** 16x16 */ public static final Icon SplitVertically = IconLoader.getIcon("/actions/splitVertically.svg"); /** 16x16 */ public static final Icon StartDebugger = IconLoader.getIcon("/actions/startDebugger.svg"); /** 16x16 */ public static final Icon StartMemoryProfile = IconLoader.getIcon("/actions/startMemoryProfile.svg"); /** 16x16 */ public static final Icon StepOut = IconLoader.getIcon("/actions/stepOut.svg"); /** 16x16 */ public static final Icon StepOutCodeBlock = IconLoader.getIcon("/actions/stepOutCodeBlock.svg"); /** 16x16 */ public static final Icon Stub = IconLoader.getIcon("/actions/stub.svg"); /** 16x16 */ public static final Icon Suspend = IconLoader.getIcon("/actions/suspend.svg"); /** 16x16 */ public static final Icon SwapPanels = IconLoader.getIcon("/actions/swapPanels.svg"); /** 16x16 */ public static final Icon SynchronizeScrolling = IconLoader.getIcon("/actions/synchronizeScrolling.svg"); /** 16x16 */ public static final Icon SyncPanels = IconLoader.getIcon("/actions/syncPanels.svg"); /** 16x16 */ public static final Icon ToggleSoftWrap = IconLoader.getIcon("/actions/toggleSoftWrap.svg"); /** 16x16 */ public static final Icon TraceInto = IconLoader.getIcon("/actions/traceInto.svg"); /** 16x16 */ public static final Icon TraceOver = IconLoader.getIcon("/actions/traceOver.svg"); /** 16x16 */ public static final Icon Undo = IconLoader.getIcon("/actions/undo.svg"); /** 16x16 */ public static final Icon Uninstall = IconLoader.getIcon("/actions/uninstall.svg"); /** 16x16 */ public static final Icon Unselectall = IconLoader.getIcon("/actions/unselectall.svg"); /** 14x14 */ public static final Icon Unshare = IconLoader.getIcon("/actions/unshare.png"); /** 16x16 */ public static final Icon Upload = IconLoader.getIcon("/actions/upload.svg"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon AddFacesSupport = IconLoader.getIcon("/actions/addFacesSupport.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon AllLeft = IconLoader.getIcon("/actions/allLeft.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon AllRight = IconLoader.getIcon("/actions/allRight.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.PreviousOccurence */ @SuppressWarnings("unused") @Deprecated public static final Icon Browser_externalJavaDoc = AllIcons.Actions.PreviousOccurence; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Checked */ @SuppressWarnings("unused") @Deprecated public static final Icon Checked_small = AllIcons.Actions.Checked; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Checked_selected */ @SuppressWarnings("unused") @Deprecated public static final Icon Checked_small_selected = AllIcons.Actions.Checked_selected; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Checked */ @SuppressWarnings("unused") @Deprecated public static final Icon CheckedBlack = AllIcons.Actions.Checked; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Checked */ @SuppressWarnings("unused") @Deprecated public static final Icon CheckedGrey = AllIcons.Actions.Checked; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.CloseHovered */ @SuppressWarnings("unused") @Deprecated public static final Icon Clean = AllIcons.Actions.CloseHovered; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Close */ @SuppressWarnings("unused") @Deprecated public static final Icon CleanLight = AllIcons.Actions.Close; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Clear = IconLoader.getIcon("/actions/clear.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Close */ @SuppressWarnings("unused") @Deprecated public static final Icon CloseNew = AllIcons.Actions.Close; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.CloseHovered */ @SuppressWarnings("unused") @Deprecated public static final Icon CloseNewHovered = AllIcons.Actions.CloseHovered; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.IntentionBulb */ @SuppressWarnings("unused") @Deprecated public static final Icon CreateFromUsage = AllIcons.Actions.IntentionBulb; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon CreatePatch = IconLoader.getIcon("/actions/createPatch.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Close */ @SuppressWarnings("unused") @Deprecated public static final Icon Cross = AllIcons.Actions.Close; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Cancel */ @SuppressWarnings("unused") @Deprecated public static final Icon Delete = AllIcons.Actions.Cancel; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Diff */ @SuppressWarnings("unused") @Deprecated public static final Icon DiffPreview = AllIcons.Actions.Diff; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Diff */ @SuppressWarnings("unused") @Deprecated public static final Icon DiffWithCurrent = AllIcons.Actions.Diff; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowDown */ @SuppressWarnings("unused") @Deprecated public static final Icon Down = AllIcons.General.ArrowDown; /** @deprecated to be removed in IDEA 2020 - use J2EEIcons.ErDiagram */ @SuppressWarnings("unused") @Deprecated public static final Icon ErDiagram = IconLoader.getIcon("/actions/erDiagram.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.Remove */ @SuppressWarnings("unused") @Deprecated public static final Icon Exclude = AllIcons.General.Remove; /** @deprecated to be removed in IDEA 2020 - use AllIcons.ToolbarDecorator.Export */ @SuppressWarnings("unused") @Deprecated public static final Icon Export = AllIcons.ToolbarDecorator.Export; @SuppressWarnings("unused") @Deprecated public static final Icon FileStatus = IconLoader.getIcon("/actions/fileStatus.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.Filter */ @SuppressWarnings("unused") @Deprecated public static final Icon Filter_small = AllIcons.General.Filter; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Find */ @SuppressWarnings("unused") @Deprecated public static final Icon FindPlain = AllIcons.Actions.Find; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon FindWhite = IconLoader.getIcon("/actions/findWhite.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Download */ @SuppressWarnings("unused") @Deprecated public static final Icon Get = AllIcons.Actions.Download; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowLeft */ @SuppressWarnings("unused") @Deprecated public static final Icon Left = AllIcons.General.ArrowLeft; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Find */ @SuppressWarnings("unused") @Deprecated public static final Icon Menu_find = AllIcons.Actions.Find; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Help */ @SuppressWarnings("unused") @Deprecated public static final Icon Menu_help = AllIcons.Actions.Help; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Replace */ @SuppressWarnings("unused") @Deprecated public static final Icon Menu_replace = AllIcons.Actions.Replace; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.HideToolWindow */ @SuppressWarnings("unused") @Deprecated public static final Icon Minimize = AllIcons.General.HideToolWindow; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Nodes.Module */ @SuppressWarnings("unused") @Deprecated public static final Icon Module = AllIcons.Nodes.Module; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Move_to_button */ @SuppressWarnings("unused") @Deprecated public static final Icon Move_to_button_top = AllIcons.Actions.Move_to_button; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.MoveTo2 */ @SuppressWarnings("unused") @Deprecated public static final Icon MoveToAnotherChangelist = AllIcons.Actions.MoveTo2; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.MoveTo2 */ @SuppressWarnings("unused") @Deprecated public static final Icon MoveToStandardPlace = AllIcons.Actions.MoveTo2; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Multicaret = IconLoader.getIcon("/actions/multicaret.svg"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Forward */ @SuppressWarnings("unused") @Deprecated public static final Icon Nextfile = AllIcons.Actions.Forward; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Back */ @SuppressWarnings("unused") @Deprecated public static final Icon Prevfile = AllIcons.Actions.Back; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon QuickList = IconLoader.getIcon("/actions/quickList.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon RealIntentionOffBulb = IconLoader.getIcon("/actions/realIntentionOffBulb.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Rollback */ @SuppressWarnings("unused") @Deprecated public static final Icon Reset_to_default = AllIcons.Actions.Rollback; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Rollback */ @SuppressWarnings("unused") @Deprecated public static final Icon Reset = AllIcons.Actions.Rollback; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Uninstall */ @SuppressWarnings("unused") @Deprecated public static final Icon Reset_to_empty = AllIcons.Actions.Uninstall; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowRight */ @SuppressWarnings("unused") @Deprecated public static final Icon Right = AllIcons.General.ArrowRight; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Preview */ @SuppressWarnings("unused") @Deprecated public static final Icon ShowChangesOnly = AllIcons.Actions.Preview; @SuppressWarnings("unused") @Deprecated public static final Icon ShowViewer = IconLoader.getIcon("/actions/showViewer.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.MoveUp */ @SuppressWarnings("unused") @Deprecated public static final Icon SortAsc = AllIcons.Actions.MoveUp; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.MoveDown */ @SuppressWarnings("unused") @Deprecated public static final Icon SortDesc = AllIcons.Actions.MoveDown; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.SetDefault */ @SuppressWarnings("unused") @Deprecated public static final Icon Submit1 = AllIcons.Actions.SetDefault; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Refresh */ @SuppressWarnings("unused") @Deprecated public static final Icon SynchronizeFS = AllIcons.Actions.Refresh; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowUp */ @SuppressWarnings("unused") @Deprecated public static final Icon UP = AllIcons.General.ArrowUp; } public final static class CodeStyle { /** 16x16 */ public static final Icon AddNewSectionRule = IconLoader.getIcon("/codeStyle/AddNewSectionRule.svg"); public final static class Mac { /** @deprecated to be removed in IDEA 2020 - use AllIcons.CodeStyle.AddNewSectionRule */ @SuppressWarnings("unused") @Deprecated public static final Icon AddNewSectionRule = AllIcons.CodeStyle.AddNewSectionRule; } /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.GearPlain */ @SuppressWarnings("unused") @Deprecated public static final Icon Gear = AllIcons.General.GearPlain; } public final static class Css { /** @deprecated use 'icons.CssIcons' from 'intellij.css' module instead */ @SuppressWarnings("unused") @Deprecated public static final Icon Atrule = IconLoader.getIcon("/css/atrule.png"); /** @deprecated use 'icons.CssIcons' from 'intellij.css' module instead */ @SuppressWarnings("unused") @Deprecated public static final Icon Import = IconLoader.getIcon("/css/import.png"); /** @deprecated use 'icons.CssIcons' from 'intellij.css' module instead */ @SuppressWarnings("unused") @Deprecated public static final Icon Property = IconLoader.getIcon("/css/property.png"); } public final static class Darcula { @SuppressWarnings("unused") @Deprecated public static final Icon DoubleComboArrow = IconLoader.getIcon("/darcula/doubleComboArrow.png"); @SuppressWarnings("unused") @Deprecated public static final Icon TreeNodeCollapsed = IconLoader.getIcon("/darcula/treeNodeCollapsed.png"); @SuppressWarnings("unused") @Deprecated public static final Icon TreeNodeExpanded = IconLoader.getIcon("/darcula/treeNodeExpanded.png"); } public final static class Debugger { public final static class Actions { /** 16x16 */ public static final Icon Force_run_to_cursor = IconLoader.getIcon("/debugger/actions/force_run_to_cursor.svg"); /** 16x16 */ public static final Icon Force_step_into = IconLoader.getIcon("/debugger/actions/force_step_into.svg"); /** 16x16 */ public static final Icon Force_step_over = IconLoader.getIcon("/debugger/actions/force_step_over.svg"); } /** 16x16 */ public static final Icon AddToWatch = IconLoader.getIcon("/debugger/addToWatch.svg"); /** 16x16 */ public static final Icon AttachToProcess = IconLoader.getIcon("/debugger/attachToProcess.svg"); /** 16x16 */ public static final Icon ClassLevelWatch = IconLoader.getIcon("/debugger/classLevelWatch.svg"); /** 16x16 */ public static final Icon Console = IconLoader.getIcon("/debugger/console.svg"); /** 16x16 */ public static final Icon Db_array = IconLoader.getIcon("/debugger/db_array.svg"); /** 16x16 */ public static final Icon Db_db_object = IconLoader.getIcon("/debugger/db_db_object.svg"); /** 12x12 */ public static final Icon Db_dep_field_breakpoint = IconLoader.getIcon("/debugger/db_dep_field_breakpoint.svg"); /** 12x12 */ public static final Icon Db_dep_line_breakpoint = IconLoader.getIcon("/debugger/db_dep_line_breakpoint.svg"); /** 12x12 */ public static final Icon Db_dep_method_breakpoint = IconLoader.getIcon("/debugger/db_dep_method_breakpoint.svg"); /** 12x12 */ public static final Icon Db_disabled_breakpoint = IconLoader.getIcon("/debugger/db_disabled_breakpoint.svg"); /** 16x16 */ public static final Icon Db_disabled_breakpoint_process = IconLoader.getIcon("/debugger/db_disabled_breakpoint_process.svg"); /** 12x12 */ public static final Icon Db_disabled_exception_breakpoint = IconLoader.getIcon("/debugger/db_disabled_exception_breakpoint.svg"); /** 12x12 */ public static final Icon Db_disabled_field_breakpoint = IconLoader.getIcon("/debugger/db_disabled_field_breakpoint.svg"); /** 12x12 */ public static final Icon Db_disabled_method_breakpoint = IconLoader.getIcon("/debugger/db_disabled_method_breakpoint.svg"); /** 12x12 */ public static final Icon Db_exception_breakpoint = IconLoader.getIcon("/debugger/db_exception_breakpoint.svg"); /** 12x12 */ public static final Icon Db_field_breakpoint = IconLoader.getIcon("/debugger/db_field_breakpoint.svg"); /** 12x12 */ public static final Icon Db_invalid_breakpoint = IconLoader.getIcon("/debugger/db_invalid_breakpoint.svg"); /** 12x12 */ public static final Icon Db_method_breakpoint = IconLoader.getIcon("/debugger/db_method_breakpoint.svg"); /** 12x12 */ public static final Icon Db_muted_breakpoint = IconLoader.getIcon("/debugger/db_muted_breakpoint.svg"); /** 12x12 */ public static final Icon Db_muted_dep_field_breakpoint = IconLoader.getIcon("/debugger/db_muted_dep_field_breakpoint.svg"); /** 12x12 */ public static final Icon Db_muted_dep_line_breakpoint = IconLoader.getIcon("/debugger/db_muted_dep_line_breakpoint.svg"); /** 12x12 */ public static final Icon Db_muted_dep_method_breakpoint = IconLoader.getIcon("/debugger/db_muted_dep_method_breakpoint.svg"); /** 12x12 */ public static final Icon Db_muted_disabled_breakpoint = IconLoader.getIcon("/debugger/db_muted_disabled_breakpoint.svg"); /** 12x12 */ public static final Icon Db_muted_disabled_field_breakpoint = IconLoader.getIcon("/debugger/db_muted_disabled_field_breakpoint.svg"); /** 12x12 */ public static final Icon Db_muted_disabled_method_breakpoint = IconLoader.getIcon("/debugger/db_muted_disabled_method_breakpoint.svg"); /** 12x12 */ public static final Icon Db_muted_field_breakpoint = IconLoader.getIcon("/debugger/db_muted_field_breakpoint.svg"); /** 12x12 */ public static final Icon Db_muted_method_breakpoint = IconLoader.getIcon("/debugger/db_muted_method_breakpoint.svg"); /** 12x12 */ public static final Icon Db_no_suspend_breakpoint = IconLoader.getIcon("/debugger/db_no_suspend_breakpoint.svg"); /** 12x12 */ public static final Icon Db_no_suspend_field_breakpoint = IconLoader.getIcon("/debugger/db_no_suspend_field_breakpoint.svg"); /** 12x12 */ public static final Icon Db_no_suspend_method_breakpoint = IconLoader.getIcon("/debugger/db_no_suspend_method_breakpoint.svg"); /** 12x12 */ public static final Icon Db_obsolete = IconLoader.getIcon("/debugger/db_obsolete.svg"); /** 16x16 */ public static final Icon Db_primitive = IconLoader.getIcon("/debugger/db_primitive.svg"); /** 12x12 */ public static final Icon Db_set_breakpoint = IconLoader.getIcon("/debugger/db_set_breakpoint.svg"); /** 12x12 */ public static final Icon Db_verified_breakpoint = IconLoader.getIcon("/debugger/db_verified_breakpoint.svg"); /** 12x12 */ public static final Icon Db_verified_field_breakpoint = IconLoader.getIcon("/debugger/db_verified_field_breakpoint.svg"); /** 12x12 */ public static final Icon Db_verified_method_breakpoint = IconLoader.getIcon("/debugger/db_verified_method_breakpoint.svg"); /** 12x12 */ public static final Icon Db_verified_no_suspend_breakpoint = IconLoader.getIcon("/debugger/db_verified_no_suspend_breakpoint.svg"); /** 12x12 */ public static final Icon Db_verified_no_suspend_field_breakpoint = IconLoader.getIcon("/debugger/db_verified_no_suspend_field_breakpoint.svg"); /** 12x12 */ public static final Icon Db_verified_no_suspend_method_breakpoint = IconLoader.getIcon("/debugger/db_verified_no_suspend_method_breakpoint.svg"); /** 16x16 */ public static final Icon Db_watch = IconLoader.getIcon("/debugger/db_watch.svg"); /** 16x16 */ public static final Icon EvaluateExpression = IconLoader.getIcon("/debugger/evaluateExpression.svg"); /** 16x16 */ public static final Icon EvaluationResult = IconLoader.getIcon("/debugger/evaluationResult.svg"); /** 16x16 */ public static final Icon Frame = IconLoader.getIcon("/debugger/frame.svg"); /** 16x16 */ public static final Icon KillProcess = IconLoader.getIcon("/debugger/killProcess.svg"); /** 12x12 */ public static final Icon LambdaBreakpoint = IconLoader.getIcon("/debugger/LambdaBreakpoint.svg"); public final static class MemoryView { /** 16x16 */ public static final Icon Active = IconLoader.getIcon("/debugger/memoryView/active.svg"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Watch */ @SuppressWarnings("unused") @Deprecated public static final Icon ClassTracked = AllIcons.Debugger.Watch; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon ToolWindowDisabled = IconLoader.getIcon("/debugger/memoryView/toolWindowDisabled.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon ToolWindowEnabled = IconLoader.getIcon("/debugger/memoryView/toolWindowEnabled.png"); } /** 12x12 */ public static final Icon MultipleBreakpoints = IconLoader.getIcon("/debugger/MultipleBreakpoints.svg"); /** 16x16 */ public static final Icon MuteBreakpoints = IconLoader.getIcon("/debugger/muteBreakpoints.svg"); /** 16x16 */ public static final Icon Overhead = IconLoader.getIcon("/debugger/overhead.svg"); /** 16x16 */ public static final Icon PromptInput = IconLoader.getIcon("/debugger/promptInput.svg"); /** 16x16 */ public static final Icon PromptInputHistory = IconLoader.getIcon("/debugger/promptInputHistory.svg"); /** 7x9 */ public static final Icon Question_badge = IconLoader.getIcon("/debugger/question_badge.svg"); /** 16x16 */ public static final Icon RestoreLayout = IconLoader.getIcon("/debugger/restoreLayout.svg"); /** 16x16 */ public static final Icon Selfreference = IconLoader.getIcon("/debugger/selfreference.svg"); /** 16x16 */ public static final Icon ShowCurrentFrame = IconLoader.getIcon("/debugger/showCurrentFrame.svg"); /** 16x16 */ public static final Icon SmartStepInto = IconLoader.getIcon("/debugger/smartStepInto.svg"); /** 16x16 */ public static final Icon ThreadAtBreakpoint = IconLoader.getIcon("/debugger/threadAtBreakpoint.svg"); /** 16x16 */ public static final Icon ThreadCurrent = IconLoader.getIcon("/debugger/threadCurrent.svg"); /** 16x16 */ public static final Icon ThreadFrozen = IconLoader.getIcon("/debugger/threadFrozen.svg"); /** 16x16 */ public static final Icon ThreadGroup = IconLoader.getIcon("/debugger/threadGroup.svg"); /** 16x16 */ public static final Icon ThreadGroupCurrent = IconLoader.getIcon("/debugger/threadGroupCurrent.svg"); /** 16x16 */ public static final Icon ThreadRunning = IconLoader.getIcon("/debugger/threadRunning.svg"); /** 16x16 */ public static final Icon Threads = IconLoader.getIcon("/debugger/threads.svg"); public final static class ThreadStates { /** 16x16 */ public static final Icon Daemon_sign = IconLoader.getIcon("/debugger/threadStates/daemon_sign.svg"); /** 16x16 */ public static final Icon Idle = IconLoader.getIcon("/debugger/threadStates/idle.svg"); /** 16x16 */ public static final Icon Socket = IconLoader.getIcon("/debugger/threadStates/socket.svg"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.ProfileCPU */ @SuppressWarnings("unused") @Deprecated public static final Icon EdtBusy = AllIcons.Actions.ProfileCPU; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Lightning */ @SuppressWarnings("unused") @Deprecated public static final Icon Exception = AllIcons.Actions.Lightning; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Menu_saveall */ @SuppressWarnings("unused") @Deprecated public static final Icon IO = AllIcons.Actions.Menu_saveall; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.MuteBreakpoints */ @SuppressWarnings("unused") @Deprecated public static final Icon Locked = AllIcons.Debugger.MuteBreakpoints; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Pause */ @SuppressWarnings("unused") @Deprecated public static final Icon Paused = AllIcons.Actions.Pause; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Resume */ @SuppressWarnings("unused") @Deprecated public static final Icon Running = AllIcons.Actions.Resume; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Dump */ @SuppressWarnings("unused") @Deprecated public static final Icon Threaddump = AllIcons.Actions.Dump; } /** 16x16 */ public static final Icon ThreadSuspended = IconLoader.getIcon("/debugger/threadSuspended.svg"); /** 16x16 */ public static final Icon Value = IconLoader.getIcon("/debugger/value.svg"); /** 16x16 */ public static final Icon VariablesTab = IconLoader.getIcon("/debugger/variablesTab.svg"); /** 16x16 */ public static final Icon ViewBreakpoints = IconLoader.getIcon("/debugger/viewBreakpoints.svg"); /** 16x16 */ public static final Icon Watch = IconLoader.getIcon("/debugger/watch.svg"); /** 16x16 */ public static final Icon WatchLastReturnValue = IconLoader.getIcon("/debugger/watchLastReturnValue.svg"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon AutoVariablesMode = IconLoader.getIcon("/debugger/autoVariablesMode.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon BreakpointAlert = IconLoader.getIcon("/debugger/breakpointAlert.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.Filter */ @SuppressWarnings("unused") @Deprecated public static final Icon Class_filter = AllIcons.General.Filter; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Console */ @SuppressWarnings("unused") @Deprecated public static final Icon CommandLine = AllIcons.Debugger.Console; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Console */ @SuppressWarnings("unused") @Deprecated public static final Icon Console_log = AllIcons.Debugger.Console; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Db_exception_breakpoint */ @SuppressWarnings("unused") @Deprecated public static final Icon Db_dep_exception_breakpoint = AllIcons.Debugger.Db_exception_breakpoint; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Db_exception_breakpoint */ @SuppressWarnings("unused") @Deprecated public static final Icon Db_field_warning_breakpoint = AllIcons.Debugger.Db_exception_breakpoint; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Db_invalid_breakpoint */ @SuppressWarnings("unused") @Deprecated public static final Icon Db_invalid_field_breakpoint = AllIcons.Debugger.Db_invalid_breakpoint; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Db_invalid_breakpoint */ @SuppressWarnings("unused") @Deprecated public static final Icon Db_invalid_method_breakpoint = AllIcons.Debugger.Db_invalid_breakpoint; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Db_exception_breakpoint */ @SuppressWarnings("unused") @Deprecated public static final Icon Db_method_warning_breakpoint = AllIcons.Debugger.Db_exception_breakpoint; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Db_exception_breakpoint */ @SuppressWarnings("unused") @Deprecated public static final Icon Db_muted_dep_exception_breakpoint = AllIcons.Debugger.Db_exception_breakpoint; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Db_exception_breakpoint */ @SuppressWarnings("unused") @Deprecated public static final Icon Db_muted_disabled_breakpoint_process = AllIcons.Debugger.Db_exception_breakpoint; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Db_exception_breakpoint */ @SuppressWarnings("unused") @Deprecated public static final Icon Db_muted_disabled_exception_breakpoint = AllIcons.Debugger.Db_exception_breakpoint; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Db_exception_breakpoint */ @SuppressWarnings("unused") @Deprecated public static final Icon Db_muted_exception_breakpoint = AllIcons.Debugger.Db_exception_breakpoint; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Db_exception_breakpoint */ @SuppressWarnings("unused") @Deprecated public static final Icon Db_muted_field_warning_breakpoint = AllIcons.Debugger.Db_exception_breakpoint; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Db_invalid_breakpoint */ @SuppressWarnings("unused") @Deprecated public static final Icon Db_muted_invalid_breakpoint = AllIcons.Debugger.Db_invalid_breakpoint; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Db_invalid_breakpoint */ @SuppressWarnings("unused") @Deprecated public static final Icon Db_muted_invalid_field_breakpoint = AllIcons.Debugger.Db_invalid_breakpoint; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Db_invalid_breakpoint */ @SuppressWarnings("unused") @Deprecated public static final Icon Db_muted_invalid_method_breakpoint = AllIcons.Debugger.Db_invalid_breakpoint; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Db_exception_breakpoint */ @SuppressWarnings("unused") @Deprecated public static final Icon Db_muted_method_warning_breakpoint = AllIcons.Debugger.Db_exception_breakpoint; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Db_muted_breakpoint */ @SuppressWarnings("unused") @Deprecated public static final Icon Db_muted_temporary_breakpoint = AllIcons.Debugger.Db_muted_breakpoint; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Db_muted_breakpoint */ @SuppressWarnings("unused") @Deprecated public static final Icon Db_muted_verified_breakpoint = AllIcons.Debugger.Db_muted_breakpoint; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Db_muted_field_breakpoint */ @SuppressWarnings("unused") @Deprecated public static final Icon Db_muted_verified_field_breakpoint = AllIcons.Debugger.Db_muted_field_breakpoint; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Db_muted_field_breakpoint */ @SuppressWarnings("unused") @Deprecated public static final Icon Db_muted_verified_method_breakpoint = AllIcons.Debugger.Db_muted_field_breakpoint; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Db_exception_breakpoint */ @SuppressWarnings("unused") @Deprecated public static final Icon Db_muted_verified_warning_breakpoint = AllIcons.Debugger.Db_exception_breakpoint; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Db_set_breakpoint */ @SuppressWarnings("unused") @Deprecated public static final Icon Db_pending_breakpoint = AllIcons.Debugger.Db_set_breakpoint; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Db_set_breakpoint */ @SuppressWarnings("unused") @Deprecated public static final Icon Db_temporary_breakpoint = AllIcons.Debugger.Db_set_breakpoint; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Db_exception_breakpoint */ @SuppressWarnings("unused") @Deprecated public static final Icon Db_verified_warning_breakpoint = AllIcons.Debugger.Db_exception_breakpoint; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Disable_value_calculation = IconLoader.getIcon("/debugger/disable_value_calculation.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Explosion = IconLoader.getIcon("/debugger/explosion.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.Add */ @SuppressWarnings("unused") @Deprecated public static final Icon NewWatch = AllIcons.General.Add; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Frame */ @SuppressWarnings("unused") @Deprecated public static final Icon StackFrame = AllIcons.Debugger.Frame; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Console */ @SuppressWarnings("unused") @Deprecated public static final Icon ToolConsole = AllIcons.Debugger.Console; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Watch */ @SuppressWarnings("unused") @Deprecated public static final Icon Watches = AllIcons.Debugger.Watch; } public final static class Diff { /** 16x16 */ public static final Icon ApplyNotConflicts = IconLoader.getIcon("/diff/applyNotConflicts.svg"); /** 16x16 */ public static final Icon ApplyNotConflictsLeft = IconLoader.getIcon("/diff/applyNotConflictsLeft.svg"); /** 16x16 */ public static final Icon ApplyNotConflictsRight = IconLoader.getIcon("/diff/applyNotConflictsRight.svg"); /** 12x12 */ public static final Icon Arrow = IconLoader.getIcon("/diff/arrow.svg"); /** 12x12 */ public static final Icon ArrowLeftDown = IconLoader.getIcon("/diff/arrowLeftDown.svg"); /** 12x12 */ public static final Icon ArrowRight = IconLoader.getIcon("/diff/arrowRight.svg"); /** 12x12 */ public static final Icon ArrowRightDown = IconLoader.getIcon("/diff/arrowRightDown.svg"); /** 16x16 */ public static final Icon Compare3LeftMiddle = IconLoader.getIcon("/diff/compare3LeftMiddle.svg"); /** 16x16 */ public static final Icon Compare3LeftRight = IconLoader.getIcon("/diff/compare3LeftRight.svg"); /** 16x16 */ public static final Icon Compare3MiddleRight = IconLoader.getIcon("/diff/compare3MiddleRight.svg"); /** 16x16 */ public static final Icon Compare4LeftBottom = IconLoader.getIcon("/diff/compare4LeftBottom.svg"); /** 16x16 */ public static final Icon Compare4LeftMiddle = IconLoader.getIcon("/diff/compare4LeftMiddle.svg"); /** 16x16 */ public static final Icon Compare4LeftRight = IconLoader.getIcon("/diff/compare4LeftRight.svg"); /** 16x16 */ public static final Icon Compare4MiddleBottom = IconLoader.getIcon("/diff/compare4MiddleBottom.svg"); /** 16x16 */ public static final Icon Compare4MiddleRight = IconLoader.getIcon("/diff/compare4MiddleRight.svg"); /** 16x16 */ public static final Icon Compare4RightBottom = IconLoader.getIcon("/diff/compare4RightBottom.svg"); /** 12x12 */ public static final Icon GutterCheckBox = IconLoader.getIcon("/diff/gutterCheckBox.svg"); /** 12x12 */ public static final Icon GutterCheckBoxIndeterminate = IconLoader.getIcon("/diff/gutterCheckBoxIndeterminate.svg"); /** 12x12 */ public static final Icon GutterCheckBoxSelected = IconLoader.getIcon("/diff/gutterCheckBoxSelected.svg"); /** 16x16 */ public static final Icon Lock = IconLoader.getIcon("/diff/lock.svg"); /** 12x12 */ public static final Icon MagicResolve = IconLoader.getIcon("/diff/magicResolve.svg"); /** 16x16 */ public static final Icon MagicResolveToolbar = IconLoader.getIcon("/diff/magicResolveToolbar.svg"); /** 12x12 */ public static final Icon Remove = IconLoader.getIcon("/diff/remove.svg"); /** 12x12 */ public static final Icon Revert = IconLoader.getIcon("/diff/revert.svg"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Forward */ @SuppressWarnings("unused") @Deprecated public static final Icon CurrentLine = AllIcons.Actions.Forward; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Diff */ @SuppressWarnings("unused") @Deprecated public static final Icon Diff = AllIcons.Actions.Diff; } public final static class Duplicates { /** 16x16 */ public static final Icon SendToTheLeft = IconLoader.getIcon("/duplicates/sendToTheLeft.png"); /** 16x16 */ public static final Icon SendToTheLeftGrayed = IconLoader.getIcon("/duplicates/sendToTheLeftGrayed.png"); /** 16x16 */ public static final Icon SendToTheRight = IconLoader.getIcon("/duplicates/sendToTheRight.png"); /** 16x16 */ public static final Icon SendToTheRightGrayed = IconLoader.getIcon("/duplicates/sendToTheRightGrayed.png"); } public final static class FileTypes { /** 16x16 */ public static final Icon AddAny = IconLoader.getIcon("/fileTypes/addAny.svg"); /** 16x16 */ public static final Icon Any_type = IconLoader.getIcon("/fileTypes/any_type.svg"); /** 16x16 */ public static final Icon Archive = IconLoader.getIcon("/fileTypes/archive.svg"); /** 16x16 */ public static final Icon AS = IconLoader.getIcon("/fileTypes/as.svg"); /** 16x16 */ public static final Icon Aspectj = IconLoader.getIcon("/fileTypes/aspectj.svg"); /** 16x16 */ public static final Icon Config = IconLoader.getIcon("/fileTypes/config.svg"); /** 16x16 */ public static final Icon Css = IconLoader.getIcon("/fileTypes/css.svg"); /** 16x16 */ public static final Icon Custom = IconLoader.getIcon("/fileTypes/custom.svg"); /** 16x16 */ public static final Icon Diagram = IconLoader.getIcon("/fileTypes/diagram.svg"); /** 16x16 */ public static final Icon Dtd = IconLoader.getIcon("/fileTypes/dtd.svg"); /** 16x16 */ public static final Icon Htaccess = IconLoader.getIcon("/fileTypes/htaccess.svg"); /** 16x16 */ public static final Icon Html = IconLoader.getIcon("/fileTypes/html.svg"); /** 16x16 */ public static final Icon Idl = IconLoader.getIcon("/fileTypes/idl.svg"); /** 16x16 */ public static final Icon Java = IconLoader.getIcon("/fileTypes/java.svg"); /** 16x16 */ public static final Icon JavaClass = IconLoader.getIcon("/fileTypes/javaClass.svg"); /** 16x16 */ public static final Icon JavaOutsideSource = IconLoader.getIcon("/fileTypes/javaOutsideSource.svg"); /** 16x16 */ public static final Icon JavaScript = IconLoader.getIcon("/fileTypes/javaScript.svg"); /** 16x16 */ public static final Icon Json = IconLoader.getIcon("/fileTypes/json.svg"); /** 16x16 */ public static final Icon JsonSchema = IconLoader.getIcon("/fileTypes/jsonSchema.svg"); /** 16x16 */ public static final Icon Jsp = IconLoader.getIcon("/fileTypes/jsp.svg"); /** 16x16 */ public static final Icon Jspx = IconLoader.getIcon("/fileTypes/jspx.svg"); /** 16x16 */ public static final Icon Manifest = IconLoader.getIcon("/fileTypes/manifest.svg"); /** 16x16 */ public static final Icon Properties = IconLoader.getIcon("/fileTypes/properties.svg"); /** 16x16 */ public static final Icon Regexp = IconLoader.getIcon("/fileTypes/regexp.svg"); /** 16x16 */ public static final Icon Text = IconLoader.getIcon("/fileTypes/text.svg"); /** 16x16 */ public static final Icon UiForm = IconLoader.getIcon("/fileTypes/uiForm.svg"); /** 16x16 */ public static final Icon Unknown = IconLoader.getIcon("/fileTypes/unknown.svg"); /** 16x16 */ public static final Icon WsdlFile = IconLoader.getIcon("/fileTypes/wsdlFile.svg"); /** 16x16 */ public static final Icon Xhtml = IconLoader.getIcon("/fileTypes/xhtml.svg"); /** 16x16 */ public static final Icon Xml = IconLoader.getIcon("/fileTypes/xml.svg"); /** 16x16 */ public static final Icon XsdFile = IconLoader.getIcon("/fileTypes/xsdFile.svg"); /** @deprecated to be removed in IDEA 2020 - use JsfIcons.Facelets */ @SuppressWarnings("unused") @Deprecated public static final Icon Facelets = IconLoader.getIcon("/fileTypes/facelets.svg"); /** @deprecated to be removed in IDEA 2020 - use JsfIcons.FacesConfig */ @SuppressWarnings("unused") @Deprecated public static final Icon FacesConfig = IconLoader.getIcon("/fileTypes/facesConfig.svg"); /** @deprecated to be removed in IDEA 2020 - use JavaScriptPsiIcons.FileTypes.TypeScriptFile */ @SuppressWarnings("unused") @Deprecated public static final Icon TypeScript = IconLoader.getIcon("/fileTypes/typeScript.svg"); } public final static class General { /** 16x16 */ public static final Icon ActualZoom = IconLoader.getIcon("/general/actualZoom.svg"); /** 16x16 */ public static final Icon Add = IconLoader.getIcon("/general/add.svg"); /** 16x16 */ public static final Icon AddJdk = IconLoader.getIcon("/general/addJdk.svg"); /** 16x16 */ public static final Icon ArrowDown = IconLoader.getIcon("/general/arrowDown.svg"); /** 9x5 */ public static final Icon ArrowDownSmall = IconLoader.getIcon("/general/arrowDownSmall.svg"); /** 16x16 */ public static final Icon ArrowLeft = IconLoader.getIcon("/general/arrowLeft.svg"); /** 16x16 */ public static final Icon ArrowRight = IconLoader.getIcon("/general/arrowRight.svg"); /** 16x16 */ public static final Icon ArrowSplitCenterH = IconLoader.getIcon("/general/arrowSplitCenterH.svg"); /** 16x16 */ public static final Icon ArrowSplitCenterV = IconLoader.getIcon("/general/arrowSplitCenterV.svg"); /** 16x16 */ public static final Icon ArrowUp = IconLoader.getIcon("/general/arrowUp.svg"); /** 16x16 */ public static final Icon AutoscrollFromSource = IconLoader.getIcon("/general/autoscrollFromSource.svg"); /** 16x16 */ public static final Icon AutoscrollToSource = IconLoader.getIcon("/general/autoscrollToSource.svg"); /** 16x16 */ public static final Icon Balloon = IconLoader.getIcon("/general/balloon.svg"); /** 16x16 */ public static final Icon BalloonError = IconLoader.getIcon("/general/balloonError.svg"); /** 16x16 */ public static final Icon BalloonInformation = IconLoader.getIcon("/general/balloonInformation.svg"); /** 16x16 */ public static final Icon BalloonWarning = IconLoader.getIcon("/general/balloonWarning.svg"); /** 12x12 */ public static final Icon BalloonWarning12 = IconLoader.getIcon("/general/balloonWarning12.svg"); /** 8x4 */ public static final Icon ButtonDropTriangle = IconLoader.getIcon("/general/buttonDropTriangle.svg"); /** 12x12 */ public static final Icon CollapseComponent = IconLoader.getIcon("/general/collapseComponent.svg"); /** 12x12 */ public static final Icon CollapseComponentHover = IconLoader.getIcon("/general/collapseComponentHover.svg"); /** 16x16 */ public static final Icon ContextHelp = IconLoader.getIcon("/general/contextHelp.svg"); /** 16x16 */ public static final Icon CopyHovered = IconLoader.getIcon("/general/copyHovered.svg"); /** 2x19 */ public static final Icon Divider = IconLoader.getIcon("/general/divider.svg"); /** 16x16 */ public static final Icon Dropdown = IconLoader.getIcon("/general/dropdown.svg"); /** 13x13 */ public static final Icon DropdownGutter = IconLoader.getIcon("/general/dropdownGutter.svg"); /** 9x9 */ public static final Icon Ellipsis = IconLoader.getIcon("/general/ellipsis.svg"); /** 16x16 */ public static final Icon Error = IconLoader.getIcon("/general/error.svg"); /** 32x32 */ public static final Icon ErrorDialog = IconLoader.getIcon("/general/errorDialog.svg"); /** 16x16 */ public static final Icon ExclMark = IconLoader.getIcon("/general/exclMark.svg"); /** 12x12 */ public static final Icon ExpandComponent = IconLoader.getIcon("/general/expandComponent.svg"); /** 12x12 */ public static final Icon ExpandComponentHover = IconLoader.getIcon("/general/expandComponentHover.svg"); /** 16x16 */ public static final Icon ExternalTools = IconLoader.getIcon("/general/externalTools.svg"); /** 16x16 */ public static final Icon Filter = IconLoader.getIcon("/general/filter.svg"); /** 16x16 */ public static final Icon FitContent = IconLoader.getIcon("/general/fitContent.svg"); /** 16x16 */ public static final Icon GearPlain = IconLoader.getIcon("/general/gearPlain.svg"); /** 16x16 */ public static final Icon HideToolWindow = IconLoader.getIcon("/general/hideToolWindow.svg"); /** 16x16 */ public static final Icon ImplementingMethod = IconLoader.getIcon("/general/implementingMethod.svg"); /** 16x16 */ public static final Icon Information = IconLoader.getIcon("/general/information.svg"); /** 32x32 */ public static final Icon InformationDialog = IconLoader.getIcon("/general/informationDialog.svg"); /** 16x16 */ public static final Icon InheritedMethod = IconLoader.getIcon("/general/inheritedMethod.svg"); /** 16x16 */ public static final Icon Inline_edit = IconLoader.getIcon("/general/inline_edit.svg"); /** 16x16 */ public static final Icon Inline_edit_hovered = IconLoader.getIcon("/general/inline_edit_hovered.svg"); /** 16x16 */ public static final Icon InlineAdd = IconLoader.getIcon("/general/inlineAdd.svg"); /** 16x16 */ public static final Icon InlineAddHover = IconLoader.getIcon("/general/inlineAddHover.svg"); /** 16x16 */ public static final Icon InlineVariables = IconLoader.getIcon("/general/inlineVariables.svg"); /** 16x16 */ public static final Icon InlineVariablesHover = IconLoader.getIcon("/general/inlineVariablesHover.svg"); /** 14x14 */ public static final Icon InspectionsError = IconLoader.getIcon("/general/inspectionsError.svg"); /** 14x14 */ public static final Icon InspectionsEye = IconLoader.getIcon("/general/inspectionsEye.svg"); /** 14x14 */ public static final Icon InspectionsOK = IconLoader.getIcon("/general/inspectionsOK.svg"); /** 14x14 */ public static final Icon InspectionsPause = IconLoader.getIcon("/general/inspectionsPause.svg"); /** 14x14 */ public static final Icon InspectionsTrafficOff = IconLoader.getIcon("/general/inspectionsTrafficOff.svg"); /** 14x14 */ public static final Icon InspectionsTypos = IconLoader.getIcon("/general/inspectionsTypos.svg"); /** 16x16 */ public static final Icon Layout = IconLoader.getIcon("/general/layout.svg"); /** 16x16 */ public static final Icon LayoutEditorOnly = IconLoader.getIcon("/general/layoutEditorOnly.svg"); /** 16x16 */ public static final Icon LayoutEditorPreview = IconLoader.getIcon("/general/layoutEditorPreview.svg"); /** 16x16 */ public static final Icon LayoutPreviewOnly = IconLoader.getIcon("/general/layoutPreviewOnly.svg"); /** 14x14 */ public static final Icon LinkDropTriangle = IconLoader.getIcon("/general/linkDropTriangle.svg"); /** 16x16 */ public static final Icon Locate = IconLoader.getIcon("/general/locate.svg"); /** 13x13 */ public static final Icon Modified = IconLoader.getIcon("/general/modified.svg"); /** 13x13 */ public static final Icon ModifiedSelected = IconLoader.getIcon("/general/modifiedSelected.svg"); /** 16x16 */ public static final Icon MoreTabs = IconLoader.getIcon("/general/moreTabs.svg"); /** 16x16 */ public static final Icon Mouse = IconLoader.getIcon("/general/mouse.svg"); /** 16x16 */ public static final Icon Note = IconLoader.getIcon("/general/note.svg"); /** 24x24 */ public static final Icon NotificationError = IconLoader.getIcon("/general/notificationError.svg"); /** 24x24 */ public static final Icon NotificationInfo = IconLoader.getIcon("/general/notificationInfo.svg"); /** 24x24 */ public static final Icon NotificationWarning = IconLoader.getIcon("/general/notificationWarning.svg"); /** 16x16 */ public static final Icon OpenDisk = IconLoader.getIcon("/general/openDisk.svg"); /** 16x16 */ public static final Icon OpenDiskHover = IconLoader.getIcon("/general/openDiskHover.svg"); /** 16x16 */ public static final Icon OverridenMethod = IconLoader.getIcon("/general/overridenMethod.svg"); /** 16x16 */ public static final Icon OverridingMethod = IconLoader.getIcon("/general/overridingMethod.svg"); /** 16x16 */ public static final Icon Pin_tab = IconLoader.getIcon("/general/pin_tab.svg"); /** 16x16 */ public static final Icon Print = IconLoader.getIcon("/general/print.svg"); /** 9x9 */ public static final Icon ProjectConfigurable = IconLoader.getIcon("/general/projectConfigurable.svg"); /** 16x16 */ public static final Icon ProjectStructure = IconLoader.getIcon("/general/projectStructure.svg"); /** 16x16 */ public static final Icon ProjectTab = IconLoader.getIcon("/general/projectTab.svg"); /** 32x32 */ public static final Icon QuestionDialog = IconLoader.getIcon("/general/questionDialog.svg"); /** 16x16 */ public static final Icon Remove = IconLoader.getIcon("/general/remove.svg"); /** 16x16 */ public static final Icon Reset = IconLoader.getIcon("/general/reset.svg"); /** 16x16 */ public static final Icon RunWithCoverage = IconLoader.getIcon("/general/runWithCoverage.svg"); /** 16x16 */ public static final Icon SeparatorH = IconLoader.getIcon("/general/separatorH.svg"); /** 16x16 */ public static final Icon Settings = IconLoader.getIcon("/general/settings.svg"); /** 16x16 */ public static final Icon Show_to_implement = IconLoader.getIcon("/general/show_to_implement.svg"); /** 16x16 */ public static final Icon ShowWarning = IconLoader.getIcon("/general/showWarning.svg"); /** 16x16 */ public static final Icon TbHidden = IconLoader.getIcon("/general/tbHidden.svg"); /** 16x16 */ public static final Icon TbShown = IconLoader.getIcon("/general/tbShown.svg"); /** 32x32 */ public static final Icon Tip = IconLoader.getIcon("/general/tip.svg"); /** 16x16 */ public static final Icon TodoDefault = IconLoader.getIcon("/general/todoDefault.svg"); /** 16x16 */ public static final Icon TodoImportant = IconLoader.getIcon("/general/todoImportant.svg"); /** 16x16 */ public static final Icon TodoQuestion = IconLoader.getIcon("/general/todoQuestion.svg"); /** 16x16 */ public static final Icon User = IconLoader.getIcon("/general/user.svg"); /** 16x16 */ public static final Icon Warning = IconLoader.getIcon("/general/warning.svg"); /** 16x16 */ public static final Icon WarningDecorator = IconLoader.getIcon("/general/warningDecorator.svg"); /** 32x32 */ public static final Icon WarningDialog = IconLoader.getIcon("/general/warningDialog.svg"); /** 16x16 */ public static final Icon Web = IconLoader.getIcon("/general/web.svg"); /** 16x16 */ public static final Icon ZoomIn = IconLoader.getIcon("/general/zoomIn.svg"); /** 16x16 */ public static final Icon ZoomOut = IconLoader.getIcon("/general/zoomOut.svg"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.Add */ @SuppressWarnings("unused") @Deprecated public static final Icon AddFavoritesList = AllIcons.General.Add; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowDown */ @SuppressWarnings("unused") @Deprecated public static final Icon ArrowDown_white = AllIcons.General.ArrowDown; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.Pin_tab */ @SuppressWarnings("unused") @Deprecated public static final Icon AutohideOff = AllIcons.General.Pin_tab; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.Pin_tab */ @SuppressWarnings("unused") @Deprecated public static final Icon AutohideOffInactive = AllIcons.General.Pin_tab; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.Pin_tab */ @SuppressWarnings("unused") @Deprecated public static final Icon AutohideOffPressed = AllIcons.General.Pin_tab; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Ide.Notification.Close */ @SuppressWarnings("unused") @Deprecated public static final Icon BalloonClose = AllIcons.Ide.Notification.Close; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Bullet = IconLoader.getIcon("/general/bullet.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Collapseall */ @SuppressWarnings("unused") @Deprecated public static final Icon CollapseAll = AllIcons.Actions.Collapseall; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Collapseall */ @SuppressWarnings("unused") @Deprecated public static final Icon CollapseAllHover = AllIcons.Actions.Collapseall; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowDown */ @SuppressWarnings("unused") @Deprecated public static final Icon Combo = AllIcons.General.ArrowDown; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowDown */ @SuppressWarnings("unused") @Deprecated public static final Icon Combo2 = AllIcons.General.ArrowDown; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowDown */ @SuppressWarnings("unused") @Deprecated public static final Icon Combo3 = AllIcons.General.ArrowDown; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowDown */ @SuppressWarnings("unused") @Deprecated public static final Icon ComboArrow = AllIcons.General.ArrowDown; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowDownSmall */ @SuppressWarnings("unused") @Deprecated public static final Icon ComboArrowDown = AllIcons.General.ArrowDownSmall; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowLeft */ @SuppressWarnings("unused") @Deprecated public static final Icon ComboArrowLeft = AllIcons.General.ArrowLeft; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowLeft */ @SuppressWarnings("unused") @Deprecated public static final Icon ComboArrowLeftPassive = AllIcons.General.ArrowLeft; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowRight */ @SuppressWarnings("unused") @Deprecated public static final Icon ComboArrowRight = AllIcons.General.ArrowRight; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowRight */ @SuppressWarnings("unused") @Deprecated public static final Icon ComboArrowRightPassive = AllIcons.General.ArrowRight; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowDown */ @SuppressWarnings("unused") @Deprecated public static final Icon ComboBoxButtonArrow = AllIcons.General.ArrowDown; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon ComboUpPassive = IconLoader.getIcon("/general/comboUpPassive.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon ConfigurableDefault = IconLoader.getIcon("/general/configurableDefault.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.Settings */ @SuppressWarnings("unused") @Deprecated public static final Icon Configure = AllIcons.General.Settings; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Welcome.CreateNewProject */ @SuppressWarnings("unused") @Deprecated public static final Icon CreateNewProject = AllIcons.Welcome.CreateNewProject; /** @deprecated to be removed in IDEA 2020 - use AllIcons.ToolbarDecorator.Import */ @SuppressWarnings("unused") @Deprecated public static final Icon CreateNewProjectfromExistingFiles = AllIcons.ToolbarDecorator.Import; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.StartDebugger */ @SuppressWarnings("unused") @Deprecated public static final Icon Debug = AllIcons.Actions.StartDebugger; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon DefaultKeymap = IconLoader.getIcon("/general/defaultKeymap.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon DownloadPlugin = IconLoader.getIcon("/general/downloadPlugin.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.Settings */ @SuppressWarnings("unused") @Deprecated public static final Icon EditColors = AllIcons.General.Settings; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Edit */ @SuppressWarnings("unused") @Deprecated public static final Icon EditItemInSection = AllIcons.Actions.Edit; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon ErrorsInProgress = IconLoader.getIcon("/general/errorsInProgress.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Expandall */ @SuppressWarnings("unused") @Deprecated public static final Icon ExpandAll = AllIcons.Actions.Expandall; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Expandall */ @SuppressWarnings("unused") @Deprecated public static final Icon ExpandAllHover = AllIcons.Actions.Expandall; /** @deprecated to be removed in IDEA 2020 - use AllIcons.ToolbarDecorator.Export */ @SuppressWarnings("unused") @Deprecated public static final Icon ExportSettings = AllIcons.ToolbarDecorator.Export; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ExternalTools */ @SuppressWarnings("unused") @Deprecated public static final Icon ExternalToolsSmall = AllIcons.General.ExternalTools; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.MoveTo2 */ @SuppressWarnings("unused") @Deprecated public static final Icon Floating = AllIcons.Actions.MoveTo2; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.GearPlain */ @SuppressWarnings("unused") @Deprecated public static final Icon Gear = AllIcons.General.GearPlain; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon GearHover = IconLoader.getIcon("/general/gearHover.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Welcome.FromVCS */ @SuppressWarnings("unused") @Deprecated public static final Icon GetProjectfromVCS = AllIcons.Welcome.FromVCS; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ContextHelp */ @SuppressWarnings("unused") @Deprecated public static final Icon Help = AllIcons.General.ContextHelp; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ContextHelp */ @SuppressWarnings("unused") @Deprecated public static final Icon Help_small = AllIcons.General.ContextHelp; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.HideToolWindow */ @SuppressWarnings("unused") @Deprecated public static final Icon HideDown = AllIcons.General.HideToolWindow; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.HideToolWindow */ @SuppressWarnings("unused") @Deprecated public static final Icon HideDownHover = AllIcons.General.HideToolWindow; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.HideToolWindow */ @SuppressWarnings("unused") @Deprecated public static final Icon HideDownPart = AllIcons.General.HideToolWindow; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.HideToolWindow */ @SuppressWarnings("unused") @Deprecated public static final Icon HideDownPartHover = AllIcons.General.HideToolWindow; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.HideToolWindow */ @SuppressWarnings("unused") @Deprecated public static final Icon HideLeft = AllIcons.General.HideToolWindow; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.HideToolWindow */ @SuppressWarnings("unused") @Deprecated public static final Icon HideLeftHover = AllIcons.General.HideToolWindow; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.HideToolWindow */ @SuppressWarnings("unused") @Deprecated public static final Icon HideLeftPart = AllIcons.General.HideToolWindow; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.HideToolWindow */ @SuppressWarnings("unused") @Deprecated public static final Icon HideLeftPartHover = AllIcons.General.HideToolWindow; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.HideToolWindow */ @SuppressWarnings("unused") @Deprecated public static final Icon HideRight = AllIcons.General.HideToolWindow; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.HideToolWindow */ @SuppressWarnings("unused") @Deprecated public static final Icon HideRightHover = AllIcons.General.HideToolWindow; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.HideToolWindow */ @SuppressWarnings("unused") @Deprecated public static final Icon HideRightPart = AllIcons.General.HideToolWindow; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.HideToolWindow */ @SuppressWarnings("unused") @Deprecated public static final Icon HideRightPartHover = AllIcons.General.HideToolWindow; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.HideToolWindow */ @SuppressWarnings("unused") @Deprecated public static final Icon HideToolWindowInactive = AllIcons.General.HideToolWindow; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon HideWarnings = IconLoader.getIcon("/general/hideWarnings.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon IjLogo = IconLoader.getIcon("/general/ijLogo.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.ToolbarDecorator.Import */ @SuppressWarnings("unused") @Deprecated public static final Icon ImportProject = AllIcons.ToolbarDecorator.Import; /** @deprecated to be removed in IDEA 2020 - use AllIcons.ToolbarDecorator.Import */ @SuppressWarnings("unused") @Deprecated public static final Icon ImportSettings = AllIcons.ToolbarDecorator.Import; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Ide.HectorOff */ @SuppressWarnings("unused") @Deprecated public static final Icon InspectionsOff = AllIcons.Ide.HectorOff; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Jdk = IconLoader.getIcon("/general/jdk.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon KeyboardShortcut = IconLoader.getIcon("/general/keyboardShortcut.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Keymap = IconLoader.getIcon("/general/keymap.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.Locate */ @SuppressWarnings("unused") @Deprecated public static final Icon LocateHover = AllIcons.General.Locate; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon MacCorner = IconLoader.getIcon("/general/macCorner.png"); /** @deprecated to be removed in IDEA 2020 - use EmptyIcon.ICON_16 */ @SuppressWarnings("unused") @Deprecated public static final Icon Mdot_empty = IconLoader.getIcon("/general/mdot-empty.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Mdot_white = IconLoader.getIcon("/general/mdot-white.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Mdot = IconLoader.getIcon("/general/mdot.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Vcs.History */ @SuppressWarnings("unused") @Deprecated public static final Icon MessageHistory = AllIcons.Vcs.History; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon MouseShortcut = IconLoader.getIcon("/general/mouseShortcut.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Menu_open */ @SuppressWarnings("unused") @Deprecated public static final Icon OpenProject = AllIcons.Actions.Menu_open; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Nodes.CopyOfFolder */ @SuppressWarnings("unused") @Deprecated public static final Icon PackagesTab = AllIcons.Nodes.CopyOfFolder; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon PasswordLock = IconLoader.getIcon("/general/passwordLock.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon PathVariables = IconLoader.getIcon("/general/pathVariables.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon PluginManager = IconLoader.getIcon("/general/pluginManager.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Progress = IconLoader.getIcon("/general/progress.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ProjectConfigurable */ @SuppressWarnings("unused") @Deprecated public static final Icon ProjectConfigurableBanner = AllIcons.General.ProjectConfigurable; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ProjectConfigurable */ @SuppressWarnings("unused") @Deprecated public static final Icon ProjectConfigurableSelected = AllIcons.General.ProjectConfigurable; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.GearPlain */ @SuppressWarnings("unused") @Deprecated public static final Icon ProjectSettings = AllIcons.General.GearPlain; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Help */ @SuppressWarnings("unused") @Deprecated public static final Icon ReadHelp = AllIcons.Actions.Help; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.ShowAsTree */ @SuppressWarnings("unused") @Deprecated public static final Icon Recursive = AllIcons.Actions.ShowAsTree; /** @deprecated to be removed in IDEA 2020 - use AllIcons.RunConfigurations.TestState.Run */ @SuppressWarnings("unused") @Deprecated public static final Icon Run = AllIcons.RunConfigurations.TestState.Run; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.InspectionsTrafficOff */ @SuppressWarnings("unused") @Deprecated public static final Icon SafeMode = AllIcons.General.InspectionsTrafficOff; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon SearchEverywhereGear = IconLoader.getIcon("/general/searchEverywhereGear.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.GearPlain */ @SuppressWarnings("unused") @Deprecated public static final Icon SecondaryGroup = AllIcons.General.GearPlain; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Show_to_override = IconLoader.getIcon("/general/show_to_override.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.ShowAsTree */ @SuppressWarnings("unused") @Deprecated public static final Icon SmallConfigurableVcs = AllIcons.Actions.ShowAsTree; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowSplitCenterH */ @SuppressWarnings("unused") @Deprecated public static final Icon SplitCenterH = AllIcons.General.ArrowSplitCenterH; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowSplitCenterV */ @SuppressWarnings("unused") @Deprecated public static final Icon SplitCenterV = AllIcons.General.ArrowSplitCenterV; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowDown */ @SuppressWarnings("unused") @Deprecated public static final Icon SplitDown = AllIcons.General.ArrowDown; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon SplitGlueH = IconLoader.getIcon("/general/splitGlueH.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon SplitGlueV = IconLoader.getIcon("/general/splitGlueV.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowLeft */ @SuppressWarnings("unused") @Deprecated public static final Icon SplitLeft = AllIcons.General.ArrowLeft; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowRight */ @SuppressWarnings("unused") @Deprecated public static final Icon SplitRight = AllIcons.General.ArrowRight; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowUp */ @SuppressWarnings("unused") @Deprecated public static final Icon SplitUp = AllIcons.General.ArrowUp; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Tab_white_center = IconLoader.getIcon("/general/tab-white-center.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Tab_white_left = IconLoader.getIcon("/general/tab-white-left.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Tab_white_right = IconLoader.getIcon("/general/tab-white-right.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Tab_grey_bckgrnd = IconLoader.getIcon("/general/tab_grey_bckgrnd.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Tab_grey_left = IconLoader.getIcon("/general/tab_grey_left.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Tab_grey_left_inner = IconLoader.getIcon("/general/tab_grey_left_inner.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Tab_grey_right = IconLoader.getIcon("/general/tab_grey_right.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Tab_grey_right_inner = IconLoader.getIcon("/general/tab_grey_right_inner.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.Settings */ @SuppressWarnings("unused") @Deprecated public static final Icon TemplateProjectSettings = AllIcons.General.Settings; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ProjectStructure */ @SuppressWarnings("unused") @Deprecated public static final Icon TemplateProjectStructure = AllIcons.General.ProjectStructure; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon UninstallPlugin = IconLoader.getIcon("/general/uninstallPlugin.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon WebSettings = IconLoader.getIcon("/general/webSettings.png"); } public final static class Graph { /** 16x16 */ public static final Icon ActualZoom = IconLoader.getIcon("/graph/actualZoom.svg"); /** 16x16 */ public static final Icon FitContent = IconLoader.getIcon("/graph/fitContent.svg"); /** 16x16 */ public static final Icon Grid = IconLoader.getIcon("/graph/grid.svg"); /** 16x16 */ public static final Icon Layout = IconLoader.getIcon("/graph/layout.svg"); /** 16x16 */ public static final Icon NodeSelectionMode = IconLoader.getIcon("/graph/nodeSelectionMode.svg"); /** 16x16 */ public static final Icon SnapToGrid = IconLoader.getIcon("/graph/snapToGrid.svg"); /** 16x16 */ public static final Icon ZoomIn = IconLoader.getIcon("/graph/zoomIn.svg"); /** 16x16 */ public static final Icon ZoomOut = IconLoader.getIcon("/graph/zoomOut.svg"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.ToolbarDecorator.Export */ @SuppressWarnings("unused") @Deprecated public static final Icon Export = AllIcons.ToolbarDecorator.Export; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.Print */ @SuppressWarnings("unused") @Deprecated public static final Icon Print = AllIcons.General.Print; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Preview */ @SuppressWarnings("unused") @Deprecated public static final Icon PrintPreview = AllIcons.Actions.Preview; } public final static class Gutter { /** 12x12 */ public static final Icon Colors = IconLoader.getIcon("/gutter/colors.svg"); /** 12x12 */ public static final Icon ExtAnnotation = IconLoader.getIcon("/gutter/extAnnotation.svg"); /** 12x12 */ public static final Icon ImplementedMethod = IconLoader.getIcon("/gutter/implementedMethod.svg"); /** 12x12 */ public static final Icon ImplementingFunctionalInterface = IconLoader.getIcon("/gutter/implementingFunctionalInterface.svg"); /** 12x12 */ public static final Icon ImplementingMethod = IconLoader.getIcon("/gutter/implementingMethod.svg"); /** 12x12 */ public static final Icon Java9Service = IconLoader.getIcon("/gutter/java9Service.svg"); /** 12x12 */ public static final Icon OverridenMethod = IconLoader.getIcon("/gutter/overridenMethod.svg"); /** 12x12 */ public static final Icon OverridingMethod = IconLoader.getIcon("/gutter/overridingMethod.svg"); /** 12x12 */ public static final Icon ReadAccess = IconLoader.getIcon("/gutter/readAccess.svg"); /** 12x12 */ public static final Icon RecursiveMethod = IconLoader.getIcon("/gutter/recursiveMethod.svg"); /** 12x12 */ public static final Icon SiblingInheritedMethod = IconLoader.getIcon("/gutter/siblingInheritedMethod.svg"); /** 8x8 */ public static final Icon Unique = IconLoader.getIcon("/gutter/unique.svg"); /** 12x12 */ public static final Icon WriteAccess = IconLoader.getIcon("/gutter/writeAccess.svg"); } public final static class Hierarchy { /** 16x16 */ public static final Icon Class = IconLoader.getIcon("/hierarchy/class.svg"); /** 8x8 */ public static final Icon MethodDefined = IconLoader.getIcon("/hierarchy/methodDefined.svg"); /** 8x8 */ public static final Icon MethodNotDefined = IconLoader.getIcon("/hierarchy/methodNotDefined.svg"); /** 8x8 */ public static final Icon ShouldDefineMethod = IconLoader.getIcon("/hierarchy/shouldDefineMethod.svg"); /** 16x16 */ public static final Icon Subtypes = IconLoader.getIcon("/hierarchy/subtypes.svg"); /** 16x16 */ public static final Icon Supertypes = IconLoader.getIcon("/hierarchy/supertypes.svg"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.Modified */ @SuppressWarnings("unused") @Deprecated public static final Icon Base = AllIcons.General.Modified; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Hierarchy.Subtypes */ @SuppressWarnings("unused") @Deprecated public static final Icon Callee = AllIcons.Hierarchy.Subtypes; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Hierarchy.Supertypes */ @SuppressWarnings("unused") @Deprecated public static final Icon Caller = AllIcons.Hierarchy.Supertypes; } /** 32x32 */ public static final Icon Icon = IconLoader.getIcon("/icon.png"); /** 128x128 */ public static final Icon Icon_128 = IconLoader.getIcon("/icon_128.png"); /** 32x32 */ public static final Icon Icon_CE = IconLoader.getIcon("/icon_CE.png"); /** 128x128 */ public static final Icon Icon_CE_128 = IconLoader.getIcon("/icon_CE_128.png"); /** 256x256 */ public static final Icon Icon_CE_256 = IconLoader.getIcon("/icon_CE_256.png"); /** 512x512 */ public static final Icon Icon_CE_512 = IconLoader.getIcon("/icon_CE_512.png"); /** 64x64 */ public static final Icon Icon_CE_64 = IconLoader.getIcon("/icon_CE_64.png"); /** 16x16 */ public static final Icon Icon_CEsmall = IconLoader.getIcon("/icon_CEsmall.png"); /** 16x16 */ public static final Icon Icon_small = IconLoader.getIcon("/icon_small.png"); public final static class Icons { public final static class Ide { /** 12x12 */ public static final Icon NextStep = IconLoader.getIcon("/icons/ide/nextStep.svg"); /** 12x12 */ public static final Icon NextStepInverted = IconLoader.getIcon("/icons/ide/nextStepInverted.svg"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Icons.Ide.NextStep */ @SuppressWarnings("unused") @Deprecated public static final Icon NextStepGrayed = AllIcons.Icons.Ide.NextStep; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon SpeedSearchPrompt = IconLoader.getIcon("/icons/ide/speedSearchPrompt.png"); } } public final static class Ide { public final static class Dnd { /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowUp */ @SuppressWarnings("unused") @Deprecated public static final Icon Bottom = AllIcons.General.ArrowUp; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowRight */ @SuppressWarnings("unused") @Deprecated public static final Icon Left = AllIcons.General.ArrowRight; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowLeft */ @SuppressWarnings("unused") @Deprecated public static final Icon Right = AllIcons.General.ArrowLeft; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowDown */ @SuppressWarnings("unused") @Deprecated public static final Icon Top = AllIcons.General.ArrowDown; } /** 6x6 */ public static final Icon ErrorPoint = IconLoader.getIcon("/ide/errorPoint.svg"); /** 14x14 */ public static final Icon External_link_arrow = IconLoader.getIcon("/ide/external_link_arrow.svg"); /** 16x16 */ public static final Icon FatalError_read = IconLoader.getIcon("/ide/fatalError-read.svg"); /** 16x16 */ public static final Icon FatalError = IconLoader.getIcon("/ide/fatalError.svg"); /** 16x16 */ public static final Icon HectorOff = IconLoader.getIcon("/ide/hectorOff.svg"); /** 16x16 */ public static final Icon HectorOn = IconLoader.getIcon("/ide/hectorOn.svg"); /** 16x16 */ public static final Icon HectorSyntax = IconLoader.getIcon("/ide/hectorSyntax.svg"); /** 16x16 */ public static final Icon IncomingChangesOn = IconLoader.getIcon("/ide/incomingChangesOn.svg"); /** 12x12 */ public static final Icon Link = IconLoader.getIcon("/ide/link.svg"); /** 16x16 */ public static final Icon LocalScope = IconLoader.getIcon("/ide/localScope.svg"); /** 12x12 */ public static final Icon LookupAlphanumeric = IconLoader.getIcon("/ide/lookupAlphanumeric.svg"); /** 12x12 */ public static final Icon LookupRelevance = IconLoader.getIcon("/ide/lookupRelevance.svg"); public final static class Macro { /** 16x16 */ public static final Icon Recording_1 = IconLoader.getIcon("/ide/macro/recording_1.svg"); /** 16x16 */ public static final Icon Recording_2 = IconLoader.getIcon("/ide/macro/recording_2.svg"); /** 16x16 */ public static final Icon Recording_3 = IconLoader.getIcon("/ide/macro/recording_3.svg"); /** 16x16 */ public static final Icon Recording_4 = IconLoader.getIcon("/ide/macro/recording_4.svg"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Suspend */ @SuppressWarnings("unused") @Deprecated public static final Icon Recording_stop = AllIcons.Actions.Suspend; } /** 5x15 */ public static final Icon NavBarSeparator = IconLoader.getIcon("/ide/NavBarSeparator.svg"); public final static class Notification { /** 16x16 */ public static final Icon Close = IconLoader.getIcon("/ide/notification/close.svg"); /** 16x16 */ public static final Icon CloseHover = IconLoader.getIcon("/ide/notification/closeHover.svg"); /** 16x16 */ public static final Icon Collapse = IconLoader.getIcon("/ide/notification/collapse.svg"); /** 16x16 */ public static final Icon CollapseHover = IconLoader.getIcon("/ide/notification/collapseHover.svg"); /** 16x16 */ public static final Icon DropTriangle = IconLoader.getIcon("/ide/notification/dropTriangle.svg"); /** 13x13 */ public static final Icon ErrorEvents = IconLoader.getIcon("/ide/notification/errorEvents.svg"); /** 16x16 */ public static final Icon Expand = IconLoader.getIcon("/ide/notification/expand.svg"); /** 16x16 */ public static final Icon ExpandHover = IconLoader.getIcon("/ide/notification/expandHover.svg"); /** 16x16 */ public static final Icon Gear = IconLoader.getIcon("/ide/notification/gear.svg"); /** 16x16 */ public static final Icon GearHover = IconLoader.getIcon("/ide/notification/gearHover.svg"); /** 13x13 */ public static final Icon InfoEvents = IconLoader.getIcon("/ide/notification/infoEvents.svg"); /** 13x13 */ public static final Icon NoEvents = IconLoader.getIcon("/ide/notification/noEvents.svg"); /** 13x13 */ public static final Icon WarningEvents = IconLoader.getIcon("/ide/notification/warningEvents.svg"); } /** 16x16 */ public static final Icon OutgoingChangesOn = IconLoader.getIcon("/ide/outgoingChangesOn.svg"); /** 16x16 */ public static final Icon Pipette = IconLoader.getIcon("/ide/pipette.svg"); /** 16x16 */ public static final Icon Pipette_rollover = IconLoader.getIcon("/ide/pipette_rollover.svg"); /** 11x11 */ public static final Icon Rating = IconLoader.getIcon("/ide/rating.svg"); /** 11x11 */ public static final Icon Rating1 = IconLoader.getIcon("/ide/rating1.svg"); /** 11x11 */ public static final Icon Rating2 = IconLoader.getIcon("/ide/rating2.svg"); /** 11x11 */ public static final Icon Rating3 = IconLoader.getIcon("/ide/rating3.svg"); /** 11x11 */ public static final Icon Rating4 = IconLoader.getIcon("/ide/rating4.svg"); /** 16x16 */ public static final Icon Readonly = IconLoader.getIcon("/ide/readonly.svg"); /** 16x16 */ public static final Icon Readwrite = IconLoader.getIcon("/ide/readwrite.svg"); public final static class Shadow { /** 4x14 */ public static final Icon Bottom = IconLoader.getIcon("/ide/shadow/bottom.svg"); /** 18x22 */ public static final Icon BottomLeft = IconLoader.getIcon("/ide/shadow/bottomLeft.svg"); /** 18x22 */ public static final Icon BottomRight = IconLoader.getIcon("/ide/shadow/bottomRight.svg"); /** 11x4 */ public static final Icon Left = IconLoader.getIcon("/ide/shadow/left.svg"); /** 11x4 */ public static final Icon Right = IconLoader.getIcon("/ide/shadow/right.svg"); /** 4x7 */ public static final Icon Top = IconLoader.getIcon("/ide/shadow/top.svg"); /** 18x14 */ public static final Icon TopLeft = IconLoader.getIcon("/ide/shadow/topLeft.svg"); /** 18x14 */ public static final Icon TopRight = IconLoader.getIcon("/ide/shadow/topRight.svg"); } /** 7x10 */ public static final Icon Statusbar_arrows = IconLoader.getIcon("/ide/statusbar_arrows.svg"); /** 16x16 */ public static final Icon UpDown = IconLoader.getIcon("/ide/upDown.svg"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Ide.FatalError_read */ @SuppressWarnings("unused") @Deprecated public static final Icon EmptyFatalError = AllIcons.Ide.FatalError_read; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Ide.FatalError */ @SuppressWarnings("unused") @Deprecated public static final Icon Error = AllIcons.Ide.FatalError; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.Error */ @SuppressWarnings("unused") @Deprecated public static final Icon Error_notifications = AllIcons.General.Error; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Ide.HectorOff */ @SuppressWarnings("unused") @Deprecated public static final Icon HectorNo = AllIcons.Ide.HectorOff; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon IncomingChangesOff = IconLoader.getIcon("/ide/incomingChangesOff.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.Information */ @SuppressWarnings("unused") @Deprecated public static final Icon Info_notifications = AllIcons.General.Information; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon NoNotifications13 = IconLoader.getIcon("/ide/noNotifications13.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Ide.Notification.NoEvents */ @SuppressWarnings("unused") @Deprecated public static final Icon Notifications = AllIcons.Ide.Notification.NoEvents; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.Warning */ @SuppressWarnings("unused") @Deprecated public static final Icon Warning_notifications = AllIcons.General.Warning; } /** 500x500 */ public static final Icon Idea_logo_background = IconLoader.getIcon("/idea_logo_background.png"); /** 100x100 */ public static final Icon Idea_logo_welcome = IconLoader.getIcon("/idea_logo_welcome.png"); public final static class Javaee { /** 16x16 */ public static final Icon Application_xml = IconLoader.getIcon("/javaee/application_xml.svg"); /** 16x16 */ public static final Icon BuildOnFrameDeactivation = IconLoader.getIcon("/javaee/buildOnFrameDeactivation.svg"); /** 16x16 */ public static final Icon Ejb_jar_xml = IconLoader.getIcon("/javaee/ejb-jar_xml.svg"); /** 16x16 */ public static final Icon EjbClass = IconLoader.getIcon("/javaee/ejbClass.svg"); /** 16x16 */ public static final Icon EjbModule = IconLoader.getIcon("/javaee/ejbModule.svg"); /** 16x16 */ public static final Icon EmbeddedAttributeOverlay = IconLoader.getIcon("/javaee/embeddedAttributeOverlay.svg"); /** 16x16 */ public static final Icon EntityBean = IconLoader.getIcon("/javaee/entityBean.svg"); /** 16x16 */ public static final Icon Home = IconLoader.getIcon("/javaee/home.svg"); /** 16x16 */ public static final Icon InheritedAttributeOverlay = IconLoader.getIcon("/javaee/inheritedAttributeOverlay.svg"); /** 16x16 */ public static final Icon InterceptorClass = IconLoader.getIcon("/javaee/interceptorClass.svg"); /** 16x16 */ public static final Icon InterceptorMethod = IconLoader.getIcon("/javaee/interceptorMethod.svg"); /** 16x16 */ public static final Icon JavaeeAppModule = IconLoader.getIcon("/javaee/JavaeeAppModule.svg"); /** 16x16 */ public static final Icon JpaFacet = IconLoader.getIcon("/javaee/jpaFacet.svg"); /** 16x16 */ public static final Icon MessageBean = IconLoader.getIcon("/javaee/messageBean.svg"); /** 16x16 */ public static final Icon PersistenceAttribute = IconLoader.getIcon("/javaee/persistenceAttribute.svg"); /** 16x16 */ public static final Icon PersistenceEmbeddable = IconLoader.getIcon("/javaee/persistenceEmbeddable.svg"); /** 16x16 */ public static final Icon PersistenceEntity = IconLoader.getIcon("/javaee/persistenceEntity.svg"); /** 16x16 */ public static final Icon PersistenceEntityListener = IconLoader.getIcon("/javaee/persistenceEntityListener.svg"); /** 16x16 */ public static final Icon PersistenceId = IconLoader.getIcon("/javaee/persistenceId.svg"); /** 16x16 */ public static final Icon PersistenceIdRelationship = IconLoader.getIcon("/javaee/persistenceIdRelationship.svg"); /** 16x16 */ public static final Icon PersistenceMappedSuperclass = IconLoader.getIcon("/javaee/persistenceMappedSuperclass.svg"); /** 16x16 */ public static final Icon PersistenceRelationship = IconLoader.getIcon("/javaee/persistenceRelationship.svg"); /** 16x16 */ public static final Icon PersistenceUnit = IconLoader.getIcon("/javaee/persistenceUnit.svg"); /** 16x16 */ public static final Icon Remote = IconLoader.getIcon("/javaee/remote.svg"); /** 16x16 */ public static final Icon SessionBean = IconLoader.getIcon("/javaee/sessionBean.svg"); /** 16x16 */ public static final Icon UpdateRunningApplication = IconLoader.getIcon("/javaee/updateRunningApplication.svg"); /** 16x16 */ public static final Icon Web_xml = IconLoader.getIcon("/javaee/web_xml.svg"); /** 16x16 */ public static final Icon WebModule = IconLoader.getIcon("/javaee/webModule.svg"); /** 16x16 */ public static final Icon WebModuleGroup = IconLoader.getIcon("/javaee/webModuleGroup.svg"); /** 16x16 */ public static final Icon WebService = IconLoader.getIcon("/javaee/WebService.svg"); /** 16x16 */ public static final Icon WebServiceClient = IconLoader.getIcon("/javaee/WebServiceClient.svg"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon DataSourceImport = IconLoader.getIcon("/javaee/dataSourceImport.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon DbSchemaImportBig = IconLoader.getIcon("/javaee/dbSchemaImportBig.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon EntityBeanBig = IconLoader.getIcon("/javaee/entityBeanBig.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Nodes.Interface */ @SuppressWarnings("unused") @Deprecated public static final Icon Local = AllIcons.Nodes.Interface; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Javaee.Home */ @SuppressWarnings("unused") @Deprecated public static final Icon LocalHome = AllIcons.Javaee.Home; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Javaee.WebService */ @SuppressWarnings("unused") @Deprecated public static final Icon WebService2 = AllIcons.Javaee.WebService; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Javaee.WebServiceClient */ @SuppressWarnings("unused") @Deprecated public static final Icon WebServiceClient2 = AllIcons.Javaee.WebServiceClient; } public final static class Json { /** 16x16 */ public static final Icon Array = IconLoader.getIcon("/json/array.svg"); /** 16x16 */ public static final Icon Object = IconLoader.getIcon("/json/object.svg"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Json.Object */ @SuppressWarnings("unused") @Deprecated public static final Icon Property_braces = AllIcons.Json.Object; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Json.Array */ @SuppressWarnings("unused") @Deprecated public static final Icon Property_brackets = AllIcons.Json.Array; } /** 80x80 */ public static final Icon Logo_welcomeScreen = IconLoader.getIcon("/Logo_welcomeScreen.png"); /** 80x80 */ public static final Icon Logo_welcomeScreen_CE = IconLoader.getIcon("/Logo_welcomeScreen_CE.png"); public final static class Mac { /** 55x55 */ public static final Icon AppIconOk512 = IconLoader.getIcon("/mac/appIconOk512.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Text = IconLoader.getIcon("/mac/text.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Tree_black_right_arrow = IconLoader.getIcon("/mac/tree_black_right_arrow.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Tree_white_down_arrow = IconLoader.getIcon("/mac/tree_white_down_arrow.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Tree_white_right_arrow = IconLoader.getIcon("/mac/tree_white_right_arrow.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon YosemiteOptionButtonSelector = IconLoader.getIcon("/mac/yosemiteOptionButtonSelector.png"); } public final static class Modules { /** 16x16 */ public static final Icon AddExcludedRoot = IconLoader.getIcon("/modules/addExcludedRoot.svg"); /** 16x16 */ public static final Icon Annotation = IconLoader.getIcon("/modules/annotation.svg"); /** 16x16 */ public static final Icon EditFolder = IconLoader.getIcon("/modules/editFolder.svg"); /** 16x16 */ public static final Icon ExcludedGeneratedRoot = IconLoader.getIcon("/modules/excludedGeneratedRoot.svg"); /** 16x16 */ public static final Icon ExcludeRoot = IconLoader.getIcon("/modules/excludeRoot.svg"); /** 16x16 */ public static final Icon GeneratedFolder = IconLoader.getIcon("/modules/generatedFolder.svg"); /** 16x16 */ public static final Icon GeneratedSourceRoot = IconLoader.getIcon("/modules/generatedSourceRoot.svg"); /** 16x16 */ public static final Icon GeneratedTestRoot = IconLoader.getIcon("/modules/generatedTestRoot.svg"); /** 16x16 */ public static final Icon Output = IconLoader.getIcon("/modules/output.svg"); /** 16x16 */ public static final Icon ResourcesRoot = IconLoader.getIcon("/modules/resourcesRoot.svg"); /** 16x16 */ public static final Icon SourceRoot = IconLoader.getIcon("/modules/sourceRoot.svg"); /** 16x16 */ public static final Icon SourceRootFileLayer = IconLoader.getIcon("/modules/sourceRootFileLayer.svg"); /** 16x16 */ public static final Icon Split = IconLoader.getIcon("/modules/split.svg"); /** 16x16 */ public static final Icon TestResourcesRoot = IconLoader.getIcon("/modules/testResourcesRoot.svg"); /** 16x16 */ public static final Icon TestRoot = IconLoader.getIcon("/modules/testRoot.svg"); public final static class Types { /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.User */ @SuppressWarnings("unused") @Deprecated public static final Icon UserDefined = AllIcons.General.User; } /** 16x16 */ public static final Icon UnloadedModule = IconLoader.getIcon("/modules/unloadedModule.svg"); /** 16x16 */ public static final Icon UnmarkWebroot = IconLoader.getIcon("/modules/unmarkWebroot.svg"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.Add */ @SuppressWarnings("unused") @Deprecated public static final Icon AddContentEntry = AllIcons.General.Add; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Close */ @SuppressWarnings("unused") @Deprecated public static final Icon DeleteContentFolder = AllIcons.Actions.Close; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.CloseHovered */ @SuppressWarnings("unused") @Deprecated public static final Icon DeleteContentFolderRollover = AllIcons.Actions.CloseHovered; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Close */ @SuppressWarnings("unused") @Deprecated public static final Icon DeleteContentRoot = AllIcons.Actions.Close; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.CloseHovered */ @SuppressWarnings("unused") @Deprecated public static final Icon DeleteContentRootRollover = AllIcons.Actions.CloseHovered; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Edit */ @SuppressWarnings("unused") @Deprecated public static final Icon Edit = AllIcons.Actions.Edit; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Nodes.PpLib */ @SuppressWarnings("unused") @Deprecated public static final Icon Library = AllIcons.Nodes.PpLib; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Vcs.Merge */ @SuppressWarnings("unused") @Deprecated public static final Icon Merge = AllIcons.Vcs.Merge; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Nodes.ModuleGroup */ @SuppressWarnings("unused") @Deprecated public static final Icon ModulesNode = AllIcons.Nodes.ModuleGroup; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.Inline_edit */ @SuppressWarnings("unused") @Deprecated public static final Icon SetPackagePrefix = AllIcons.General.Inline_edit; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.Inline_edit_hovered */ @SuppressWarnings("unused") @Deprecated public static final Icon SetPackagePrefixRollover = AllIcons.General.Inline_edit_hovered; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Nodes.Package */ @SuppressWarnings("unused") @Deprecated public static final Icon SourceFolder = AllIcons.Nodes.Package; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Sources = IconLoader.getIcon("/modules/sources.svg"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Nodes.TestSourceFolder */ @SuppressWarnings("unused") @Deprecated public static final Icon TestSourceFolder = AllIcons.Nodes.TestSourceFolder; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Nodes.WebFolder */ @SuppressWarnings("unused") @Deprecated public static final Icon WebRoot = AllIcons.Nodes.WebFolder; } public final static class Nodes { /** 16x16 */ public static final Icon AbstractClass = IconLoader.getIcon("/nodes/abstractClass.svg"); /** 16x16 */ public static final Icon AbstractException = IconLoader.getIcon("/nodes/abstractException.svg"); /** 16x16 */ public static final Icon AbstractMethod = IconLoader.getIcon("/nodes/abstractMethod.svg"); /** 16x16 */ public static final Icon Alias = IconLoader.getIcon("/nodes/alias.svg"); /** 16x16 */ public static final Icon Annotationtype = IconLoader.getIcon("/nodes/annotationtype.svg"); /** 16x16 */ public static final Icon AnonymousClass = IconLoader.getIcon("/nodes/anonymousClass.svg"); /** 16x16 */ public static final Icon Artifact = IconLoader.getIcon("/nodes/artifact.svg"); /** 16x16 */ public static final Icon Aspect = IconLoader.getIcon("/nodes/aspect.svg"); /** 16x16 */ public static final Icon C_plocal = IconLoader.getIcon("/nodes/c_plocal.svg"); /** 16x16 */ public static final Icon C_private = IconLoader.getIcon("/nodes/c_private.svg"); /** 16x16 */ public static final Icon C_protected = IconLoader.getIcon("/nodes/c_protected.svg"); /** 16x16 */ public static final Icon C_public = IconLoader.getIcon("/nodes/c_public.svg"); /** 16x16 */ public static final Icon Class = IconLoader.getIcon("/nodes/class.svg"); /** 16x16 */ public static final Icon ClassInitializer = IconLoader.getIcon("/nodes/classInitializer.svg"); /** 16x16 */ public static final Icon CompiledClassesFolder = IconLoader.getIcon("/nodes/compiledClassesFolder.svg"); /** 16x16 */ public static final Icon ConfigFolder = IconLoader.getIcon("/nodes/configFolder.svg"); /** 16x16 */ public static final Icon Constant = IconLoader.getIcon("/nodes/constant.svg"); /** 16x16 */ public static final Icon Controller = IconLoader.getIcon("/nodes/controller.svg"); /** 16x16 */ public static final Icon CopyOfFolder = IconLoader.getIcon("/nodes/copyOfFolder.svg"); /** 16x16 */ public static final Icon CustomRegion = IconLoader.getIcon("/nodes/customRegion.svg"); /** 16x16 */ public static final Icon Cvs_global = IconLoader.getIcon("/nodes/cvs_global.svg"); /** 16x16 */ public static final Icon Cvs_roots = IconLoader.getIcon("/nodes/cvs_roots.svg"); /** 16x16 */ public static final Icon DataColumn = IconLoader.getIcon("/nodes/dataColumn.svg"); /** 16x16 */ public static final Icon DataTables = IconLoader.getIcon("/nodes/DataTables.svg"); /** 16x16 */ public static final Icon Deploy = IconLoader.getIcon("/nodes/deploy.svg"); /** 16x16 */ public static final Icon Desktop = IconLoader.getIcon("/nodes/desktop.svg"); /** 16x16 */ public static final Icon Editorconfig = IconLoader.getIcon("/nodes/editorconfig.svg"); /** 16x16 */ public static final Icon Ejb = IconLoader.getIcon("/nodes/ejb.svg"); /** 16x16 */ public static final Icon EjbBusinessMethod = IconLoader.getIcon("/nodes/ejbBusinessMethod.svg"); /** 16x16 */ public static final Icon EjbCmpField = IconLoader.getIcon("/nodes/ejbCmpField.svg"); /** 16x16 */ public static final Icon EjbCmrField = IconLoader.getIcon("/nodes/ejbCmrField.svg"); /** 16x16 */ public static final Icon EjbCreateMethod = IconLoader.getIcon("/nodes/ejbCreateMethod.svg"); /** 16x16 */ public static final Icon EjbFinderMethod = IconLoader.getIcon("/nodes/ejbFinderMethod.svg"); /** 16x16 */ public static final Icon EjbPrimaryKeyClass = IconLoader.getIcon("/nodes/ejbPrimaryKeyClass.svg"); /** 16x16 */ public static final Icon EjbReference = IconLoader.getIcon("/nodes/ejbReference.svg"); /** 16x16 */ public static final Icon EmptyNode = IconLoader.getIcon("/nodes/emptyNode.svg"); /** 16x16 */ public static final Icon EnterpriseProject = IconLoader.getIcon("/nodes/enterpriseProject.svg"); /** 16x16 */ public static final Icon EntryPoints = IconLoader.getIcon("/nodes/entryPoints.svg"); /** 16x16 */ public static final Icon Enum = IconLoader.getIcon("/nodes/enum.svg"); /** 16x16 */ public static final Icon ErrorIntroduction = IconLoader.getIcon("/nodes/errorIntroduction.svg"); /** 16x16 */ public static final Icon ErrorMark = IconLoader.getIcon("/nodes/errorMark.svg"); /** 16x16 */ public static final Icon ExceptionClass = IconLoader.getIcon("/nodes/exceptionClass.svg"); /** 16x16 */ public static final Icon ExcludedFromCompile = IconLoader.getIcon("/nodes/excludedFromCompile.svg"); /** 16x16 */ public static final Icon ExtractedFolder = IconLoader.getIcon("/nodes/extractedFolder.svg"); /** 16x16 */ public static final Icon Favorite = IconLoader.getIcon("/nodes/favorite.svg"); /** 16x16 */ public static final Icon Field = IconLoader.getIcon("/nodes/field.svg"); /** 16x16 */ public static final Icon FieldPK = IconLoader.getIcon("/nodes/fieldPK.svg"); /** 16x16 */ public static final Icon FinalMark = IconLoader.getIcon("/nodes/finalMark.svg"); /** 16x16 */ public static final Icon Folder = IconLoader.getIcon("/nodes/folder.svg"); /** 16x16 */ public static final Icon Function = IconLoader.getIcon("/nodes/function.svg"); /** 16x16 */ public static final Icon HomeFolder = IconLoader.getIcon("/nodes/homeFolder.svg"); /** 16x16 */ public static final Icon IdeaModule = IconLoader.getIcon("/nodes/ideaModule.svg"); /** 16x16 */ public static final Icon IdeaProject = IconLoader.getIcon("/nodes/ideaProject.svg"); /** 16x16 */ public static final Icon InspectionResults = IconLoader.getIcon("/nodes/inspectionResults.svg"); /** 16x16 */ public static final Icon Interface = IconLoader.getIcon("/nodes/interface.svg"); /** 16x16 */ public static final Icon J2eeParameter = IconLoader.getIcon("/nodes/j2eeParameter.svg"); /** 16x16 */ public static final Icon JarDirectory = IconLoader.getIcon("/nodes/jarDirectory.svg"); /** 16x16 */ public static final Icon JavaDocFolder = IconLoader.getIcon("/nodes/javaDocFolder.svg"); /** 16x16 */ public static final Icon JavaModule = IconLoader.getIcon("/nodes/javaModule.svg"); public final static class Jsf { /** 16x16 */ public static final Icon Component = IconLoader.getIcon("/nodes/jsf/component.svg"); /** 16x16 */ public static final Icon Converter = IconLoader.getIcon("/nodes/jsf/converter.svg"); /** 16x16 */ public static final Icon General = IconLoader.getIcon("/nodes/jsf/general.svg"); /** 16x16 */ public static final Icon ManagedBean = IconLoader.getIcon("/nodes/jsf/managedBean.svg"); /** 16x16 */ public static final Icon NavigationRule = IconLoader.getIcon("/nodes/jsf/navigationRule.svg"); /** 16x16 */ public static final Icon Renderer = IconLoader.getIcon("/nodes/jsf/renderer.svg"); /** 16x16 */ public static final Icon RenderKit = IconLoader.getIcon("/nodes/jsf/renderKit.svg"); /** 16x16 */ public static final Icon Validator = IconLoader.getIcon("/nodes/jsf/validator.svg"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Nodes.Parameter */ @SuppressWarnings("unused") @Deprecated public static final Icon GenericValue = AllIcons.Nodes.Parameter; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Nodes.UpFolder */ @SuppressWarnings("unused") @Deprecated public static final Icon NavigationCase = AllIcons.Nodes.UpFolder; } /** 16x16 */ public static final Icon Jsr45 = IconLoader.getIcon("/nodes/jsr45.svg"); /** 16x16 */ public static final Icon JunitTestMark = IconLoader.getIcon("/nodes/junitTestMark.svg"); /** 16x16 */ public static final Icon KeymapAnt = IconLoader.getIcon("/nodes/keymapAnt.svg"); /** 16x16 */ public static final Icon KeymapEditor = IconLoader.getIcon("/nodes/keymapEditor.svg"); /** 16x16 */ public static final Icon KeymapMainMenu = IconLoader.getIcon("/nodes/keymapMainMenu.svg"); /** 16x16 */ public static final Icon KeymapOther = IconLoader.getIcon("/nodes/keymapOther.svg"); /** 16x16 */ public static final Icon KeymapTools = IconLoader.getIcon("/nodes/keymapTools.svg"); /** 16x16 */ public static final Icon Locked = IconLoader.getIcon("/nodes/locked.svg"); /** 16x16 */ public static final Icon LogFolder = IconLoader.getIcon("/nodes/logFolder.svg"); /** 16x16 */ public static final Icon Method = IconLoader.getIcon("/nodes/method.svg"); /** 16x16 */ public static final Icon MethodReference = IconLoader.getIcon("/nodes/methodReference.svg"); /** 16x16 */ public static final Icon ModelClass = IconLoader.getIcon("/nodes/modelClass.svg"); /** 16x16 */ public static final Icon Models = IconLoader.getIcon("/nodes/models.svg"); /** 16x16 */ public static final Icon Module = IconLoader.getIcon("/nodes/Module.svg"); /** 16x16 */ public static final Icon ModuleGroup = IconLoader.getIcon("/nodes/moduleGroup.svg"); /** 16x16 */ public static final Icon NativeLibrariesFolder = IconLoader.getIcon("/nodes/nativeLibrariesFolder.svg"); /** 16x16 */ public static final Icon NewParameter = IconLoader.getIcon("/nodes/newParameter.svg"); /** 16x16 */ public static final Icon NodePlaceholder = IconLoader.getIcon("/nodes/nodePlaceholder.svg"); /** 16x16 */ public static final Icon NotFavoriteOnHover = IconLoader.getIcon("/nodes/notFavoriteOnHover.svg"); /** 16x16 */ public static final Icon ObjectTypeAttribute = IconLoader.getIcon("/nodes/objectTypeAttribute.svg"); /** 16x16 */ public static final Icon Package = IconLoader.getIcon("/nodes/package.svg"); /** 16x16 */ public static final Icon Padlock = IconLoader.getIcon("/nodes/padlock.svg"); /** 16x16 */ public static final Icon Parameter = IconLoader.getIcon("/nodes/parameter.svg"); /** 16x16 */ public static final Icon Plugin = IconLoader.getIcon("/nodes/plugin.svg"); /** 16x16 */ public static final Icon PluginJB = IconLoader.getIcon("/nodes/pluginJB.svg"); /** 32x32 */ public static final Icon PluginLogo = IconLoader.getIcon("/nodes/pluginLogo.svg"); /** 16x16 */ public static final Icon Pluginnotinstalled = IconLoader.getIcon("/nodes/pluginnotinstalled.svg"); /** 16x16 */ public static final Icon Pluginobsolete = IconLoader.getIcon("/nodes/pluginobsolete.svg"); /** 16x16 */ public static final Icon PluginRestart = IconLoader.getIcon("/nodes/pluginRestart.svg"); /** 16x16 */ public static final Icon PpInvalid = IconLoader.getIcon("/nodes/ppInvalid.svg"); /** 16x16 */ public static final Icon PpJar = IconLoader.getIcon("/nodes/ppJar.svg"); /** 16x16 */ public static final Icon PpJdk = IconLoader.getIcon("/nodes/ppJdk.svg"); /** 16x16 */ public static final Icon PpLib = IconLoader.getIcon("/nodes/ppLib.svg"); /** 16x16 */ public static final Icon PpLibFolder = IconLoader.getIcon("/nodes/ppLibFolder.svg"); /** 16x16 */ public static final Icon PpWeb = IconLoader.getIcon("/nodes/ppWeb.svg"); /** 16x16 */ public static final Icon Project = IconLoader.getIcon("/nodes/project.svg"); /** 16x16 */ public static final Icon Property = IconLoader.getIcon("/nodes/property.svg"); /** 16x16 */ public static final Icon PropertyRead = IconLoader.getIcon("/nodes/propertyRead.svg"); /** 16x16 */ public static final Icon PropertyReadStatic = IconLoader.getIcon("/nodes/propertyReadStatic.svg"); /** 16x16 */ public static final Icon PropertyReadWrite = IconLoader.getIcon("/nodes/propertyReadWrite.svg"); /** 16x16 */ public static final Icon PropertyReadWriteStatic = IconLoader.getIcon("/nodes/propertyReadWriteStatic.svg"); /** 16x16 */ public static final Icon PropertyWrite = IconLoader.getIcon("/nodes/propertyWrite.svg"); /** 16x16 */ public static final Icon PropertyWriteStatic = IconLoader.getIcon("/nodes/propertyWriteStatic.svg"); /** 16x16 */ public static final Icon Read_access = IconLoader.getIcon("/nodes/read-access.svg"); /** 16x16 */ public static final Icon ResourceBundle = IconLoader.getIcon("/nodes/resourceBundle.svg"); /** 16x16 */ public static final Icon RunnableMark = IconLoader.getIcon("/nodes/runnableMark.svg"); /** 16x16 */ public static final Icon Rw_access = IconLoader.getIcon("/nodes/rw-access.svg"); /** 16x16 */ public static final Icon SecurityRole = IconLoader.getIcon("/nodes/securityRole.svg"); /** 16x16 */ public static final Icon Servlet = IconLoader.getIcon("/nodes/servlet.svg"); /** 16x16 */ public static final Icon Shared = IconLoader.getIcon("/nodes/shared.svg"); /** 16x16 */ public static final Icon SortBySeverity = IconLoader.getIcon("/nodes/sortBySeverity.svg"); /** 16x16 */ public static final Icon Static = IconLoader.getIcon("/nodes/static.svg"); /** 16x16 */ public static final Icon StaticMark = IconLoader.getIcon("/nodes/staticMark.svg"); /** 16x16 */ public static final Icon Symlink = IconLoader.getIcon("/nodes/symlink.svg"); /** 16x16 */ public static final Icon TabAlert = IconLoader.getIcon("/nodes/tabAlert.svg"); /** 16x16 */ public static final Icon TabPin = IconLoader.getIcon("/nodes/tabPin.svg"); /** 16x16 */ public static final Icon Tag = IconLoader.getIcon("/nodes/tag.svg"); /** 13x13 */ public static final Icon Target = IconLoader.getIcon("/nodes/target.svg"); /** 16x16 */ public static final Icon Test = IconLoader.getIcon("/nodes/test.svg"); /** 16x16 */ public static final Icon TestGroup = IconLoader.getIcon("/nodes/testGroup.svg"); /** 16x16 */ public static final Icon TestIgnored = IconLoader.getIcon("/nodes/testIgnored.svg"); /** 16x16 */ public static final Icon TestSourceFolder = IconLoader.getIcon("/nodes/testSourceFolder.svg"); /** 16x16 */ public static final Icon Type = IconLoader.getIcon("/nodes/type.svg"); /** 16x16 */ public static final Icon Undeploy = IconLoader.getIcon("/nodes/undeploy.svg"); /** 16x16 */ public static final Icon Unknown = IconLoader.getIcon("/nodes/unknown.svg"); /** 16x16 */ public static final Icon UnknownJdk = IconLoader.getIcon("/nodes/unknownJdk.svg"); /** 16x16 */ public static final Icon UpFolder = IconLoader.getIcon("/nodes/upFolder.svg"); /** 16x16 */ public static final Icon UpLevel = IconLoader.getIcon("/nodes/upLevel.svg"); /** 16x16 */ public static final Icon Variable = IconLoader.getIcon("/nodes/variable.svg"); /** 16x16 */ public static final Icon WarningIntroduction = IconLoader.getIcon("/nodes/warningIntroduction.svg"); /** 16x16 */ public static final Icon WebFolder = IconLoader.getIcon("/nodes/webFolder.svg"); /** 16x16 */ public static final Icon Weblistener = IconLoader.getIcon("/nodes/weblistener.svg"); /** 16x16 */ public static final Icon Write_access = IconLoader.getIcon("/nodes/write-access.svg"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Nodes.Tag */ @SuppressWarnings("unused") @Deprecated public static final Icon Advice = AllIcons.Nodes.Tag; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowDown */ @SuppressWarnings("unused") @Deprecated public static final Icon CollapseNode = AllIcons.General.ArrowDown; /** @deprecated to be removed in IDEA 2020 - see DatabaseIcons.View */ @SuppressWarnings("unused") @Deprecated public static final Icon DataSchema = IconLoader.getIcon("/nodes/dataSchema.svg"); /** @deprecated to be removed in IDEA 2020 - see DatabaseIcons.DatabaseGroup */ @SuppressWarnings("unused") @Deprecated public static final Icon DataSource = IconLoader.getIcon("/nodes/DataSource.svg"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon DataView = IconLoader.getIcon("/nodes/dataView.svg"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon DisabledPointcut = IconLoader.getIcon("/nodes/disabledPointcut.svg"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowRight */ @SuppressWarnings("unused") @Deprecated public static final Icon ExpandNode = AllIcons.General.ArrowRight; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Nodes.Favorite */ @SuppressWarnings("unused") @Deprecated public static final Icon FavoriteOnHover = AllIcons.Nodes.Favorite; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Nodes.Module */ @SuppressWarnings("unused") @Deprecated public static final Icon JavaModuleRoot = AllIcons.Nodes.Module; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon NewException = IconLoader.getIcon("/nodes/newException.svg"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Nodes.Folder */ @SuppressWarnings("unused") @Deprecated public static final Icon NewFolder = AllIcons.Nodes.Folder; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Nodes.TabPin */ @SuppressWarnings("unused") @Deprecated public static final Icon PinToolWindow = AllIcons.Nodes.TabPin; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon PluginUpdate = IconLoader.getIcon("/nodes/pluginUpdate.svg"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Pointcut = IconLoader.getIcon("/nodes/pointcut.svg"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Nodes.Folder */ @SuppressWarnings("unused") @Deprecated public static final Icon PpFile = AllIcons.Nodes.Folder; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon PpWebLogo = IconLoader.getIcon("/nodes/ppWebLogo.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Nodes.Package */ @SuppressWarnings("unused") @Deprecated public static final Icon SourceFolder = AllIcons.Nodes.Package; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Nodes.Folder */ @SuppressWarnings("unused") @Deprecated public static final Icon TreeClosed = AllIcons.Nodes.Folder; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowDown */ @SuppressWarnings("unused") @Deprecated public static final Icon TreeCollapseNode = AllIcons.General.ArrowDown; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon TreeDownArrow = IconLoader.getIcon("/nodes/treeDownArrow.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowRight */ @SuppressWarnings("unused") @Deprecated public static final Icon TreeExpandNode = AllIcons.General.ArrowRight; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Nodes.Folder */ @SuppressWarnings("unused") @Deprecated public static final Icon TreeOpen = AllIcons.Nodes.Folder; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon TreeRightArrow = IconLoader.getIcon("/nodes/treeRightArrow.png"); } public final static class ObjectBrowser { /** 16x16 */ public static final Icon AbbreviatePackageNames = IconLoader.getIcon("/objectBrowser/abbreviatePackageNames.svg"); /** 16x16 */ public static final Icon CompactEmptyPackages = IconLoader.getIcon("/objectBrowser/compactEmptyPackages.svg"); /** 16x16 */ public static final Icon FlattenModules = IconLoader.getIcon("/objectBrowser/flattenModules.svg"); /** 16x16 */ public static final Icon FlattenPackages = IconLoader.getIcon("/objectBrowser/flattenPackages.svg"); /** 16x16 */ public static final Icon ShowLibraryContents = IconLoader.getIcon("/objectBrowser/showLibraryContents.svg"); /** 16x16 */ public static final Icon ShowMembers = IconLoader.getIcon("/objectBrowser/showMembers.svg"); /** 16x16 */ public static final Icon SortByType = IconLoader.getIcon("/objectBrowser/sortByType.svg"); /** 16x16 */ public static final Icon Sorted = IconLoader.getIcon("/objectBrowser/sorted.svg"); /** 16x16 */ public static final Icon SortedByUsage = IconLoader.getIcon("/objectBrowser/sortedByUsage.svg"); /** 16x16 */ public static final Icon VisibilitySort = IconLoader.getIcon("/objectBrowser/visibilitySort.svg"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Edit */ @SuppressWarnings("unused") @Deprecated public static final Icon ShowEditorHighlighting = AllIcons.Actions.Edit; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.GroupByModule */ @SuppressWarnings("unused") @Deprecated public static final Icon ShowModules = AllIcons.Actions.GroupByModule; } public final static class Plugins { /** 12x12 */ public static final Icon Downloads = IconLoader.getIcon("/plugins/downloads.svg"); /** 15x15 */ public static final Icon ModifierInvalid = IconLoader.getIcon("/plugins/modifierInvalid.svg"); /** 14x14 */ public static final Icon ModifierJBLogo = IconLoader.getIcon("/plugins/modifierJBLogo.svg"); /** 40x40 */ public static final Icon PluginLogo = IconLoader.getIcon("/plugins/pluginLogo.svg"); /** 40x40 */ public static final Icon PluginLogo_40 = IconLoader.getIcon("/plugins/pluginLogo_40.png"); /** 80x80 */ public static final Icon PluginLogo_80 = IconLoader.getIcon("/plugins/pluginLogo_80.png"); /** 40x40 */ public static final Icon PluginLogoDisabled_40 = IconLoader.getIcon("/plugins/pluginLogoDisabled_40.png"); /** 80x80 */ public static final Icon PluginLogoDisabled_80 = IconLoader.getIcon("/plugins/pluginLogoDisabled_80.png"); /** 12x12 */ public static final Icon Rating = IconLoader.getIcon("/plugins/rating.svg"); /** 12x12 */ public static final Icon Updated = IconLoader.getIcon("/plugins/updated.svg"); } public final static class Preferences { /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Appearance = IconLoader.getIcon("/preferences/Appearance.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon CodeStyle = IconLoader.getIcon("/preferences/CodeStyle.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Compiler = IconLoader.getIcon("/preferences/Compiler.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Editor = IconLoader.getIcon("/preferences/Editor.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon FileColors = IconLoader.getIcon("/preferences/FileColors.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon FileTypes = IconLoader.getIcon("/preferences/FileTypes.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon General = IconLoader.getIcon("/preferences/General.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Keymap = IconLoader.getIcon("/preferences/Keymap.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Plugins = IconLoader.getIcon("/preferences/Plugins.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Updates = IconLoader.getIcon("/preferences/Updates.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon VersionControl = IconLoader.getIcon("/preferences/VersionControl.png"); } public final static class Process { public final static class Big { /** 32x32 */ public static final Icon Step_1 = IconLoader.getIcon("/process/big/step_1.svg"); /** 32x32 */ public static final Icon Step_2 = IconLoader.getIcon("/process/big/step_2.svg"); /** 32x32 */ public static final Icon Step_3 = IconLoader.getIcon("/process/big/step_3.svg"); /** 32x32 */ public static final Icon Step_4 = IconLoader.getIcon("/process/big/step_4.svg"); /** 32x32 */ public static final Icon Step_5 = IconLoader.getIcon("/process/big/step_5.svg"); /** 32x32 */ public static final Icon Step_6 = IconLoader.getIcon("/process/big/step_6.svg"); /** 32x32 */ public static final Icon Step_7 = IconLoader.getIcon("/process/big/step_7.svg"); /** 32x32 */ public static final Icon Step_8 = IconLoader.getIcon("/process/big/step_8.svg"); /** 32x32 */ public static final Icon Step_passive = IconLoader.getIcon("/process/big/step_passive.svg"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated /** 32x32 */ public static final Icon Step_10 = IconLoader.getIcon("/process/big/step_4.svg"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated /** 32x32 */ public static final Icon Step_11 = IconLoader.getIcon("/process/big/step_6.svg"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated /** 32x32 */ public static final Icon Step_12 = IconLoader.getIcon("/process/big/step_8.svg"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated /** 32x32 */ public static final Icon Step_9 = IconLoader.getIcon("/process/big/step_2.svg"); } public final static class FS { /** 16x16 */ public static final Icon Step_1 = IconLoader.getIcon("/process/fs/step_1.png"); /** 16x16 */ public static final Icon Step_10 = IconLoader.getIcon("/process/fs/step_10.png"); /** 16x16 */ public static final Icon Step_11 = IconLoader.getIcon("/process/fs/step_11.png"); /** 16x16 */ public static final Icon Step_12 = IconLoader.getIcon("/process/fs/step_12.png"); /** 16x16 */ public static final Icon Step_13 = IconLoader.getIcon("/process/fs/step_13.png"); /** 16x16 */ public static final Icon Step_14 = IconLoader.getIcon("/process/fs/step_14.png"); /** 16x16 */ public static final Icon Step_15 = IconLoader.getIcon("/process/fs/step_15.png"); /** 16x16 */ public static final Icon Step_16 = IconLoader.getIcon("/process/fs/step_16.png"); /** 16x16 */ public static final Icon Step_17 = IconLoader.getIcon("/process/fs/step_17.png"); /** 16x16 */ public static final Icon Step_18 = IconLoader.getIcon("/process/fs/step_18.png"); /** 16x16 */ public static final Icon Step_2 = IconLoader.getIcon("/process/fs/step_2.png"); /** 16x16 */ public static final Icon Step_3 = IconLoader.getIcon("/process/fs/step_3.png"); /** 16x16 */ public static final Icon Step_4 = IconLoader.getIcon("/process/fs/step_4.png"); /** 16x16 */ public static final Icon Step_5 = IconLoader.getIcon("/process/fs/step_5.png"); /** 16x16 */ public static final Icon Step_6 = IconLoader.getIcon("/process/fs/step_6.png"); /** 16x16 */ public static final Icon Step_7 = IconLoader.getIcon("/process/fs/step_7.png"); /** 16x16 */ public static final Icon Step_8 = IconLoader.getIcon("/process/fs/step_8.png"); /** 16x16 */ public static final Icon Step_9 = IconLoader.getIcon("/process/fs/step_9.png"); /** 16x16 */ public static final Icon Step_mask = IconLoader.getIcon("/process/fs/step_mask.png"); /** 16x16 */ public static final Icon Step_passive = IconLoader.getIcon("/process/fs/step_passive.png"); } /** 14x14 */ public static final Icon ProgressPause = IconLoader.getIcon("/process/progressPause.svg"); /** 14x14 */ public static final Icon ProgressPauseHover = IconLoader.getIcon("/process/progressPauseHover.svg"); /** 12x12 */ public static final Icon ProgressPauseSmall = IconLoader.getIcon("/process/progressPauseSmall.svg"); /** 12x12 */ public static final Icon ProgressPauseSmallHover = IconLoader.getIcon("/process/progressPauseSmallHover.svg"); /** 14x14 */ public static final Icon ProgressResume = IconLoader.getIcon("/process/progressResume.svg"); /** 14x14 */ public static final Icon ProgressResumeHover = IconLoader.getIcon("/process/progressResumeHover.svg"); /** 12x12 */ public static final Icon ProgressResumeSmall = IconLoader.getIcon("/process/progressResumeSmall.svg"); /** 12x12 */ public static final Icon ProgressResumeSmallHover = IconLoader.getIcon("/process/progressResumeSmallHover.svg"); public final static class State { /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon GreenOK = IconLoader.getIcon("/process/state/GreenOK.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon GreyProgr = IconLoader.getIcon("/process/state/GreyProgr.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon GreyProgr_1 = IconLoader.getIcon("/process/state/GreyProgr_1.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon GreyProgr_2 = IconLoader.getIcon("/process/state/GreyProgr_2.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon GreyProgr_3 = IconLoader.getIcon("/process/state/GreyProgr_3.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon GreyProgr_4 = IconLoader.getIcon("/process/state/GreyProgr_4.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon GreyProgr_5 = IconLoader.getIcon("/process/state/GreyProgr_5.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon GreyProgr_6 = IconLoader.getIcon("/process/state/GreyProgr_6.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon GreyProgr_7 = IconLoader.getIcon("/process/state/GreyProgr_7.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon GreyProgr_8 = IconLoader.getIcon("/process/state/GreyProgr_8.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon RedExcl = IconLoader.getIcon("/process/state/RedExcl.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon YellowStr = IconLoader.getIcon("/process/state/YellowStr.png"); } /** 16x16 */ public static final Icon Step_1 = IconLoader.getIcon("/process/step_1.svg"); /** 16x16 */ public static final Icon Step_2 = IconLoader.getIcon("/process/step_2.svg"); /** 16x16 */ public static final Icon Step_3 = IconLoader.getIcon("/process/step_3.svg"); /** 16x16 */ public static final Icon Step_4 = IconLoader.getIcon("/process/step_4.svg"); /** 16x16 */ public static final Icon Step_5 = IconLoader.getIcon("/process/step_5.svg"); /** 16x16 */ public static final Icon Step_6 = IconLoader.getIcon("/process/step_6.svg"); /** 16x16 */ public static final Icon Step_7 = IconLoader.getIcon("/process/step_7.svg"); /** 16x16 */ public static final Icon Step_8 = IconLoader.getIcon("/process/step_8.svg"); /** 16x16 */ public static final Icon Step_mask = IconLoader.getIcon("/process/step_mask.svg"); /** 16x16 */ public static final Icon Step_passive = IconLoader.getIcon("/process/step_passive.svg"); /** 14x14 */ public static final Icon Stop = IconLoader.getIcon("/process/stop.svg"); /** 14x14 */ public static final Icon StopHovered = IconLoader.getIcon("/process/stopHovered.svg"); /** 12x12 */ public static final Icon StopSmall = IconLoader.getIcon("/process/stopSmall.svg"); /** 12x12 */ public static final Icon StopSmallHovered = IconLoader.getIcon("/process/stopSmallHovered.svg"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon DisabledDebug = IconLoader.getIcon("/process/disabledDebug.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon DisabledRun = IconLoader.getIcon("/process/disabledRun.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated /** 16x16 */ public static final Icon Step_10 = IconLoader.getIcon("/process/step_4.svg"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated /** 16x16 */ public static final Icon Step_11 = IconLoader.getIcon("/process/step_6.svg"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated /** 16x16 */ public static final Icon Step_12 = IconLoader.getIcon("/process/step_8.svg"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated /** 16x16 */ public static final Icon Step_9 = IconLoader.getIcon("/process/step_2.svg"); } public final static class Providers { /** 16x16 */ public static final Icon Apache = IconLoader.getIcon("/providers/apache.svg"); /** 16x16 */ public static final Icon ApacheDerby = IconLoader.getIcon("/providers/apacheDerby.svg"); /** 16x16 */ public static final Icon Azure = IconLoader.getIcon("/providers/azure.svg"); /** 16x16 */ public static final Icon Cassandra = IconLoader.getIcon("/providers/cassandra.svg"); /** 16x16 */ public static final Icon ClickHouse = IconLoader.getIcon("/providers/clickHouse.svg"); /** 16x16 */ public static final Icon DB2 = IconLoader.getIcon("/providers/DB2.svg"); /** 16x16 */ public static final Icon Eclipse = IconLoader.getIcon("/providers/eclipse.svg"); /** 16x16 */ public static final Icon Exasol = IconLoader.getIcon("/providers/exasol.svg"); /** 16x16 */ public static final Icon Firebird = IconLoader.getIcon("/providers/firebird.svg"); /** 16x16 */ public static final Icon Greenplum = IconLoader.getIcon("/providers/greenplum.svg"); /** 16x16 */ public static final Icon H2 = IconLoader.getIcon("/providers/h2.svg"); /** 16x16 */ public static final Icon HANA = IconLoader.getIcon("/providers/HANA.svg"); /** 16x16 */ public static final Icon Hibernate = IconLoader.getIcon("/providers/hibernate.svg"); /** 16x16 */ public static final Icon Hive = IconLoader.getIcon("/providers/hive.svg"); /** 16x16 */ public static final Icon Hsqldb = IconLoader.getIcon("/providers/hsqldb.svg"); /** 16x16 */ public static final Icon Ibm = IconLoader.getIcon("/providers/ibm.svg"); /** 16x16 */ public static final Icon Informix = IconLoader.getIcon("/providers/informix.svg"); /** 16x16 */ public static final Icon Mariadb = IconLoader.getIcon("/providers/mariadb.svg"); /** 16x16 */ public static final Icon Microsoft = IconLoader.getIcon("/providers/microsoft.svg"); /** 16x16 */ public static final Icon Mysql = IconLoader.getIcon("/providers/mysql.svg"); /** 16x16 */ public static final Icon Oracle = IconLoader.getIcon("/providers/oracle.svg"); /** 16x16 */ public static final Icon Postgresql = IconLoader.getIcon("/providers/postgresql.svg"); /** 16x16 */ public static final Icon Presto = IconLoader.getIcon("/providers/presto.svg"); /** 16x16 */ public static final Icon Redshift = IconLoader.getIcon("/providers/redshift.svg"); /** 16x16 */ public static final Icon Snowflake = IconLoader.getIcon("/providers/snowflake.svg"); /** 16x16 */ public static final Icon Spark = IconLoader.getIcon("/providers/spark.svg"); /** 16x16 */ public static final Icon Sqlite = IconLoader.getIcon("/providers/sqlite.svg"); /** 16x16 */ public static final Icon SqlServer = IconLoader.getIcon("/providers/sqlServer.svg"); /** 16x16 */ public static final Icon Sun = IconLoader.getIcon("/providers/sun.svg"); /** 16x16 */ public static final Icon Sybase = IconLoader.getIcon("/providers/sybase.svg"); /** 16x16 */ public static final Icon Teradata = IconLoader.getIcon("/providers/teradata.svg"); /** 16x16 */ public static final Icon Vertica = IconLoader.getIcon("/providers/vertica.svg"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Bea = IconLoader.getIcon("/providers/bea.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Nodes.Cvs_global */ @SuppressWarnings("unused") @Deprecated public static final Icon Cvs = AllIcons.Nodes.Cvs_global; } public final static class RunConfigurations { /** 16x16 */ public static final Icon Applet = IconLoader.getIcon("/runConfigurations/applet.svg"); /** 16x16 */ public static final Icon Application = IconLoader.getIcon("/runConfigurations/application.svg"); /** 16x16 */ public static final Icon Compound = IconLoader.getIcon("/runConfigurations/compound.svg"); /** 16x16 */ public static final Icon HidePassed = IconLoader.getIcon("/runConfigurations/hidePassed.svg"); /** 16x16 */ public static final Icon IgnoredTest = IconLoader.getIcon("/runConfigurations/ignoredTest.svg"); /** 16x16 */ public static final Icon InvalidConfigurationLayer = IconLoader.getIcon("/runConfigurations/invalidConfigurationLayer.svg"); /** 16x16 */ public static final Icon Junit = IconLoader.getIcon("/runConfigurations/junit.svg"); /** 16x16 */ public static final Icon Remote = IconLoader.getIcon("/runConfigurations/remote.svg"); /** 16x16 */ public static final Icon RerunFailedTests = IconLoader.getIcon("/runConfigurations/rerunFailedTests.svg"); /** 16x16 */ public static final Icon Scroll_down = IconLoader.getIcon("/runConfigurations/scroll_down.svg"); /** 16x16 */ public static final Icon ShowIgnored = IconLoader.getIcon("/runConfigurations/showIgnored.svg"); /** 16x16 */ public static final Icon ShowPassed = IconLoader.getIcon("/runConfigurations/showPassed.svg"); /** 16x16 */ public static final Icon SortbyDuration = IconLoader.getIcon("/runConfigurations/sortbyDuration.svg"); /** 16x16 */ public static final Icon TestCustom = IconLoader.getIcon("/runConfigurations/testCustom.svg"); /** 16x16 */ public static final Icon TestError = IconLoader.getIcon("/runConfigurations/testError.svg"); /** 16x16 */ public static final Icon TestFailed = IconLoader.getIcon("/runConfigurations/testFailed.svg"); /** 16x16 */ public static final Icon TestIgnored = IconLoader.getIcon("/runConfigurations/testIgnored.svg"); /** 16x16 */ public static final Icon TestMark = IconLoader.getIcon("/runConfigurations/testMark.svg"); /** 16x16 */ public static final Icon TestNotRan = IconLoader.getIcon("/runConfigurations/testNotRan.svg"); /** 16x16 */ public static final Icon TestPassed = IconLoader.getIcon("/runConfigurations/testPassed.svg"); /** 16x16 */ public static final Icon TestPaused = IconLoader.getIcon("/runConfigurations/testPaused.svg"); /** 16x16 */ public static final Icon TestSkipped = IconLoader.getIcon("/runConfigurations/testSkipped.svg"); public final static class TestState { /** 12x12 */ public static final Icon Green2 = IconLoader.getIcon("/runConfigurations/testState/green2.svg"); /** 12x12 */ public static final Icon Red2 = IconLoader.getIcon("/runConfigurations/testState/red2.svg"); /** 12x12 */ public static final Icon Run = IconLoader.getIcon("/runConfigurations/testState/run.svg"); /** 12x12 */ public static final Icon Run_run = IconLoader.getIcon("/runConfigurations/testState/run_run.svg"); /** 12x12 */ public static final Icon Yellow2 = IconLoader.getIcon("/runConfigurations/testState/yellow2.svg"); } /** 16x16 */ public static final Icon TestTerminated = IconLoader.getIcon("/runConfigurations/testTerminated.svg"); /** 16x16 */ public static final Icon TestUnknown = IconLoader.getIcon("/runConfigurations/testUnknown.svg"); /** 16x16 */ public static final Icon Tomcat = IconLoader.getIcon("/runConfigurations/tomcat.svg"); /** 16x16 */ public static final Icon ToolbarError = IconLoader.getIcon("/runConfigurations/toolbarError.svg"); /** 16x16 */ public static final Icon ToolbarFailed = IconLoader.getIcon("/runConfigurations/toolbarFailed.svg"); /** 16x16 */ public static final Icon ToolbarPassed = IconLoader.getIcon("/runConfigurations/toolbarPassed.svg"); /** 16x16 */ public static final Icon ToolbarSkipped = IconLoader.getIcon("/runConfigurations/toolbarSkipped.svg"); /** 16x16 */ public static final Icon ToolbarTerminated = IconLoader.getIcon("/runConfigurations/toolbarTerminated.svg"); /** 16x16 */ public static final Icon TrackCoverage = IconLoader.getIcon("/runConfigurations/trackCoverage.svg"); /** 16x16 */ public static final Icon Web_app = IconLoader.getIcon("/runConfigurations/web_app.svg"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.BalloonError */ @SuppressWarnings("unused") @Deprecated public static final Icon ConfigurationWarning = AllIcons.General.BalloonError; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon HideIgnored = IconLoader.getIcon("/runConfigurations/hideIgnored.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon IncludeNonStartedTests_Rerun = IconLoader.getIcon("/runConfigurations/includeNonStartedTests_Rerun.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon LoadingTree = IconLoader.getIcon("/runConfigurations/loadingTree.png"); /** @deprecated to be removed in IDEA 2020 - use DatabaseIcons.ConsoleRun */ @SuppressWarnings("unused") @Deprecated public static final Icon Ql_console = IconLoader.getIcon("/runConfigurations/ql_console.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Menu_saveall */ @SuppressWarnings("unused") @Deprecated public static final Icon SaveTempConfig = AllIcons.Actions.Menu_saveall; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon ScrollToStackTrace = IconLoader.getIcon("/runConfigurations/scrollToStackTrace.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon SelectFirstDefect = IconLoader.getIcon("/runConfigurations/selectFirstDefect.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon SourceAtException = IconLoader.getIcon("/runConfigurations/sourceAtException.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Process.Step_1 */ @SuppressWarnings("unused") @Deprecated public static final Icon TestInProgress1 = AllIcons.Process.Step_1; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Process.Step_2 */ @SuppressWarnings("unused") @Deprecated public static final Icon TestInProgress2 = AllIcons.Process.Step_2; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Process.Step_3 */ @SuppressWarnings("unused") @Deprecated public static final Icon TestInProgress3 = AllIcons.Process.Step_3; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Process.Step_4 */ @SuppressWarnings("unused") @Deprecated public static final Icon TestInProgress4 = AllIcons.Process.Step_4; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Process.Step_5 */ @SuppressWarnings("unused") @Deprecated public static final Icon TestInProgress5 = AllIcons.Process.Step_5; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Process.Step_6 */ @SuppressWarnings("unused") @Deprecated public static final Icon TestInProgress6 = AllIcons.Process.Step_6; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Process.Step_7 */ @SuppressWarnings("unused") @Deprecated public static final Icon TestInProgress7 = AllIcons.Process.Step_7; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Process.Step_8 */ @SuppressWarnings("unused") @Deprecated public static final Icon TestInProgress8 = AllIcons.Process.Step_8; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Nodes.Jsf.Renderer */ @SuppressWarnings("unused") @Deprecated public static final Icon TrackTests = AllIcons.Nodes.Jsf.Renderer; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Help */ @SuppressWarnings("unused") @Deprecated public static final Icon Unknown = AllIcons.Actions.Help; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.ListFiles */ @SuppressWarnings("unused") @Deprecated public static final Icon Variables = AllIcons.Actions.ListFiles; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon WithCoverageLayer = IconLoader.getIcon("/runConfigurations/withCoverageLayer.png"); } public final static class Scope { /** 16x16 */ public static final Icon ChangedFiles = IconLoader.getIcon("/scope/changedFiles.svg"); /** 16x16 */ public static final Icon ChangedFilesAll = IconLoader.getIcon("/scope/changedFilesAll.svg"); /** 16x16 */ public static final Icon Problems = IconLoader.getIcon("/scope/problems.svg"); /** 16x16 */ public static final Icon Production = IconLoader.getIcon("/scope/production.svg"); /** 16x16 */ public static final Icon Scratches = IconLoader.getIcon("/scope/scratches.svg"); /** 16x16 */ public static final Icon Tests = IconLoader.getIcon("/scope/tests.svg"); } public final static class Toolbar { /** 16x16 */ public static final Icon Filterdups = IconLoader.getIcon("/toolbar/filterdups.svg"); /** 16x16 */ public static final Icon Unknown = IconLoader.getIcon("/toolbar/unknown.svg"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.GroupByPackage */ @SuppressWarnings("unused") @Deprecated public static final Icon Folders = AllIcons.Actions.GroupByPackage; } public final static class ToolbarDecorator { /** 16x16 */ public static final Icon AddBlankLine = IconLoader.getIcon("/toolbarDecorator/addBlankLine.svg"); /** 16x16 */ public static final Icon AddClass = IconLoader.getIcon("/toolbarDecorator/addClass.svg"); /** 16x16 */ public static final Icon AddFolder = IconLoader.getIcon("/toolbarDecorator/addFolder.svg"); /** 16x16 */ public static final Icon AddIcon = IconLoader.getIcon("/toolbarDecorator/addIcon.svg"); /** 16x16 */ public static final Icon AddJira = IconLoader.getIcon("/toolbarDecorator/addJira.svg"); /** 16x16 */ public static final Icon AddLink = IconLoader.getIcon("/toolbarDecorator/addLink.svg"); /** 16x16 */ public static final Icon AddPattern = IconLoader.getIcon("/toolbarDecorator/addPattern.svg"); /** 16x16 */ public static final Icon AddRemoteDatasource = IconLoader.getIcon("/toolbarDecorator/addRemoteDatasource.svg"); /** 16x16 */ public static final Icon AddYouTrack = IconLoader.getIcon("/toolbarDecorator/addYouTrack.svg"); /** 16x16 */ public static final Icon Export = IconLoader.getIcon("/toolbarDecorator/export.svg"); /** 16x16 */ public static final Icon Import = IconLoader.getIcon("/toolbarDecorator/import.svg"); public final static class Mac { /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.Add */ @SuppressWarnings("unused") @Deprecated public static final Icon Add = AllIcons.General.Add; /** @deprecated to be removed in IDEA 2020 - use AllIcons.ToolbarDecorator.AddBlankLine */ @SuppressWarnings("unused") @Deprecated public static final Icon AddBlankLine = AllIcons.ToolbarDecorator.AddBlankLine; /** @deprecated to be removed in IDEA 2020 - use AllIcons.ToolbarDecorator.AddClass */ @SuppressWarnings("unused") @Deprecated public static final Icon AddClass = AllIcons.ToolbarDecorator.AddClass; /** @deprecated to be removed in IDEA 2020 - use AllIcons.ToolbarDecorator.AddFolder */ @SuppressWarnings("unused") @Deprecated public static final Icon AddFolder = AllIcons.ToolbarDecorator.AddFolder; /** @deprecated to be removed in IDEA 2020 - use AllIcons.ToolbarDecorator.AddIcon */ @SuppressWarnings("unused") @Deprecated public static final Icon AddIcon = AllIcons.ToolbarDecorator.AddIcon; /** @deprecated to be removed in IDEA 2020 - use AllIcons.ToolbarDecorator.AddJira */ @SuppressWarnings("unused") @Deprecated public static final Icon AddJira = AllIcons.ToolbarDecorator.AddJira; /** @deprecated to be removed in IDEA 2020 - use AllIcons.ToolbarDecorator.AddLink */ @SuppressWarnings("unused") @Deprecated public static final Icon AddLink = AllIcons.ToolbarDecorator.AddLink; /** @deprecated to be removed in IDEA 2020 - use AllIcons.ToolbarDecorator.AddFolder */ @SuppressWarnings("unused") @Deprecated public static final Icon AddPackage = AllIcons.ToolbarDecorator.AddFolder; /** @deprecated to be removed in IDEA 2020 - use AllIcons.ToolbarDecorator.AddPattern */ @SuppressWarnings("unused") @Deprecated public static final Icon AddPattern = AllIcons.ToolbarDecorator.AddPattern; /** @deprecated to be removed in IDEA 2020 - use AllIcons.ToolbarDecorator.AddRemoteDatasource */ @SuppressWarnings("unused") @Deprecated public static final Icon AddRemoteDatasource = AllIcons.ToolbarDecorator.AddRemoteDatasource; /** @deprecated to be removed in IDEA 2020 - use AllIcons.ToolbarDecorator.AddYouTrack */ @SuppressWarnings("unused") @Deprecated public static final Icon AddYouTrack = AllIcons.ToolbarDecorator.AddYouTrack; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Analyze = IconLoader.getIcon("/toolbarDecorator/mac/analyze.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Edit */ @SuppressWarnings("unused") @Deprecated public static final Icon Edit = AllIcons.Actions.Edit; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.MoveDown */ @SuppressWarnings("unused") @Deprecated public static final Icon MoveDown = AllIcons.Actions.MoveDown; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.MoveUp */ @SuppressWarnings("unused") @Deprecated public static final Icon MoveUp = AllIcons.Actions.MoveUp; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.Remove */ @SuppressWarnings("unused") @Deprecated public static final Icon Remove = AllIcons.General.Remove; } /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.Add */ @SuppressWarnings("unused") @Deprecated public static final Icon Add = AllIcons.General.Add; /** @deprecated to be removed in IDEA 2020 - use AllIcons.ToolbarDecorator.AddFolder */ @SuppressWarnings("unused") @Deprecated public static final Icon AddPackage = AllIcons.ToolbarDecorator.AddFolder; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Analyze = IconLoader.getIcon("/toolbarDecorator/analyze.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Edit */ @SuppressWarnings("unused") @Deprecated public static final Icon Edit = AllIcons.Actions.Edit; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.MoveDown */ @SuppressWarnings("unused") @Deprecated public static final Icon MoveDown = AllIcons.Actions.MoveDown; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.MoveUp */ @SuppressWarnings("unused") @Deprecated public static final Icon MoveUp = AllIcons.Actions.MoveUp; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.Remove */ @SuppressWarnings("unused") @Deprecated public static final Icon Remove = AllIcons.General.Remove; } public final static class Toolwindows { /** 13x13 */ public static final Icon Documentation = IconLoader.getIcon("/toolwindows/documentation.svg"); /** 13x13 */ public static final Icon Problems = IconLoader.getIcon("/toolwindows/problems.svg"); /** 13x13 */ public static final Icon ProblemsEmpty = IconLoader.getIcon("/toolwindows/problemsEmpty.svg"); /** 13x13 */ public static final Icon ToolWindowAnt = IconLoader.getIcon("/toolwindows/toolWindowAnt.svg"); /** 13x13 */ public static final Icon ToolWindowBuild = IconLoader.getIcon("/toolwindows/toolWindowBuild.svg"); /** 13x13 */ public static final Icon ToolWindowChanges = IconLoader.getIcon("/toolwindows/toolWindowChanges.svg"); /** 13x13 */ public static final Icon ToolWindowCommander = IconLoader.getIcon("/toolwindows/toolWindowCommander.svg"); /** 13x13 */ public static final Icon ToolWindowCoverage = IconLoader.getIcon("/toolwindows/toolWindowCoverage.svg"); /** 13x13 */ public static final Icon ToolWindowDebugger = IconLoader.getIcon("/toolwindows/toolWindowDebugger.svg"); /** 13x13 */ public static final Icon ToolWindowFavorites = IconLoader.getIcon("/toolwindows/toolWindowFavorites.svg"); /** 13x13 */ public static final Icon ToolWindowFind = IconLoader.getIcon("/toolwindows/toolWindowFind.svg"); /** 13x13 */ public static final Icon ToolWindowHierarchy = IconLoader.getIcon("/toolwindows/toolWindowHierarchy.svg"); /** 13x13 */ public static final Icon ToolWindowInspection = IconLoader.getIcon("/toolwindows/toolWindowInspection.svg"); /** 13x13 */ public static final Icon ToolWindowMessages = IconLoader.getIcon("/toolwindows/toolWindowMessages.svg"); /** 13x13 */ public static final Icon ToolWindowModuleDependencies = IconLoader.getIcon("/toolwindows/toolWindowModuleDependencies.svg"); /** 13x13 */ public static final Icon ToolWindowPalette = IconLoader.getIcon("/toolwindows/toolWindowPalette.svg"); /** 13x13 */ public static final Icon ToolWindowPreview = IconLoader.getIcon("/toolwindows/toolWindowPreview.png"); /** 13x13 */ public static final Icon ToolWindowProfiler = IconLoader.getIcon("/toolwindows/toolWindowProfiler.svg"); /** 13x13 */ public static final Icon ToolWindowProject = IconLoader.getIcon("/toolwindows/toolWindowProject.svg"); /** 13x13 */ public static final Icon ToolWindowRun = IconLoader.getIcon("/toolwindows/toolWindowRun.svg"); /** 13x13 */ public static final Icon ToolWindowStructure = IconLoader.getIcon("/toolwindows/toolWindowStructure.svg"); /** 13x13 */ public static final Icon ToolWindowTodo = IconLoader.getIcon("/toolwindows/toolWindowTodo.svg"); /** 13x13 */ public static final Icon ToolWindowUIDesigner = IconLoader.getIcon("/toolwindows/toolWindowUIDesigner.svg"); /** 13x13 */ public static final Icon WebToolWindow = IconLoader.getIcon("/toolwindows/webToolWindow.svg"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon ToolWindowCvs = IconLoader.getIcon("/toolwindows/toolWindowCvs.png"); } public final static class Vcs { /** 16x16 */ public static final Icon Arrow_left = IconLoader.getIcon("/vcs/arrow_left.svg"); /** 16x16 */ public static final Icon Arrow_right = IconLoader.getIcon("/vcs/arrow_right.svg"); /** 16x16 */ public static final Icon Branch = IconLoader.getIcon("/vcs/branch.svg"); /** 16x16 */ public static final Icon Changelist = IconLoader.getIcon("/vcs/changelist.svg"); /** 16x16 */ public static final Icon CommitNode = IconLoader.getIcon("/vcs/commitNode.svg"); /** 16x16 */ public static final Icon Equal = IconLoader.getIcon("/vcs/equal.svg"); /** 16x16 */ public static final Icon Folders = IconLoader.getIcon("/vcs/folders.svg"); /** 16x16 */ public static final Icon History = IconLoader.getIcon("/vcs/history.svg"); /** 16x16 */ public static final Icon Ignore_file = IconLoader.getIcon("/vcs/ignore_file.svg"); /** 16x16 */ public static final Icon Merge = IconLoader.getIcon("/vcs/merge.svg"); /** 16x16 */ public static final Icon Not_equal = IconLoader.getIcon("/vcs/not_equal.svg"); /** 16x16 */ public static final Icon Patch = IconLoader.getIcon("/vcs/patch.svg"); /** 16x16 */ public static final Icon Patch_applied = IconLoader.getIcon("/vcs/patch_applied.svg"); /** 16x16 */ public static final Icon Patch_file = IconLoader.getIcon("/vcs/patch_file.svg"); /** 16x16 */ public static final Icon Push = IconLoader.getIcon("/vcs/push.svg"); /** 16x16 */ public static final Icon Remove = IconLoader.getIcon("/vcs/remove.svg"); /** 16x16 */ public static final Icon Shelve = IconLoader.getIcon("/vcs/Shelve.svg"); /** 16x16 */ public static final Icon ShelveSilent = IconLoader.getIcon("/vcs/shelveSilent.svg"); /** 16x16 */ public static final Icon ShowUnversionedFiles = IconLoader.getIcon("/vcs/ShowUnversionedFiles.svg"); /** 16x16 */ public static final Icon Unshelve = IconLoader.getIcon("/vcs/Unshelve.svg"); /** 16x16 */ public static final Icon UnshelveSilent = IconLoader.getIcon("/vcs/unshelveSilent.svg"); public final static class Vendors { /** 16x16 */ public static final Icon Github = IconLoader.getIcon("/vcs/vendors/github.svg"); } /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon CheckSpelling = IconLoader.getIcon("/vcs/checkSpelling.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Vcs.Folders */ @SuppressWarnings("unused") @Deprecated public static final Icon MapBase = AllIcons.Vcs.Folders; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.ShowAsTree */ @SuppressWarnings("unused") @Deprecated public static final Icon MergeSourcesTree = AllIcons.Actions.ShowAsTree; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon ResetStrip = IconLoader.getIcon("/vcs/resetStrip.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon RestoreDefaultSize = IconLoader.getIcon("/vcs/restoreDefaultSize.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon StripDown = IconLoader.getIcon("/vcs/stripDown.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon StripNull = IconLoader.getIcon("/vcs/stripNull.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon StripUp = IconLoader.getIcon("/vcs/stripUp.png"); } public final static class Webreferences { /** 16x16 */ public static final Icon Server = IconLoader.getIcon("/webreferences/server.svg"); } public final static class Welcome { /** 32x32 */ public static final Icon CreateDesktopEntry = IconLoader.getIcon("/welcome/createDesktopEntry.png"); /** 16x16 */ public static final Icon CreateNewProject = IconLoader.getIcon("/welcome/createNewProject.svg"); /** 16x16 */ public static final Icon FromVCS = IconLoader.getIcon("/welcome/fromVCS.svg"); public final static class Project { /** 10x10 */ public static final Icon Remove_hover = IconLoader.getIcon("/welcome/project/remove-hover.svg"); /** 10x10 */ public static final Icon Remove = IconLoader.getIcon("/welcome/project/remove.svg"); } /** 32x32 */ public static final Icon Register = IconLoader.getIcon("/welcome/register.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.ToolbarDecorator.Import */ @SuppressWarnings("unused") @Deprecated public static final Icon CreateNewProjectfromExistingFiles = AllIcons.ToolbarDecorator.Import; /** @deprecated to be removed in IDEA 2020 - use AllIcons.ToolbarDecorator.Import */ @SuppressWarnings("unused") @Deprecated public static final Icon ImportProject = AllIcons.ToolbarDecorator.Import; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Menu_open */ @SuppressWarnings("unused") @Deprecated public static final Icon OpenProject = AllIcons.Actions.Menu_open; } public final static class Windows { /** 16x16 */ public static final Icon CloseActive = IconLoader.getIcon("/windows/closeActive.svg"); /** 16x16 */ public static final Icon CloseHover = IconLoader.getIcon("/windows/closeHover.svg"); /** 16x16 */ public static final Icon CloseInactive = IconLoader.getIcon("/windows/closeInactive.svg"); /** 16x16 */ public static final Icon CloseSmall = IconLoader.getIcon("/windows/closeSmall.svg"); /** 16x16 */ public static final Icon Help = IconLoader.getIcon("/windows/help.svg"); /** 16x16 */ public static final Icon HelpButton = IconLoader.getIcon("/windows/helpButton.svg"); /** 16x16 */ public static final Icon HelpButtonInactive = IconLoader.getIcon("/windows/helpButtonInactive.svg"); /** 16x16 */ public static final Icon HelpInactive = IconLoader.getIcon("/windows/helpInactive.svg"); /** 16x16 */ public static final Icon Maximize = IconLoader.getIcon("/windows/maximize.svg"); /** 16x16 */ public static final Icon MaximizeInactive = IconLoader.getIcon("/windows/maximizeInactive.svg"); /** 16x16 */ public static final Icon MaximizeSmall = IconLoader.getIcon("/windows/maximizeSmall.svg"); /** 16x16 */ public static final Icon Minimize = IconLoader.getIcon("/windows/minimize.svg"); /** 16x16 */ public static final Icon MinimizeInactive = IconLoader.getIcon("/windows/minimizeInactive.svg"); /** 16x16 */ public static final Icon MinimizeSmall = IconLoader.getIcon("/windows/minimizeSmall.svg"); /** 16x16 */ public static final Icon Restore = IconLoader.getIcon("/windows/restore.svg"); /** 16x16 */ public static final Icon RestoreInactive = IconLoader.getIcon("/windows/restoreInactive.svg"); /** 16x16 */ public static final Icon RestoreSmall = IconLoader.getIcon("/windows/restoreSmall.svg"); } public final static class Xml { public final static class Browsers { /** 16x16 */ public static final Icon Canary16 = IconLoader.getIcon("/xml/browsers/canary16.svg"); /** 16x16 */ public static final Icon Chrome16 = IconLoader.getIcon("/xml/browsers/chrome16.svg"); /** 16x16 */ public static final Icon Chromium16 = IconLoader.getIcon("/xml/browsers/chromium16.svg"); /** 16x16 */ public static final Icon Edge16 = IconLoader.getIcon("/xml/browsers/edge16.svg"); /** 16x16 */ public static final Icon Explorer16 = IconLoader.getIcon("/xml/browsers/explorer16.svg"); /** 16x16 */ public static final Icon Firefox16 = IconLoader.getIcon("/xml/browsers/firefox16.svg"); /** 16x16 */ public static final Icon Nwjs16 = IconLoader.getIcon("/xml/browsers/nwjs16.svg"); /** 16x16 */ public static final Icon Opera16 = IconLoader.getIcon("/xml/browsers/opera16.svg"); /** 16x16 */ public static final Icon Safari16 = IconLoader.getIcon("/xml/browsers/safari16.svg"); /** 16x16 */ public static final Icon Yandex16 = IconLoader.getIcon("/xml/browsers/yandex16.svg"); } /** 16x16 */ public static final Icon Css_class = IconLoader.getIcon("/xml/css_class.svg"); /** 16x16 */ public static final Icon Html5 = IconLoader.getIcon("/xml/html5.svg"); /** 16x16 */ public static final Icon Html_id = IconLoader.getIcon("/xml/html_id.svg"); } }
platform/util/src/com/intellij/icons/AllIcons.java
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.icons; import com.intellij.openapi.util.IconLoader; import javax.swing.*; /** * NOTE THIS FILE IS AUTO-GENERATED * DO NOT EDIT IT BY HAND, run "Generate icon classes" configuration instead */ public class AllIcons { public final static class Actions { /** 16x16 */ public static final Icon AddMulticaret = IconLoader.getIcon("/actions/AddMulticaret.svg"); /** 16x16 */ public static final Icon Annotate = IconLoader.getIcon("/actions/annotate.svg"); /** 16x16 */ public static final Icon Back = IconLoader.getIcon("/actions/back.svg"); /** 16x16 */ public static final Icon Cancel = IconLoader.getIcon("/actions/cancel.svg"); /** 16x16 */ public static final Icon ChangeView = IconLoader.getIcon("/actions/changeView.svg"); /** 12x12 */ public static final Icon Checked = IconLoader.getIcon("/actions/checked.svg"); /** 12x12 */ public static final Icon Checked_selected = IconLoader.getIcon("/actions/checked_selected.svg"); /** 16x16 */ public static final Icon CheckMulticaret = IconLoader.getIcon("/actions/CheckMulticaret.svg"); /** 16x16 */ public static final Icon CheckOut = IconLoader.getIcon("/actions/checkOut.svg"); /** 16x16 */ public static final Icon Close = IconLoader.getIcon("/actions/close.svg"); /** 16x16 */ public static final Icon CloseHovered = IconLoader.getIcon("/actions/closeHovered.svg"); /** 16x16 */ public static final Icon Collapseall = IconLoader.getIcon("/actions/collapseall.svg"); /** 16x16 */ public static final Icon Colors = IconLoader.getIcon("/actions/colors.svg"); /** 16x16 */ public static final Icon Commit = IconLoader.getIcon("/actions/commit.svg"); /** 16x16 */ public static final Icon Compile = IconLoader.getIcon("/actions/compile.svg"); /** 16x16 */ public static final Icon Copy = IconLoader.getIcon("/actions/copy.svg"); /** 16x16 */ public static final Icon DiagramDiff = IconLoader.getIcon("/actions/diagramDiff.svg"); /** 16x16 */ public static final Icon Diff = IconLoader.getIcon("/actions/diff.svg"); /** 16x16 */ public static final Icon DiffWithClipboard = IconLoader.getIcon("/actions/diffWithClipboard.svg"); /** 16x16 */ public static final Icon Download = IconLoader.getIcon("/actions/download.svg"); /** 16x16 */ public static final Icon Dump = IconLoader.getIcon("/actions/dump.svg"); /** 16x16 */ public static final Icon Edit = IconLoader.getIcon("/actions/edit.svg"); /** 16x16 */ public static final Icon EditSource = IconLoader.getIcon("/actions/editSource.svg"); /** 16x16 */ public static final Icon Execute = IconLoader.getIcon("/actions/execute.svg"); /** 16x16 */ public static final Icon Exit = IconLoader.getIcon("/actions/exit.svg"); /** 16x16 */ public static final Icon Expandall = IconLoader.getIcon("/actions/expandall.svg"); /** 16x16 */ public static final Icon Find = IconLoader.getIcon("/actions/find.svg"); /** 16x16 */ public static final Icon ForceRefresh = IconLoader.getIcon("/actions/forceRefresh.svg"); /** 16x16 */ public static final Icon Forward = IconLoader.getIcon("/actions/forward.svg"); /** 16x16 */ public static final Icon GC = IconLoader.getIcon("/actions/gc.svg"); /** 16x16 */ public static final Icon GroupBy = IconLoader.getIcon("/actions/groupBy.svg"); /** 16x16 */ public static final Icon GroupByClass = IconLoader.getIcon("/actions/GroupByClass.svg"); /** 16x16 */ public static final Icon GroupByFile = IconLoader.getIcon("/actions/GroupByFile.svg"); /** 16x16 */ public static final Icon GroupByMethod = IconLoader.getIcon("/actions/groupByMethod.svg"); /** 16x16 */ public static final Icon GroupByModule = IconLoader.getIcon("/actions/GroupByModule.svg"); /** 16x16 */ public static final Icon GroupByModuleGroup = IconLoader.getIcon("/actions/GroupByModuleGroup.svg"); /** 16x16 */ public static final Icon GroupByPackage = IconLoader.getIcon("/actions/GroupByPackage.svg"); /** 16x16 */ public static final Icon GroupByPrefix = IconLoader.getIcon("/actions/GroupByPrefix.svg"); /** 16x16 */ public static final Icon GroupByTestProduction = IconLoader.getIcon("/actions/groupByTestProduction.svg"); /** 16x16 */ public static final Icon Help = IconLoader.getIcon("/actions/help.svg"); /** 16x16 */ public static final Icon Highlighting = IconLoader.getIcon("/actions/highlighting.svg"); /** 16x16 */ public static final Icon Install = IconLoader.getIcon("/actions/install.svg"); /** 16x16 */ public static final Icon IntentionBulb = IconLoader.getIcon("/actions/intentionBulb.svg"); /** 16x16 */ public static final Icon Lightning = IconLoader.getIcon("/actions/lightning.svg"); /** 16x16 */ public static final Icon ListChanges = IconLoader.getIcon("/actions/listChanges.svg"); /** 16x16 */ public static final Icon ListFiles = IconLoader.getIcon("/actions/listFiles.svg"); /** 16x16 */ public static final Icon Menu_cut = IconLoader.getIcon("/actions/menu-cut.svg"); /** 16x16 */ public static final Icon Menu_open = IconLoader.getIcon("/actions/menu-open.svg"); /** 16x16 */ public static final Icon Menu_paste = IconLoader.getIcon("/actions/menu-paste.svg"); /** 16x16 */ public static final Icon Menu_saveall = IconLoader.getIcon("/actions/menu-saveall.svg"); /** 16x16 */ public static final Icon ModuleDirectory = IconLoader.getIcon("/actions/moduleDirectory.svg"); /** 16x16 */ public static final Icon More = IconLoader.getIcon("/actions/more.svg"); /** 12x12 */ public static final Icon Move_to_button = IconLoader.getIcon("/actions/move-to-button.svg"); /** 16x16 */ public static final Icon MoveDown = IconLoader.getIcon("/actions/moveDown.svg"); /** 16x16 */ public static final Icon MoveTo2 = IconLoader.getIcon("/actions/MoveTo2.svg"); /** 16x16 */ public static final Icon MoveToBottomLeft = IconLoader.getIcon("/actions/moveToBottomLeft.svg"); /** 16x16 */ public static final Icon MoveToBottomRight = IconLoader.getIcon("/actions/moveToBottomRight.svg"); /** 16x16 */ public static final Icon MoveToLeftBottom = IconLoader.getIcon("/actions/moveToLeftBottom.svg"); /** 16x16 */ public static final Icon MoveToLeftTop = IconLoader.getIcon("/actions/moveToLeftTop.svg"); /** 16x16 */ public static final Icon MoveToRightBottom = IconLoader.getIcon("/actions/moveToRightBottom.svg"); /** 16x16 */ public static final Icon MoveToRightTop = IconLoader.getIcon("/actions/moveToRightTop.svg"); /** 16x16 */ public static final Icon MoveToTopLeft = IconLoader.getIcon("/actions/moveToTopLeft.svg"); /** 16x16 */ public static final Icon MoveToTopRight = IconLoader.getIcon("/actions/moveToTopRight.svg"); /** 16x16 */ public static final Icon MoveUp = IconLoader.getIcon("/actions/moveUp.svg"); /** 16x16 */ public static final Icon New = IconLoader.getIcon("/actions/new.svg"); /** 16x16 */ public static final Icon NewFolder = IconLoader.getIcon("/actions/newFolder.svg"); /** 16x16 */ public static final Icon NextOccurence = IconLoader.getIcon("/actions/nextOccurence.svg"); /** 16x16 */ public static final Icon OfflineMode = IconLoader.getIcon("/actions/offlineMode.svg"); /** 16x16 */ public static final Icon OpenNewTab = IconLoader.getIcon("/actions/openNewTab.svg"); /** 16x16 */ public static final Icon Pause = IconLoader.getIcon("/actions/pause.svg"); /** 16x16 */ public static final Icon Play_back = IconLoader.getIcon("/actions/play_back.svg"); /** 16x16 */ public static final Icon Play_first = IconLoader.getIcon("/actions/play_first.svg"); /** 16x16 */ public static final Icon Play_forward = IconLoader.getIcon("/actions/play_forward.svg"); /** 16x16 */ public static final Icon Play_last = IconLoader.getIcon("/actions/play_last.svg"); /** 16x16 */ public static final Icon PopFrame = IconLoader.getIcon("/actions/popFrame.svg"); /** 16x16 */ public static final Icon Preview = IconLoader.getIcon("/actions/preview.svg"); /** 16x16 */ public static final Icon PreviewDetails = IconLoader.getIcon("/actions/previewDetails.svg"); /** 16x16 */ public static final Icon PreviewDetailsVertically = IconLoader.getIcon("/actions/previewDetailsVertically.svg"); /** 16x16 */ public static final Icon PreviousOccurence = IconLoader.getIcon("/actions/previousOccurence.svg"); /** 16x16 */ public static final Icon Profile = IconLoader.getIcon("/actions/profile.svg"); /** 16x16 */ public static final Icon ProfileBlue = IconLoader.getIcon("/actions/profileBlue.svg"); /** 16x16 */ public static final Icon ProfileCPU = IconLoader.getIcon("/actions/profileCPU.svg"); /** 16x16 */ public static final Icon ProfileMemory = IconLoader.getIcon("/actions/profileMemory.svg"); /** 16x16 */ public static final Icon ProfileRed = IconLoader.getIcon("/actions/profileRed.svg"); /** 16x16 */ public static final Icon ProfileYellow = IconLoader.getIcon("/actions/profileYellow.svg"); /** 16x16 */ public static final Icon ProjectDirectory = IconLoader.getIcon("/actions/projectDirectory.svg"); /** 16x16 */ public static final Icon Properties = IconLoader.getIcon("/actions/properties.svg"); /** 16x16 */ public static final Icon QuickfixBulb = IconLoader.getIcon("/actions/quickfixBulb.svg"); /** 16x16 */ public static final Icon QuickfixOffBulb = IconLoader.getIcon("/actions/quickfixOffBulb.svg"); /** 16x16 */ public static final Icon RealIntentionBulb = IconLoader.getIcon("/actions/realIntentionBulb.svg"); /** 16x16 */ public static final Icon Redo = IconLoader.getIcon("/actions/redo.svg"); /** 16x16 */ public static final Icon RefactoringBulb = IconLoader.getIcon("/actions/refactoringBulb.svg"); /** 16x16 */ public static final Icon Refresh = IconLoader.getIcon("/actions/refresh.svg"); /** 16x16 */ public static final Icon RemoveMulticaret = IconLoader.getIcon("/actions/RemoveMulticaret.svg"); /** 16x16 */ public static final Icon Replace = IconLoader.getIcon("/actions/replace.svg"); /** 16x16 */ public static final Icon Rerun = IconLoader.getIcon("/actions/rerun.svg"); /** 16x16 */ public static final Icon Restart = IconLoader.getIcon("/actions/restart.svg"); /** 16x16 */ public static final Icon RestartDebugger = IconLoader.getIcon("/actions/restartDebugger.svg"); /** 16x16 */ public static final Icon Resume = IconLoader.getIcon("/actions/resume.svg"); /** 16x16 */ public static final Icon Rollback = IconLoader.getIcon("/actions/rollback.svg"); /** 16x16 */ public static final Icon Run_anything = IconLoader.getIcon("/actions/run_anything.svg"); /** 16x16 */ public static final Icon RunToCursor = IconLoader.getIcon("/actions/runToCursor.svg"); /** 16x16 */ public static final Icon Scratch = IconLoader.getIcon("/actions/scratch.svg"); /** 16x16 */ public static final Icon Search = IconLoader.getIcon("/actions/search.svg"); /** 16x16 */ public static final Icon SearchNewLine = IconLoader.getIcon("/actions/searchNewLine.svg"); /** 16x16 */ public static final Icon SearchNewLineHover = IconLoader.getIcon("/actions/searchNewLineHover.svg"); /** 16x16 */ public static final Icon SearchWithHistory = IconLoader.getIcon("/actions/searchWithHistory.svg"); /** 16x16 */ public static final Icon Selectall = IconLoader.getIcon("/actions/selectall.svg"); /** 16x16 */ public static final Icon SetDefault = IconLoader.getIcon("/actions/setDefault.svg"); /** 14x14 */ public static final Icon Share = IconLoader.getIcon("/actions/share.png"); /** 16x16 */ public static final Icon ShortcutFilter = IconLoader.getIcon("/actions/shortcutFilter.svg"); /** 16x16 */ public static final Icon Show = IconLoader.getIcon("/actions/show.svg"); /** 16x16 */ public static final Icon ShowAsTree = IconLoader.getIcon("/actions/showAsTree.svg"); /** 16x16 */ public static final Icon ShowHiddens = IconLoader.getIcon("/actions/showHiddens.svg"); /** 16x16 */ public static final Icon ShowImportStatements = IconLoader.getIcon("/actions/showImportStatements.svg"); /** 16x16 */ public static final Icon ShowReadAccess = IconLoader.getIcon("/actions/showReadAccess.svg"); /** 16x16 */ public static final Icon ShowWriteAccess = IconLoader.getIcon("/actions/showWriteAccess.svg"); /** 16x16 */ public static final Icon SplitHorizontally = IconLoader.getIcon("/actions/splitHorizontally.svg"); /** 16x16 */ public static final Icon SplitVertically = IconLoader.getIcon("/actions/splitVertically.svg"); /** 16x16 */ public static final Icon StartDebugger = IconLoader.getIcon("/actions/startDebugger.svg"); /** 16x16 */ public static final Icon StartMemoryProfile = IconLoader.getIcon("/actions/startMemoryProfile.svg"); /** 16x16 */ public static final Icon StepOut = IconLoader.getIcon("/actions/stepOut.svg"); /** 16x16 */ public static final Icon StepOutCodeBlock = IconLoader.getIcon("/actions/stepOutCodeBlock.svg"); /** 16x16 */ public static final Icon Stub = IconLoader.getIcon("/actions/stub.svg"); /** 16x16 */ public static final Icon Suspend = IconLoader.getIcon("/actions/suspend.svg"); /** 16x16 */ public static final Icon SwapPanels = IconLoader.getIcon("/actions/swapPanels.svg"); /** 16x16 */ public static final Icon SynchronizeScrolling = IconLoader.getIcon("/actions/synchronizeScrolling.svg"); /** 16x16 */ public static final Icon SyncPanels = IconLoader.getIcon("/actions/syncPanels.svg"); /** 16x16 */ public static final Icon ToggleSoftWrap = IconLoader.getIcon("/actions/toggleSoftWrap.svg"); /** 16x16 */ public static final Icon TraceInto = IconLoader.getIcon("/actions/traceInto.svg"); /** 16x16 */ public static final Icon TraceOver = IconLoader.getIcon("/actions/traceOver.svg"); /** 16x16 */ public static final Icon Undo = IconLoader.getIcon("/actions/undo.svg"); /** 16x16 */ public static final Icon Uninstall = IconLoader.getIcon("/actions/uninstall.svg"); /** 16x16 */ public static final Icon Unselectall = IconLoader.getIcon("/actions/unselectall.svg"); /** 14x14 */ public static final Icon Unshare = IconLoader.getIcon("/actions/unshare.png"); /** 16x16 */ public static final Icon Upload = IconLoader.getIcon("/actions/upload.svg"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon AddFacesSupport = IconLoader.getIcon("/actions/addFacesSupport.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon AllLeft = IconLoader.getIcon("/actions/allLeft.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon AllRight = IconLoader.getIcon("/actions/allRight.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.PreviousOccurence */ @SuppressWarnings("unused") @Deprecated public static final Icon Browser_externalJavaDoc = AllIcons.Actions.PreviousOccurence; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Checked */ @SuppressWarnings("unused") @Deprecated public static final Icon Checked_small = AllIcons.Actions.Checked; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Checked_selected */ @SuppressWarnings("unused") @Deprecated public static final Icon Checked_small_selected = AllIcons.Actions.Checked_selected; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Checked */ @SuppressWarnings("unused") @Deprecated public static final Icon CheckedBlack = AllIcons.Actions.Checked; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Checked */ @SuppressWarnings("unused") @Deprecated public static final Icon CheckedGrey = AllIcons.Actions.Checked; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.CloseHovered */ @SuppressWarnings("unused") @Deprecated public static final Icon Clean = AllIcons.Actions.CloseHovered; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Close */ @SuppressWarnings("unused") @Deprecated public static final Icon CleanLight = AllIcons.Actions.Close; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Clear = IconLoader.getIcon("/actions/clear.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Close */ @SuppressWarnings("unused") @Deprecated public static final Icon CloseNew = AllIcons.Actions.Close; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.CloseHovered */ @SuppressWarnings("unused") @Deprecated public static final Icon CloseNewHovered = AllIcons.Actions.CloseHovered; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.IntentionBulb */ @SuppressWarnings("unused") @Deprecated public static final Icon CreateFromUsage = AllIcons.Actions.IntentionBulb; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon CreatePatch = IconLoader.getIcon("/actions/createPatch.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Close */ @SuppressWarnings("unused") @Deprecated public static final Icon Cross = AllIcons.Actions.Close; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Cancel */ @SuppressWarnings("unused") @Deprecated public static final Icon Delete = AllIcons.Actions.Cancel; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Diff */ @SuppressWarnings("unused") @Deprecated public static final Icon DiffPreview = AllIcons.Actions.Diff; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Diff */ @SuppressWarnings("unused") @Deprecated public static final Icon DiffWithCurrent = AllIcons.Actions.Diff; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowDown */ @SuppressWarnings("unused") @Deprecated public static final Icon Down = AllIcons.General.ArrowDown; /** @deprecated to be removed in IDEA 2020 - use J2EEIcons.ErDiagram */ @SuppressWarnings("unused") @Deprecated public static final Icon ErDiagram = IconLoader.getIcon("/actions/erDiagram.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.Remove */ @SuppressWarnings("unused") @Deprecated public static final Icon Exclude = AllIcons.General.Remove; /** @deprecated to be removed in IDEA 2020 - use AllIcons.ToolbarDecorator.Export */ @SuppressWarnings("unused") @Deprecated public static final Icon Export = AllIcons.ToolbarDecorator.Export; @SuppressWarnings("unused") @Deprecated public static final Icon FileStatus = IconLoader.getIcon("/actions/fileStatus.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.Filter */ @SuppressWarnings("unused") @Deprecated public static final Icon Filter_small = AllIcons.General.Filter; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Find */ @SuppressWarnings("unused") @Deprecated public static final Icon FindPlain = AllIcons.Actions.Find; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon FindWhite = IconLoader.getIcon("/actions/findWhite.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Download */ @SuppressWarnings("unused") @Deprecated public static final Icon Get = AllIcons.Actions.Download; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowLeft */ @SuppressWarnings("unused") @Deprecated public static final Icon Left = AllIcons.General.ArrowLeft; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Find */ @SuppressWarnings("unused") @Deprecated public static final Icon Menu_find = AllIcons.Actions.Find; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Help */ @SuppressWarnings("unused") @Deprecated public static final Icon Menu_help = AllIcons.Actions.Help; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Replace */ @SuppressWarnings("unused") @Deprecated public static final Icon Menu_replace = AllIcons.Actions.Replace; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.HideToolWindow */ @SuppressWarnings("unused") @Deprecated public static final Icon Minimize = AllIcons.General.HideToolWindow; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Nodes.Module */ @SuppressWarnings("unused") @Deprecated public static final Icon Module = AllIcons.Nodes.Module; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Move_to_button */ @SuppressWarnings("unused") @Deprecated public static final Icon Move_to_button_top = AllIcons.Actions.Move_to_button; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.MoveTo2 */ @SuppressWarnings("unused") @Deprecated public static final Icon MoveToAnotherChangelist = AllIcons.Actions.MoveTo2; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.MoveTo2 */ @SuppressWarnings("unused") @Deprecated public static final Icon MoveToStandardPlace = AllIcons.Actions.MoveTo2; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Multicaret = IconLoader.getIcon("/actions/multicaret.svg"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Forward */ @SuppressWarnings("unused") @Deprecated public static final Icon Nextfile = AllIcons.Actions.Forward; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Back */ @SuppressWarnings("unused") @Deprecated public static final Icon Prevfile = AllIcons.Actions.Back; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon QuickList = IconLoader.getIcon("/actions/quickList.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon RealIntentionOffBulb = IconLoader.getIcon("/actions/realIntentionOffBulb.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Rollback */ @SuppressWarnings("unused") @Deprecated public static final Icon Reset_to_default = AllIcons.Actions.Rollback; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Rollback */ @SuppressWarnings("unused") @Deprecated public static final Icon Reset = AllIcons.Actions.Rollback; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Uninstall */ @SuppressWarnings("unused") @Deprecated public static final Icon Reset_to_empty = AllIcons.Actions.Uninstall; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowRight */ @SuppressWarnings("unused") @Deprecated public static final Icon Right = AllIcons.General.ArrowRight; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Preview */ @SuppressWarnings("unused") @Deprecated public static final Icon ShowChangesOnly = AllIcons.Actions.Preview; @SuppressWarnings("unused") @Deprecated public static final Icon ShowViewer = IconLoader.getIcon("/actions/showViewer.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.MoveUp */ @SuppressWarnings("unused") @Deprecated public static final Icon SortAsc = AllIcons.Actions.MoveUp; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.MoveDown */ @SuppressWarnings("unused") @Deprecated public static final Icon SortDesc = AllIcons.Actions.MoveDown; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.SetDefault */ @SuppressWarnings("unused") @Deprecated public static final Icon Submit1 = AllIcons.Actions.SetDefault; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Refresh */ @SuppressWarnings("unused") @Deprecated public static final Icon SynchronizeFS = AllIcons.Actions.Refresh; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowUp */ @SuppressWarnings("unused") @Deprecated public static final Icon UP = AllIcons.General.ArrowUp; } public final static class CodeStyle { /** 16x16 */ public static final Icon AddNewSectionRule = IconLoader.getIcon("/codeStyle/AddNewSectionRule.svg"); public final static class Mac { /** @deprecated to be removed in IDEA 2020 - use AllIcons.CodeStyle.AddNewSectionRule */ @SuppressWarnings("unused") @Deprecated public static final Icon AddNewSectionRule = AllIcons.CodeStyle.AddNewSectionRule; } /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.GearPlain */ @SuppressWarnings("unused") @Deprecated public static final Icon Gear = AllIcons.General.GearPlain; } public final static class Css { /** @deprecated use 'icons.CssIcons' from 'intellij.css' module instead */ @SuppressWarnings("unused") @Deprecated public static final Icon Atrule = IconLoader.getIcon("/css/atrule.png"); /** @deprecated use 'icons.CssIcons' from 'intellij.css' module instead */ @SuppressWarnings("unused") @Deprecated public static final Icon Import = IconLoader.getIcon("/css/import.png"); /** @deprecated use 'icons.CssIcons' from 'intellij.css' module instead */ @SuppressWarnings("unused") @Deprecated public static final Icon Property = IconLoader.getIcon("/css/property.png"); } public final static class Darcula { @SuppressWarnings("unused") @Deprecated public static final Icon DoubleComboArrow = IconLoader.getIcon("/darcula/doubleComboArrow.png"); @SuppressWarnings("unused") @Deprecated public static final Icon TreeNodeCollapsed = IconLoader.getIcon("/darcula/treeNodeCollapsed.png"); @SuppressWarnings("unused") @Deprecated public static final Icon TreeNodeExpanded = IconLoader.getIcon("/darcula/treeNodeExpanded.png"); } public final static class Debugger { public final static class Actions { /** 16x16 */ public static final Icon Force_run_to_cursor = IconLoader.getIcon("/debugger/actions/force_run_to_cursor.svg"); /** 16x16 */ public static final Icon Force_step_into = IconLoader.getIcon("/debugger/actions/force_step_into.svg"); /** 16x16 */ public static final Icon Force_step_over = IconLoader.getIcon("/debugger/actions/force_step_over.svg"); } /** 16x16 */ public static final Icon AddToWatch = IconLoader.getIcon("/debugger/addToWatch.svg"); /** 16x16 */ public static final Icon AttachToProcess = IconLoader.getIcon("/debugger/attachToProcess.svg"); /** 16x16 */ public static final Icon ClassLevelWatch = IconLoader.getIcon("/debugger/classLevelWatch.svg"); /** 16x16 */ public static final Icon Console = IconLoader.getIcon("/debugger/console.svg"); /** 16x16 */ public static final Icon Db_array = IconLoader.getIcon("/debugger/db_array.svg"); /** 16x16 */ public static final Icon Db_db_object = IconLoader.getIcon("/debugger/db_db_object.svg"); /** 12x12 */ public static final Icon Db_dep_field_breakpoint = IconLoader.getIcon("/debugger/db_dep_field_breakpoint.svg"); /** 12x12 */ public static final Icon Db_dep_line_breakpoint = IconLoader.getIcon("/debugger/db_dep_line_breakpoint.svg"); /** 12x12 */ public static final Icon Db_dep_method_breakpoint = IconLoader.getIcon("/debugger/db_dep_method_breakpoint.svg"); /** 12x12 */ public static final Icon Db_disabled_breakpoint = IconLoader.getIcon("/debugger/db_disabled_breakpoint.svg"); /** 16x16 */ public static final Icon Db_disabled_breakpoint_process = IconLoader.getIcon("/debugger/db_disabled_breakpoint_process.svg"); /** 12x12 */ public static final Icon Db_disabled_exception_breakpoint = IconLoader.getIcon("/debugger/db_disabled_exception_breakpoint.svg"); /** 12x12 */ public static final Icon Db_disabled_field_breakpoint = IconLoader.getIcon("/debugger/db_disabled_field_breakpoint.svg"); /** 12x12 */ public static final Icon Db_disabled_method_breakpoint = IconLoader.getIcon("/debugger/db_disabled_method_breakpoint.svg"); /** 12x12 */ public static final Icon Db_exception_breakpoint = IconLoader.getIcon("/debugger/db_exception_breakpoint.svg"); /** 12x12 */ public static final Icon Db_field_breakpoint = IconLoader.getIcon("/debugger/db_field_breakpoint.svg"); /** 12x12 */ public static final Icon Db_invalid_breakpoint = IconLoader.getIcon("/debugger/db_invalid_breakpoint.svg"); /** 12x12 */ public static final Icon Db_method_breakpoint = IconLoader.getIcon("/debugger/db_method_breakpoint.svg"); /** 12x12 */ public static final Icon Db_muted_breakpoint = IconLoader.getIcon("/debugger/db_muted_breakpoint.svg"); /** 12x12 */ public static final Icon Db_muted_dep_field_breakpoint = IconLoader.getIcon("/debugger/db_muted_dep_field_breakpoint.svg"); /** 12x12 */ public static final Icon Db_muted_dep_line_breakpoint = IconLoader.getIcon("/debugger/db_muted_dep_line_breakpoint.svg"); /** 12x12 */ public static final Icon Db_muted_dep_method_breakpoint = IconLoader.getIcon("/debugger/db_muted_dep_method_breakpoint.svg"); /** 12x12 */ public static final Icon Db_muted_disabled_breakpoint = IconLoader.getIcon("/debugger/db_muted_disabled_breakpoint.svg"); /** 12x12 */ public static final Icon Db_muted_disabled_field_breakpoint = IconLoader.getIcon("/debugger/db_muted_disabled_field_breakpoint.svg"); /** 12x12 */ public static final Icon Db_muted_disabled_method_breakpoint = IconLoader.getIcon("/debugger/db_muted_disabled_method_breakpoint.svg"); /** 12x12 */ public static final Icon Db_muted_field_breakpoint = IconLoader.getIcon("/debugger/db_muted_field_breakpoint.svg"); /** 12x12 */ public static final Icon Db_muted_method_breakpoint = IconLoader.getIcon("/debugger/db_muted_method_breakpoint.svg"); /** 12x12 */ public static final Icon Db_no_suspend_breakpoint = IconLoader.getIcon("/debugger/db_no_suspend_breakpoint.svg"); /** 12x12 */ public static final Icon Db_no_suspend_field_breakpoint = IconLoader.getIcon("/debugger/db_no_suspend_field_breakpoint.svg"); /** 12x12 */ public static final Icon Db_no_suspend_method_breakpoint = IconLoader.getIcon("/debugger/db_no_suspend_method_breakpoint.svg"); /** 12x12 */ public static final Icon Db_obsolete = IconLoader.getIcon("/debugger/db_obsolete.svg"); /** 16x16 */ public static final Icon Db_primitive = IconLoader.getIcon("/debugger/db_primitive.svg"); /** 12x12 */ public static final Icon Db_set_breakpoint = IconLoader.getIcon("/debugger/db_set_breakpoint.svg"); /** 12x12 */ public static final Icon Db_verified_breakpoint = IconLoader.getIcon("/debugger/db_verified_breakpoint.svg"); /** 12x12 */ public static final Icon Db_verified_field_breakpoint = IconLoader.getIcon("/debugger/db_verified_field_breakpoint.svg"); /** 12x12 */ public static final Icon Db_verified_method_breakpoint = IconLoader.getIcon("/debugger/db_verified_method_breakpoint.svg"); /** 12x12 */ public static final Icon Db_verified_no_suspend_breakpoint = IconLoader.getIcon("/debugger/db_verified_no_suspend_breakpoint.svg"); /** 12x12 */ public static final Icon Db_verified_no_suspend_field_breakpoint = IconLoader.getIcon("/debugger/db_verified_no_suspend_field_breakpoint.svg"); /** 12x12 */ public static final Icon Db_verified_no_suspend_method_breakpoint = IconLoader.getIcon("/debugger/db_verified_no_suspend_method_breakpoint.svg"); /** 16x16 */ public static final Icon Db_watch = IconLoader.getIcon("/debugger/db_watch.svg"); /** 16x16 */ public static final Icon EvaluateExpression = IconLoader.getIcon("/debugger/evaluateExpression.svg"); /** 16x16 */ public static final Icon EvaluationResult = IconLoader.getIcon("/debugger/evaluationResult.svg"); /** 16x16 */ public static final Icon Frame = IconLoader.getIcon("/debugger/frame.svg"); /** 16x16 */ public static final Icon KillProcess = IconLoader.getIcon("/debugger/killProcess.svg"); /** 12x12 */ public static final Icon LambdaBreakpoint = IconLoader.getIcon("/debugger/LambdaBreakpoint.svg"); public final static class MemoryView { /** 16x16 */ public static final Icon Active = IconLoader.getIcon("/debugger/memoryView/active.svg"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Watch */ @SuppressWarnings("unused") @Deprecated public static final Icon ClassTracked = AllIcons.Debugger.Watch; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon ToolWindowDisabled = IconLoader.getIcon("/debugger/memoryView/toolWindowDisabled.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon ToolWindowEnabled = IconLoader.getIcon("/debugger/memoryView/toolWindowEnabled.png"); } /** 12x12 */ public static final Icon MultipleBreakpoints = IconLoader.getIcon("/debugger/MultipleBreakpoints.svg"); /** 16x16 */ public static final Icon MuteBreakpoints = IconLoader.getIcon("/debugger/muteBreakpoints.svg"); /** 16x16 */ public static final Icon Overhead = IconLoader.getIcon("/debugger/overhead.svg"); /** 16x16 */ public static final Icon PromptInput = IconLoader.getIcon("/debugger/promptInput.svg"); /** 16x16 */ public static final Icon PromptInputHistory = IconLoader.getIcon("/debugger/promptInputHistory.svg"); /** 7x9 */ public static final Icon Question_badge = IconLoader.getIcon("/debugger/question_badge.svg"); /** 16x16 */ public static final Icon RestoreLayout = IconLoader.getIcon("/debugger/restoreLayout.svg"); /** 16x16 */ public static final Icon Selfreference = IconLoader.getIcon("/debugger/selfreference.svg"); /** 16x16 */ public static final Icon ShowCurrentFrame = IconLoader.getIcon("/debugger/showCurrentFrame.svg"); /** 16x16 */ public static final Icon SmartStepInto = IconLoader.getIcon("/debugger/smartStepInto.svg"); /** 16x16 */ public static final Icon ThreadAtBreakpoint = IconLoader.getIcon("/debugger/threadAtBreakpoint.svg"); /** 16x16 */ public static final Icon ThreadCurrent = IconLoader.getIcon("/debugger/threadCurrent.svg"); /** 16x16 */ public static final Icon ThreadFrozen = IconLoader.getIcon("/debugger/threadFrozen.svg"); /** 16x16 */ public static final Icon ThreadGroup = IconLoader.getIcon("/debugger/threadGroup.svg"); /** 16x16 */ public static final Icon ThreadGroupCurrent = IconLoader.getIcon("/debugger/threadGroupCurrent.svg"); /** 16x16 */ public static final Icon ThreadRunning = IconLoader.getIcon("/debugger/threadRunning.svg"); /** 16x16 */ public static final Icon Threads = IconLoader.getIcon("/debugger/threads.svg"); public final static class ThreadStates { /** 16x16 */ public static final Icon Daemon_sign = IconLoader.getIcon("/debugger/threadStates/daemon_sign.svg"); /** 16x16 */ public static final Icon Idle = IconLoader.getIcon("/debugger/threadStates/idle.svg"); /** 16x16 */ public static final Icon Socket = IconLoader.getIcon("/debugger/threadStates/socket.svg"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.ProfileCPU */ @SuppressWarnings("unused") @Deprecated public static final Icon EdtBusy = AllIcons.Actions.ProfileCPU; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Lightning */ @SuppressWarnings("unused") @Deprecated public static final Icon Exception = AllIcons.Actions.Lightning; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Menu_saveall */ @SuppressWarnings("unused") @Deprecated public static final Icon IO = AllIcons.Actions.Menu_saveall; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.MuteBreakpoints */ @SuppressWarnings("unused") @Deprecated public static final Icon Locked = AllIcons.Debugger.MuteBreakpoints; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Pause */ @SuppressWarnings("unused") @Deprecated public static final Icon Paused = AllIcons.Actions.Pause; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Resume */ @SuppressWarnings("unused") @Deprecated public static final Icon Running = AllIcons.Actions.Resume; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Dump */ @SuppressWarnings("unused") @Deprecated public static final Icon Threaddump = AllIcons.Actions.Dump; } /** 16x16 */ public static final Icon ThreadSuspended = IconLoader.getIcon("/debugger/threadSuspended.svg"); /** 16x16 */ public static final Icon Value = IconLoader.getIcon("/debugger/value.svg"); /** 16x16 */ public static final Icon VariablesTab = IconLoader.getIcon("/debugger/variablesTab.svg"); /** 16x16 */ public static final Icon ViewBreakpoints = IconLoader.getIcon("/debugger/viewBreakpoints.svg"); /** 16x16 */ public static final Icon Watch = IconLoader.getIcon("/debugger/watch.svg"); /** 16x16 */ public static final Icon WatchLastReturnValue = IconLoader.getIcon("/debugger/watchLastReturnValue.svg"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon AutoVariablesMode = IconLoader.getIcon("/debugger/autoVariablesMode.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon BreakpointAlert = IconLoader.getIcon("/debugger/breakpointAlert.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.Filter */ @SuppressWarnings("unused") @Deprecated public static final Icon Class_filter = AllIcons.General.Filter; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Console */ @SuppressWarnings("unused") @Deprecated public static final Icon CommandLine = AllIcons.Debugger.Console; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Console */ @SuppressWarnings("unused") @Deprecated public static final Icon Console_log = AllIcons.Debugger.Console; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Db_exception_breakpoint */ @SuppressWarnings("unused") @Deprecated public static final Icon Db_dep_exception_breakpoint = AllIcons.Debugger.Db_exception_breakpoint; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Db_exception_breakpoint */ @SuppressWarnings("unused") @Deprecated public static final Icon Db_field_warning_breakpoint = AllIcons.Debugger.Db_exception_breakpoint; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Db_invalid_breakpoint */ @SuppressWarnings("unused") @Deprecated public static final Icon Db_invalid_field_breakpoint = AllIcons.Debugger.Db_invalid_breakpoint; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Db_invalid_breakpoint */ @SuppressWarnings("unused") @Deprecated public static final Icon Db_invalid_method_breakpoint = AllIcons.Debugger.Db_invalid_breakpoint; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Db_exception_breakpoint */ @SuppressWarnings("unused") @Deprecated public static final Icon Db_method_warning_breakpoint = AllIcons.Debugger.Db_exception_breakpoint; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Db_exception_breakpoint */ @SuppressWarnings("unused") @Deprecated public static final Icon Db_muted_dep_exception_breakpoint = AllIcons.Debugger.Db_exception_breakpoint; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Db_exception_breakpoint */ @SuppressWarnings("unused") @Deprecated public static final Icon Db_muted_disabled_breakpoint_process = AllIcons.Debugger.Db_exception_breakpoint; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Db_exception_breakpoint */ @SuppressWarnings("unused") @Deprecated public static final Icon Db_muted_disabled_exception_breakpoint = AllIcons.Debugger.Db_exception_breakpoint; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Db_exception_breakpoint */ @SuppressWarnings("unused") @Deprecated public static final Icon Db_muted_exception_breakpoint = AllIcons.Debugger.Db_exception_breakpoint; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Db_exception_breakpoint */ @SuppressWarnings("unused") @Deprecated public static final Icon Db_muted_field_warning_breakpoint = AllIcons.Debugger.Db_exception_breakpoint; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Db_invalid_breakpoint */ @SuppressWarnings("unused") @Deprecated public static final Icon Db_muted_invalid_breakpoint = AllIcons.Debugger.Db_invalid_breakpoint; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Db_invalid_breakpoint */ @SuppressWarnings("unused") @Deprecated public static final Icon Db_muted_invalid_field_breakpoint = AllIcons.Debugger.Db_invalid_breakpoint; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Db_invalid_breakpoint */ @SuppressWarnings("unused") @Deprecated public static final Icon Db_muted_invalid_method_breakpoint = AllIcons.Debugger.Db_invalid_breakpoint; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Db_exception_breakpoint */ @SuppressWarnings("unused") @Deprecated public static final Icon Db_muted_method_warning_breakpoint = AllIcons.Debugger.Db_exception_breakpoint; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Db_muted_breakpoint */ @SuppressWarnings("unused") @Deprecated public static final Icon Db_muted_temporary_breakpoint = AllIcons.Debugger.Db_muted_breakpoint; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Db_muted_breakpoint */ @SuppressWarnings("unused") @Deprecated public static final Icon Db_muted_verified_breakpoint = AllIcons.Debugger.Db_muted_breakpoint; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Db_muted_field_breakpoint */ @SuppressWarnings("unused") @Deprecated public static final Icon Db_muted_verified_field_breakpoint = AllIcons.Debugger.Db_muted_field_breakpoint; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Db_muted_field_breakpoint */ @SuppressWarnings("unused") @Deprecated public static final Icon Db_muted_verified_method_breakpoint = AllIcons.Debugger.Db_muted_field_breakpoint; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Db_exception_breakpoint */ @SuppressWarnings("unused") @Deprecated public static final Icon Db_muted_verified_warning_breakpoint = AllIcons.Debugger.Db_exception_breakpoint; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Db_set_breakpoint */ @SuppressWarnings("unused") @Deprecated public static final Icon Db_pending_breakpoint = AllIcons.Debugger.Db_set_breakpoint; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Db_set_breakpoint */ @SuppressWarnings("unused") @Deprecated public static final Icon Db_temporary_breakpoint = AllIcons.Debugger.Db_set_breakpoint; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Db_exception_breakpoint */ @SuppressWarnings("unused") @Deprecated public static final Icon Db_verified_warning_breakpoint = AllIcons.Debugger.Db_exception_breakpoint; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Disable_value_calculation = IconLoader.getIcon("/debugger/disable_value_calculation.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Explosion = IconLoader.getIcon("/debugger/explosion.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.Add */ @SuppressWarnings("unused") @Deprecated public static final Icon NewWatch = AllIcons.General.Add; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Frame */ @SuppressWarnings("unused") @Deprecated public static final Icon StackFrame = AllIcons.Debugger.Frame; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Console */ @SuppressWarnings("unused") @Deprecated public static final Icon ToolConsole = AllIcons.Debugger.Console; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Debugger.Watch */ @SuppressWarnings("unused") @Deprecated public static final Icon Watches = AllIcons.Debugger.Watch; } public final static class Diff { /** 16x16 */ public static final Icon ApplyNotConflicts = IconLoader.getIcon("/diff/applyNotConflicts.svg"); /** 16x16 */ public static final Icon ApplyNotConflictsLeft = IconLoader.getIcon("/diff/applyNotConflictsLeft.svg"); /** 16x16 */ public static final Icon ApplyNotConflictsRight = IconLoader.getIcon("/diff/applyNotConflictsRight.svg"); /** 12x12 */ public static final Icon Arrow = IconLoader.getIcon("/diff/arrow.svg"); /** 12x12 */ public static final Icon ArrowLeftDown = IconLoader.getIcon("/diff/arrowLeftDown.svg"); /** 12x12 */ public static final Icon ArrowRight = IconLoader.getIcon("/diff/arrowRight.svg"); /** 12x12 */ public static final Icon ArrowRightDown = IconLoader.getIcon("/diff/arrowRightDown.svg"); /** 16x16 */ public static final Icon Compare3LeftMiddle = IconLoader.getIcon("/diff/compare3LeftMiddle.svg"); /** 16x16 */ public static final Icon Compare3LeftRight = IconLoader.getIcon("/diff/compare3LeftRight.svg"); /** 16x16 */ public static final Icon Compare3MiddleRight = IconLoader.getIcon("/diff/compare3MiddleRight.svg"); /** 16x16 */ public static final Icon Compare4LeftBottom = IconLoader.getIcon("/diff/compare4LeftBottom.svg"); /** 16x16 */ public static final Icon Compare4LeftMiddle = IconLoader.getIcon("/diff/compare4LeftMiddle.svg"); /** 16x16 */ public static final Icon Compare4LeftRight = IconLoader.getIcon("/diff/compare4LeftRight.svg"); /** 16x16 */ public static final Icon Compare4MiddleBottom = IconLoader.getIcon("/diff/compare4MiddleBottom.svg"); /** 16x16 */ public static final Icon Compare4MiddleRight = IconLoader.getIcon("/diff/compare4MiddleRight.svg"); /** 16x16 */ public static final Icon Compare4RightBottom = IconLoader.getIcon("/diff/compare4RightBottom.svg"); /** 12x12 */ public static final Icon GutterCheckBox = IconLoader.getIcon("/diff/gutterCheckBox.svg"); /** 12x12 */ public static final Icon GutterCheckBoxIndeterminate = IconLoader.getIcon("/diff/gutterCheckBoxIndeterminate.svg"); /** 12x12 */ public static final Icon GutterCheckBoxSelected = IconLoader.getIcon("/diff/gutterCheckBoxSelected.svg"); /** 16x16 */ public static final Icon Lock = IconLoader.getIcon("/diff/lock.svg"); /** 12x12 */ public static final Icon MagicResolve = IconLoader.getIcon("/diff/magicResolve.svg"); /** 16x16 */ public static final Icon MagicResolveToolbar = IconLoader.getIcon("/diff/magicResolveToolbar.svg"); /** 12x12 */ public static final Icon Remove = IconLoader.getIcon("/diff/remove.svg"); /** 12x12 */ public static final Icon Revert = IconLoader.getIcon("/diff/revert.svg"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Forward */ @SuppressWarnings("unused") @Deprecated public static final Icon CurrentLine = AllIcons.Actions.Forward; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Diff */ @SuppressWarnings("unused") @Deprecated public static final Icon Diff = AllIcons.Actions.Diff; } public final static class Duplicates { /** 16x16 */ public static final Icon SendToTheLeft = IconLoader.getIcon("/duplicates/sendToTheLeft.png"); /** 16x16 */ public static final Icon SendToTheLeftGrayed = IconLoader.getIcon("/duplicates/sendToTheLeftGrayed.png"); /** 16x16 */ public static final Icon SendToTheRight = IconLoader.getIcon("/duplicates/sendToTheRight.png"); /** 16x16 */ public static final Icon SendToTheRightGrayed = IconLoader.getIcon("/duplicates/sendToTheRightGrayed.png"); } public final static class FileTypes { /** 16x16 */ public static final Icon AddAny = IconLoader.getIcon("/fileTypes/addAny.svg"); /** 16x16 */ public static final Icon Any_type = IconLoader.getIcon("/fileTypes/any_type.svg"); /** 16x16 */ public static final Icon Archive = IconLoader.getIcon("/fileTypes/archive.svg"); /** 16x16 */ public static final Icon AS = IconLoader.getIcon("/fileTypes/as.svg"); /** 16x16 */ public static final Icon Aspectj = IconLoader.getIcon("/fileTypes/aspectj.svg"); /** 16x16 */ public static final Icon Config = IconLoader.getIcon("/fileTypes/config.svg"); /** 16x16 */ public static final Icon Css = IconLoader.getIcon("/fileTypes/css.svg"); /** 16x16 */ public static final Icon Custom = IconLoader.getIcon("/fileTypes/custom.svg"); /** 16x16 */ public static final Icon Diagram = IconLoader.getIcon("/fileTypes/diagram.svg"); /** 16x16 */ public static final Icon Dtd = IconLoader.getIcon("/fileTypes/dtd.svg"); /** 16x16 */ public static final Icon Htaccess = IconLoader.getIcon("/fileTypes/htaccess.svg"); /** 16x16 */ public static final Icon Html = IconLoader.getIcon("/fileTypes/html.svg"); /** 16x16 */ public static final Icon Idl = IconLoader.getIcon("/fileTypes/idl.svg"); /** 16x16 */ public static final Icon Java = IconLoader.getIcon("/fileTypes/java.svg"); /** 16x16 */ public static final Icon JavaClass = IconLoader.getIcon("/fileTypes/javaClass.svg"); /** 16x16 */ public static final Icon JavaOutsideSource = IconLoader.getIcon("/fileTypes/javaOutsideSource.svg"); /** 16x16 */ public static final Icon JavaScript = IconLoader.getIcon("/fileTypes/javaScript.svg"); /** 16x16 */ public static final Icon Json = IconLoader.getIcon("/fileTypes/json.svg"); /** 16x16 */ public static final Icon JsonSchema = IconLoader.getIcon("/fileTypes/jsonSchema.svg"); /** 16x16 */ public static final Icon Jsp = IconLoader.getIcon("/fileTypes/jsp.svg"); /** 16x16 */ public static final Icon Jspx = IconLoader.getIcon("/fileTypes/jspx.svg"); /** 16x16 */ public static final Icon Manifest = IconLoader.getIcon("/fileTypes/manifest.svg"); /** 16x16 */ public static final Icon Properties = IconLoader.getIcon("/fileTypes/properties.svg"); /** 16x16 */ public static final Icon Regexp = IconLoader.getIcon("/fileTypes/regexp.svg"); /** 16x16 */ public static final Icon Text = IconLoader.getIcon("/fileTypes/text.svg"); /** 16x16 */ public static final Icon UiForm = IconLoader.getIcon("/fileTypes/uiForm.svg"); /** 16x16 */ public static final Icon Unknown = IconLoader.getIcon("/fileTypes/unknown.svg"); /** 16x16 */ public static final Icon WsdlFile = IconLoader.getIcon("/fileTypes/wsdlFile.svg"); /** 16x16 */ public static final Icon Xhtml = IconLoader.getIcon("/fileTypes/xhtml.svg"); /** 16x16 */ public static final Icon Xml = IconLoader.getIcon("/fileTypes/xml.svg"); /** 16x16 */ public static final Icon XsdFile = IconLoader.getIcon("/fileTypes/xsdFile.svg"); /** @deprecated to be removed in IDEA 2020 - use JsfIcons.Facelets */ @SuppressWarnings("unused") @Deprecated public static final Icon Facelets = IconLoader.getIcon("/fileTypes/facelets.svg"); /** @deprecated to be removed in IDEA 2020 - use JsfIcons.FacesConfig */ @SuppressWarnings("unused") @Deprecated public static final Icon FacesConfig = IconLoader.getIcon("/fileTypes/facesConfig.svg"); /** @deprecated to be removed in IDEA 2020 - use JavaScriptPsiIcons.FileTypes.TypeScriptFile */ @SuppressWarnings("unused") @Deprecated public static final Icon TypeScript = IconLoader.getIcon("/fileTypes/typeScript.svg"); } public final static class General { /** 16x16 */ public static final Icon ActualZoom = IconLoader.getIcon("/general/actualZoom.svg"); /** 16x16 */ public static final Icon Add = IconLoader.getIcon("/general/add.svg"); /** 16x16 */ public static final Icon AddJdk = IconLoader.getIcon("/general/addJdk.svg"); /** 16x16 */ public static final Icon ArrowDown = IconLoader.getIcon("/general/arrowDown.svg"); /** 9x5 */ public static final Icon ArrowDownSmall = IconLoader.getIcon("/general/arrowDownSmall.svg"); /** 16x16 */ public static final Icon ArrowLeft = IconLoader.getIcon("/general/arrowLeft.svg"); /** 16x16 */ public static final Icon ArrowRight = IconLoader.getIcon("/general/arrowRight.svg"); /** 16x16 */ public static final Icon ArrowSplitCenterH = IconLoader.getIcon("/general/arrowSplitCenterH.svg"); /** 16x16 */ public static final Icon ArrowSplitCenterV = IconLoader.getIcon("/general/arrowSplitCenterV.svg"); /** 16x16 */ public static final Icon ArrowUp = IconLoader.getIcon("/general/arrowUp.svg"); /** 16x16 */ public static final Icon AutoscrollFromSource = IconLoader.getIcon("/general/autoscrollFromSource.svg"); /** 16x16 */ public static final Icon AutoscrollToSource = IconLoader.getIcon("/general/autoscrollToSource.svg"); /** 16x16 */ public static final Icon Balloon = IconLoader.getIcon("/general/balloon.svg"); /** 16x16 */ public static final Icon BalloonError = IconLoader.getIcon("/general/balloonError.svg"); /** 16x16 */ public static final Icon BalloonInformation = IconLoader.getIcon("/general/balloonInformation.svg"); /** 16x16 */ public static final Icon BalloonWarning = IconLoader.getIcon("/general/balloonWarning.svg"); /** 12x12 */ public static final Icon BalloonWarning12 = IconLoader.getIcon("/general/balloonWarning12.svg"); /** 8x4 */ public static final Icon ButtonDropTriangle = IconLoader.getIcon("/general/buttonDropTriangle.svg"); /** 12x12 */ public static final Icon CollapseComponent = IconLoader.getIcon("/general/collapseComponent.svg"); /** 12x12 */ public static final Icon CollapseComponentHover = IconLoader.getIcon("/general/collapseComponentHover.svg"); /** 16x16 */ public static final Icon ContextHelp = IconLoader.getIcon("/general/contextHelp.svg"); /** 16x16 */ public static final Icon CopyHovered = IconLoader.getIcon("/general/copyHovered.svg"); /** 2x19 */ public static final Icon Divider = IconLoader.getIcon("/general/divider.svg"); /** 16x16 */ public static final Icon Dropdown = IconLoader.getIcon("/general/dropdown.svg"); /** 13x13 */ public static final Icon DropdownGutter = IconLoader.getIcon("/general/dropdownGutter.svg"); /** 9x9 */ public static final Icon Ellipsis = IconLoader.getIcon("/general/ellipsis.svg"); /** 16x16 */ public static final Icon Error = IconLoader.getIcon("/general/error.svg"); /** 32x32 */ public static final Icon ErrorDialog = IconLoader.getIcon("/general/errorDialog.svg"); /** 16x16 */ public static final Icon ExclMark = IconLoader.getIcon("/general/exclMark.svg"); /** 12x12 */ public static final Icon ExpandComponent = IconLoader.getIcon("/general/expandComponent.svg"); /** 12x12 */ public static final Icon ExpandComponentHover = IconLoader.getIcon("/general/expandComponentHover.svg"); /** 16x16 */ public static final Icon ExternalTools = IconLoader.getIcon("/general/externalTools.svg"); /** 16x16 */ public static final Icon Filter = IconLoader.getIcon("/general/filter.svg"); /** 16x16 */ public static final Icon FitContent = IconLoader.getIcon("/general/fitContent.svg"); /** 16x16 */ public static final Icon GearPlain = IconLoader.getIcon("/general/gearPlain.svg"); /** 16x16 */ public static final Icon HideToolWindow = IconLoader.getIcon("/general/hideToolWindow.svg"); /** 16x16 */ public static final Icon ImplementingMethod = IconLoader.getIcon("/general/implementingMethod.svg"); /** 16x16 */ public static final Icon Information = IconLoader.getIcon("/general/information.svg"); /** 32x32 */ public static final Icon InformationDialog = IconLoader.getIcon("/general/informationDialog.svg"); /** 16x16 */ public static final Icon InheritedMethod = IconLoader.getIcon("/general/inheritedMethod.svg"); /** 16x16 */ public static final Icon Inline_edit = IconLoader.getIcon("/general/inline_edit.svg"); /** 16x16 */ public static final Icon Inline_edit_hovered = IconLoader.getIcon("/general/inline_edit_hovered.svg"); /** 16x16 */ public static final Icon InlineAdd = IconLoader.getIcon("/general/inlineAdd.svg"); /** 16x16 */ public static final Icon InlineAddHover = IconLoader.getIcon("/general/inlineAddHover.svg"); /** 16x16 */ public static final Icon InlineVariables = IconLoader.getIcon("/general/inlineVariables.svg"); /** 16x16 */ public static final Icon InlineVariablesHover = IconLoader.getIcon("/general/inlineVariablesHover.svg"); /** 14x14 */ public static final Icon InspectionsError = IconLoader.getIcon("/general/inspectionsError.svg"); /** 14x14 */ public static final Icon InspectionsEye = IconLoader.getIcon("/general/inspectionsEye.svg"); /** 14x14 */ public static final Icon InspectionsOK = IconLoader.getIcon("/general/inspectionsOK.svg"); /** 14x14 */ public static final Icon InspectionsPause = IconLoader.getIcon("/general/inspectionsPause.svg"); /** 14x14 */ public static final Icon InspectionsTrafficOff = IconLoader.getIcon("/general/inspectionsTrafficOff.svg"); /** 14x14 */ public static final Icon InspectionsTypos = IconLoader.getIcon("/general/inspectionsTypos.svg"); /** 16x16 */ public static final Icon Layout = IconLoader.getIcon("/general/layout.svg"); /** 16x16 */ public static final Icon LayoutEditorOnly = IconLoader.getIcon("/general/layoutEditorOnly.svg"); /** 16x16 */ public static final Icon LayoutEditorPreview = IconLoader.getIcon("/general/layoutEditorPreview.svg"); /** 16x16 */ public static final Icon LayoutPreviewOnly = IconLoader.getIcon("/general/layoutPreviewOnly.svg"); /** 14x14 */ public static final Icon LinkDropTriangle = IconLoader.getIcon("/general/linkDropTriangle.svg"); /** 16x16 */ public static final Icon Locate = IconLoader.getIcon("/general/locate.svg"); /** 13x13 */ public static final Icon Modified = IconLoader.getIcon("/general/modified.svg"); /** 13x13 */ public static final Icon ModifiedSelected = IconLoader.getIcon("/general/modifiedSelected.svg"); /** 16x16 */ public static final Icon MoreTabs = IconLoader.getIcon("/general/moreTabs.svg"); /** 16x16 */ public static final Icon Mouse = IconLoader.getIcon("/general/mouse.svg"); /** 16x16 */ public static final Icon Note = IconLoader.getIcon("/general/note.svg"); /** 24x24 */ public static final Icon NotificationError = IconLoader.getIcon("/general/notificationError.svg"); /** 24x24 */ public static final Icon NotificationInfo = IconLoader.getIcon("/general/notificationInfo.svg"); /** 24x24 */ public static final Icon NotificationWarning = IconLoader.getIcon("/general/notificationWarning.svg"); /** 16x16 */ public static final Icon OpenDisk = IconLoader.getIcon("/general/openDisk.svg"); /** 16x16 */ public static final Icon OpenDiskHover = IconLoader.getIcon("/general/openDiskHover.svg"); /** 16x16 */ public static final Icon OverridenMethod = IconLoader.getIcon("/general/overridenMethod.svg"); /** 16x16 */ public static final Icon OverridingMethod = IconLoader.getIcon("/general/overridingMethod.svg"); /** 16x16 */ public static final Icon Pin_tab = IconLoader.getIcon("/general/pin_tab.svg"); /** 16x16 */ public static final Icon Print = IconLoader.getIcon("/general/print.svg"); /** 9x9 */ public static final Icon ProjectConfigurable = IconLoader.getIcon("/general/projectConfigurable.svg"); /** 16x16 */ public static final Icon ProjectStructure = IconLoader.getIcon("/general/projectStructure.svg"); /** 16x16 */ public static final Icon ProjectTab = IconLoader.getIcon("/general/projectTab.svg"); /** 32x32 */ public static final Icon QuestionDialog = IconLoader.getIcon("/general/questionDialog.svg"); /** 16x16 */ public static final Icon Remove = IconLoader.getIcon("/general/remove.svg"); /** 16x16 */ public static final Icon Reset = IconLoader.getIcon("/general/reset.svg"); /** 16x16 */ public static final Icon RunWithCoverage = IconLoader.getIcon("/general/runWithCoverage.svg"); /** 16x16 */ public static final Icon SeparatorH = IconLoader.getIcon("/general/separatorH.svg"); /** 16x16 */ public static final Icon Settings = IconLoader.getIcon("/general/settings.svg"); /** 16x16 */ public static final Icon Show_to_implement = IconLoader.getIcon("/general/show_to_implement.svg"); /** 16x16 */ public static final Icon ShowWarning = IconLoader.getIcon("/general/showWarning.svg"); /** 16x16 */ public static final Icon TbHidden = IconLoader.getIcon("/general/tbHidden.svg"); /** 16x16 */ public static final Icon TbShown = IconLoader.getIcon("/general/tbShown.svg"); /** 32x32 */ public static final Icon Tip = IconLoader.getIcon("/general/tip.svg"); /** 16x16 */ public static final Icon TodoDefault = IconLoader.getIcon("/general/todoDefault.svg"); /** 16x16 */ public static final Icon TodoImportant = IconLoader.getIcon("/general/todoImportant.svg"); /** 16x16 */ public static final Icon TodoQuestion = IconLoader.getIcon("/general/todoQuestion.svg"); /** 16x16 */ public static final Icon User = IconLoader.getIcon("/general/user.svg"); /** 16x16 */ public static final Icon Warning = IconLoader.getIcon("/general/warning.svg"); /** 16x16 */ public static final Icon WarningDecorator = IconLoader.getIcon("/general/warningDecorator.svg"); /** 32x32 */ public static final Icon WarningDialog = IconLoader.getIcon("/general/warningDialog.svg"); /** 16x16 */ public static final Icon Web = IconLoader.getIcon("/general/web.svg"); /** 16x16 */ public static final Icon ZoomIn = IconLoader.getIcon("/general/zoomIn.svg"); /** 16x16 */ public static final Icon ZoomOut = IconLoader.getIcon("/general/zoomOut.svg"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.Add */ @SuppressWarnings("unused") @Deprecated public static final Icon AddFavoritesList = AllIcons.General.Add; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowDown */ @SuppressWarnings("unused") @Deprecated public static final Icon ArrowDown_white = AllIcons.General.ArrowDown; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.Pin_tab */ @SuppressWarnings("unused") @Deprecated public static final Icon AutohideOff = AllIcons.General.Pin_tab; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.Pin_tab */ @SuppressWarnings("unused") @Deprecated public static final Icon AutohideOffInactive = AllIcons.General.Pin_tab; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.Pin_tab */ @SuppressWarnings("unused") @Deprecated public static final Icon AutohideOffPressed = AllIcons.General.Pin_tab; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Ide.Notification.Close */ @SuppressWarnings("unused") @Deprecated public static final Icon BalloonClose = AllIcons.Ide.Notification.Close; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Bullet = IconLoader.getIcon("/general/bullet.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Collapseall */ @SuppressWarnings("unused") @Deprecated public static final Icon CollapseAll = AllIcons.Actions.Collapseall; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Collapseall */ @SuppressWarnings("unused") @Deprecated public static final Icon CollapseAllHover = AllIcons.Actions.Collapseall; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowDown */ @SuppressWarnings("unused") @Deprecated public static final Icon Combo = AllIcons.General.ArrowDown; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowDown */ @SuppressWarnings("unused") @Deprecated public static final Icon Combo2 = AllIcons.General.ArrowDown; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowDown */ @SuppressWarnings("unused") @Deprecated public static final Icon Combo3 = AllIcons.General.ArrowDown; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowDown */ @SuppressWarnings("unused") @Deprecated public static final Icon ComboArrow = AllIcons.General.ArrowDown; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowDownSmall */ @SuppressWarnings("unused") @Deprecated public static final Icon ComboArrowDown = AllIcons.General.ArrowDownSmall; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowLeft */ @SuppressWarnings("unused") @Deprecated public static final Icon ComboArrowLeft = AllIcons.General.ArrowLeft; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowLeft */ @SuppressWarnings("unused") @Deprecated public static final Icon ComboArrowLeftPassive = AllIcons.General.ArrowLeft; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowRight */ @SuppressWarnings("unused") @Deprecated public static final Icon ComboArrowRight = AllIcons.General.ArrowRight; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowRight */ @SuppressWarnings("unused") @Deprecated public static final Icon ComboArrowRightPassive = AllIcons.General.ArrowRight; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowDown */ @SuppressWarnings("unused") @Deprecated public static final Icon ComboBoxButtonArrow = AllIcons.General.ArrowDown; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon ComboUpPassive = IconLoader.getIcon("/general/comboUpPassive.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon ConfigurableDefault = IconLoader.getIcon("/general/configurableDefault.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.Settings */ @SuppressWarnings("unused") @Deprecated public static final Icon Configure = AllIcons.General.Settings; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Welcome.CreateNewProject */ @SuppressWarnings("unused") @Deprecated public static final Icon CreateNewProject = AllIcons.Welcome.CreateNewProject; /** @deprecated to be removed in IDEA 2020 - use AllIcons.ToolbarDecorator.Import */ @SuppressWarnings("unused") @Deprecated public static final Icon CreateNewProjectfromExistingFiles = AllIcons.ToolbarDecorator.Import; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.StartDebugger */ @SuppressWarnings("unused") @Deprecated public static final Icon Debug = AllIcons.Actions.StartDebugger; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon DefaultKeymap = IconLoader.getIcon("/general/defaultKeymap.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon DownloadPlugin = IconLoader.getIcon("/general/downloadPlugin.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.Settings */ @SuppressWarnings("unused") @Deprecated public static final Icon EditColors = AllIcons.General.Settings; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Edit */ @SuppressWarnings("unused") @Deprecated public static final Icon EditItemInSection = AllIcons.Actions.Edit; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon ErrorsInProgress = IconLoader.getIcon("/general/errorsInProgress.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Expandall */ @SuppressWarnings("unused") @Deprecated public static final Icon ExpandAll = AllIcons.Actions.Expandall; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Expandall */ @SuppressWarnings("unused") @Deprecated public static final Icon ExpandAllHover = AllIcons.Actions.Expandall; /** @deprecated to be removed in IDEA 2020 - use AllIcons.ToolbarDecorator.Export */ @SuppressWarnings("unused") @Deprecated public static final Icon ExportSettings = AllIcons.ToolbarDecorator.Export; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ExternalTools */ @SuppressWarnings("unused") @Deprecated public static final Icon ExternalToolsSmall = AllIcons.General.ExternalTools; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.MoveTo2 */ @SuppressWarnings("unused") @Deprecated public static final Icon Floating = AllIcons.Actions.MoveTo2; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.GearPlain */ @SuppressWarnings("unused") @Deprecated public static final Icon Gear = AllIcons.General.GearPlain; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon GearHover = IconLoader.getIcon("/general/gearHover.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Welcome.FromVCS */ @SuppressWarnings("unused") @Deprecated public static final Icon GetProjectfromVCS = AllIcons.Welcome.FromVCS; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ContextHelp */ @SuppressWarnings("unused") @Deprecated public static final Icon Help = AllIcons.General.ContextHelp; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ContextHelp */ @SuppressWarnings("unused") @Deprecated public static final Icon Help_small = AllIcons.General.ContextHelp; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.HideToolWindow */ @SuppressWarnings("unused") @Deprecated public static final Icon HideDown = AllIcons.General.HideToolWindow; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.HideToolWindow */ @SuppressWarnings("unused") @Deprecated public static final Icon HideDownHover = AllIcons.General.HideToolWindow; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.HideToolWindow */ @SuppressWarnings("unused") @Deprecated public static final Icon HideDownPart = AllIcons.General.HideToolWindow; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.HideToolWindow */ @SuppressWarnings("unused") @Deprecated public static final Icon HideDownPartHover = AllIcons.General.HideToolWindow; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.HideToolWindow */ @SuppressWarnings("unused") @Deprecated public static final Icon HideLeft = AllIcons.General.HideToolWindow; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.HideToolWindow */ @SuppressWarnings("unused") @Deprecated public static final Icon HideLeftHover = AllIcons.General.HideToolWindow; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.HideToolWindow */ @SuppressWarnings("unused") @Deprecated public static final Icon HideLeftPart = AllIcons.General.HideToolWindow; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.HideToolWindow */ @SuppressWarnings("unused") @Deprecated public static final Icon HideLeftPartHover = AllIcons.General.HideToolWindow; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.HideToolWindow */ @SuppressWarnings("unused") @Deprecated public static final Icon HideRight = AllIcons.General.HideToolWindow; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.HideToolWindow */ @SuppressWarnings("unused") @Deprecated public static final Icon HideRightHover = AllIcons.General.HideToolWindow; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.HideToolWindow */ @SuppressWarnings("unused") @Deprecated public static final Icon HideRightPart = AllIcons.General.HideToolWindow; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.HideToolWindow */ @SuppressWarnings("unused") @Deprecated public static final Icon HideRightPartHover = AllIcons.General.HideToolWindow; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.HideToolWindow */ @SuppressWarnings("unused") @Deprecated public static final Icon HideToolWindowInactive = AllIcons.General.HideToolWindow; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon HideWarnings = IconLoader.getIcon("/general/hideWarnings.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon IjLogo = IconLoader.getIcon("/general/ijLogo.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.ToolbarDecorator.Import */ @SuppressWarnings("unused") @Deprecated public static final Icon ImportProject = AllIcons.ToolbarDecorator.Import; /** @deprecated to be removed in IDEA 2020 - use AllIcons.ToolbarDecorator.Import */ @SuppressWarnings("unused") @Deprecated public static final Icon ImportSettings = AllIcons.ToolbarDecorator.Import; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Ide.HectorOff */ @SuppressWarnings("unused") @Deprecated public static final Icon InspectionsOff = AllIcons.Ide.HectorOff; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Jdk = IconLoader.getIcon("/general/jdk.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon KeyboardShortcut = IconLoader.getIcon("/general/keyboardShortcut.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Keymap = IconLoader.getIcon("/general/keymap.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.Locate */ @SuppressWarnings("unused") @Deprecated public static final Icon LocateHover = AllIcons.General.Locate; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon MacCorner = IconLoader.getIcon("/general/macCorner.png"); /** @deprecated to be removed in IDEA 2020 - use EmptyIcon.ICON_16 */ @SuppressWarnings("unused") @Deprecated public static final Icon Mdot_empty = IconLoader.getIcon("/general/mdot-empty.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Mdot_white = IconLoader.getIcon("/general/mdot-white.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Mdot = IconLoader.getIcon("/general/mdot.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Vcs.History */ @SuppressWarnings("unused") @Deprecated public static final Icon MessageHistory = AllIcons.Vcs.History; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon MouseShortcut = IconLoader.getIcon("/general/mouseShortcut.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Menu_open */ @SuppressWarnings("unused") @Deprecated public static final Icon OpenProject = AllIcons.Actions.Menu_open; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Nodes.CopyOfFolder */ @SuppressWarnings("unused") @Deprecated public static final Icon PackagesTab = AllIcons.Nodes.CopyOfFolder; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon PasswordLock = IconLoader.getIcon("/general/passwordLock.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon PathVariables = IconLoader.getIcon("/general/pathVariables.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon PluginManager = IconLoader.getIcon("/general/pluginManager.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Progress = IconLoader.getIcon("/general/progress.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ProjectConfigurable */ @SuppressWarnings("unused") @Deprecated public static final Icon ProjectConfigurableBanner = AllIcons.General.ProjectConfigurable; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ProjectConfigurable */ @SuppressWarnings("unused") @Deprecated public static final Icon ProjectConfigurableSelected = AllIcons.General.ProjectConfigurable; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.GearPlain */ @SuppressWarnings("unused") @Deprecated public static final Icon ProjectSettings = AllIcons.General.GearPlain; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Help */ @SuppressWarnings("unused") @Deprecated public static final Icon ReadHelp = AllIcons.Actions.Help; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.ShowAsTree */ @SuppressWarnings("unused") @Deprecated public static final Icon Recursive = AllIcons.Actions.ShowAsTree; /** @deprecated to be removed in IDEA 2020 - use AllIcons.RunConfigurations.TestState.Run */ @SuppressWarnings("unused") @Deprecated public static final Icon Run = AllIcons.RunConfigurations.TestState.Run; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.InspectionsTrafficOff */ @SuppressWarnings("unused") @Deprecated public static final Icon SafeMode = AllIcons.General.InspectionsTrafficOff; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon SearchEverywhereGear = IconLoader.getIcon("/general/searchEverywhereGear.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.GearPlain */ @SuppressWarnings("unused") @Deprecated public static final Icon SecondaryGroup = AllIcons.General.GearPlain; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Show_to_override = IconLoader.getIcon("/general/show_to_override.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.ShowAsTree */ @SuppressWarnings("unused") @Deprecated public static final Icon SmallConfigurableVcs = AllIcons.Actions.ShowAsTree; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowSplitCenterH */ @SuppressWarnings("unused") @Deprecated public static final Icon SplitCenterH = AllIcons.General.ArrowSplitCenterH; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowSplitCenterV */ @SuppressWarnings("unused") @Deprecated public static final Icon SplitCenterV = AllIcons.General.ArrowSplitCenterV; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowDown */ @SuppressWarnings("unused") @Deprecated public static final Icon SplitDown = AllIcons.General.ArrowDown; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon SplitGlueH = IconLoader.getIcon("/general/splitGlueH.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon SplitGlueV = IconLoader.getIcon("/general/splitGlueV.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowLeft */ @SuppressWarnings("unused") @Deprecated public static final Icon SplitLeft = AllIcons.General.ArrowLeft; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowRight */ @SuppressWarnings("unused") @Deprecated public static final Icon SplitRight = AllIcons.General.ArrowRight; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowUp */ @SuppressWarnings("unused") @Deprecated public static final Icon SplitUp = AllIcons.General.ArrowUp; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Tab_white_center = IconLoader.getIcon("/general/tab-white-center.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Tab_white_left = IconLoader.getIcon("/general/tab-white-left.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Tab_white_right = IconLoader.getIcon("/general/tab-white-right.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Tab_grey_bckgrnd = IconLoader.getIcon("/general/tab_grey_bckgrnd.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Tab_grey_left = IconLoader.getIcon("/general/tab_grey_left.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Tab_grey_left_inner = IconLoader.getIcon("/general/tab_grey_left_inner.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Tab_grey_right = IconLoader.getIcon("/general/tab_grey_right.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Tab_grey_right_inner = IconLoader.getIcon("/general/tab_grey_right_inner.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.Settings */ @SuppressWarnings("unused") @Deprecated public static final Icon TemplateProjectSettings = AllIcons.General.Settings; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ProjectStructure */ @SuppressWarnings("unused") @Deprecated public static final Icon TemplateProjectStructure = AllIcons.General.ProjectStructure; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon UninstallPlugin = IconLoader.getIcon("/general/uninstallPlugin.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon WebSettings = IconLoader.getIcon("/general/webSettings.png"); } public final static class Graph { /** 16x16 */ public static final Icon ActualZoom = IconLoader.getIcon("/graph/actualZoom.svg"); /** 16x16 */ public static final Icon FitContent = IconLoader.getIcon("/graph/fitContent.svg"); /** 16x16 */ public static final Icon Grid = IconLoader.getIcon("/graph/grid.svg"); /** 16x16 */ public static final Icon Layout = IconLoader.getIcon("/graph/layout.svg"); /** 16x16 */ public static final Icon NodeSelectionMode = IconLoader.getIcon("/graph/nodeSelectionMode.svg"); /** 16x16 */ public static final Icon SnapToGrid = IconLoader.getIcon("/graph/snapToGrid.svg"); /** 16x16 */ public static final Icon ZoomIn = IconLoader.getIcon("/graph/zoomIn.svg"); /** 16x16 */ public static final Icon ZoomOut = IconLoader.getIcon("/graph/zoomOut.svg"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.ToolbarDecorator.Export */ @SuppressWarnings("unused") @Deprecated public static final Icon Export = AllIcons.ToolbarDecorator.Export; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.Print */ @SuppressWarnings("unused") @Deprecated public static final Icon Print = AllIcons.General.Print; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Preview */ @SuppressWarnings("unused") @Deprecated public static final Icon PrintPreview = AllIcons.Actions.Preview; } public final static class Gutter { /** 12x12 */ public static final Icon Colors = IconLoader.getIcon("/gutter/colors.svg"); /** 12x12 */ public static final Icon ExtAnnotation = IconLoader.getIcon("/gutter/extAnnotation.svg"); /** 12x12 */ public static final Icon ImplementedMethod = IconLoader.getIcon("/gutter/implementedMethod.svg"); /** 12x12 */ public static final Icon ImplementingFunctionalInterface = IconLoader.getIcon("/gutter/implementingFunctionalInterface.svg"); /** 12x12 */ public static final Icon ImplementingMethod = IconLoader.getIcon("/gutter/implementingMethod.svg"); /** 12x12 */ public static final Icon Java9Service = IconLoader.getIcon("/gutter/java9Service.svg"); /** 12x12 */ public static final Icon OverridenMethod = IconLoader.getIcon("/gutter/overridenMethod.svg"); /** 12x12 */ public static final Icon OverridingMethod = IconLoader.getIcon("/gutter/overridingMethod.svg"); /** 12x12 */ public static final Icon ReadAccess = IconLoader.getIcon("/gutter/readAccess.svg"); /** 12x12 */ public static final Icon RecursiveMethod = IconLoader.getIcon("/gutter/recursiveMethod.svg"); /** 12x12 */ public static final Icon SiblingInheritedMethod = IconLoader.getIcon("/gutter/siblingInheritedMethod.svg"); /** 8x8 */ public static final Icon Unique = IconLoader.getIcon("/gutter/unique.svg"); /** 12x12 */ public static final Icon WriteAccess = IconLoader.getIcon("/gutter/writeAccess.svg"); } public final static class Hierarchy { /** 16x16 */ public static final Icon Class = IconLoader.getIcon("/hierarchy/class.svg"); /** 8x8 */ public static final Icon MethodDefined = IconLoader.getIcon("/hierarchy/methodDefined.svg"); /** 8x8 */ public static final Icon MethodNotDefined = IconLoader.getIcon("/hierarchy/methodNotDefined.svg"); /** 8x8 */ public static final Icon ShouldDefineMethod = IconLoader.getIcon("/hierarchy/shouldDefineMethod.svg"); /** 16x16 */ public static final Icon Subtypes = IconLoader.getIcon("/hierarchy/subtypes.svg"); /** 16x16 */ public static final Icon Supertypes = IconLoader.getIcon("/hierarchy/supertypes.svg"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Forward */ @SuppressWarnings("unused") @Deprecated public static final Icon Base = AllIcons.General.Modified; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Hierarchy.Subtypes */ @SuppressWarnings("unused") @Deprecated public static final Icon Callee = AllIcons.Hierarchy.Subtypes; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Hierarchy.Supertypes */ @SuppressWarnings("unused") @Deprecated public static final Icon Caller = AllIcons.Hierarchy.Supertypes; } /** 32x32 */ public static final Icon Icon = IconLoader.getIcon("/icon.png"); /** 128x128 */ public static final Icon Icon_128 = IconLoader.getIcon("/icon_128.png"); /** 32x32 */ public static final Icon Icon_CE = IconLoader.getIcon("/icon_CE.png"); /** 128x128 */ public static final Icon Icon_CE_128 = IconLoader.getIcon("/icon_CE_128.png"); /** 256x256 */ public static final Icon Icon_CE_256 = IconLoader.getIcon("/icon_CE_256.png"); /** 512x512 */ public static final Icon Icon_CE_512 = IconLoader.getIcon("/icon_CE_512.png"); /** 64x64 */ public static final Icon Icon_CE_64 = IconLoader.getIcon("/icon_CE_64.png"); /** 16x16 */ public static final Icon Icon_CEsmall = IconLoader.getIcon("/icon_CEsmall.png"); /** 16x16 */ public static final Icon Icon_small = IconLoader.getIcon("/icon_small.png"); public final static class Icons { public final static class Ide { /** 12x12 */ public static final Icon NextStep = IconLoader.getIcon("/icons/ide/nextStep.svg"); /** 12x12 */ public static final Icon NextStepInverted = IconLoader.getIcon("/icons/ide/nextStepInverted.svg"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Icons.Ide.NextStep */ @SuppressWarnings("unused") @Deprecated public static final Icon NextStepGrayed = AllIcons.Icons.Ide.NextStep; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon SpeedSearchPrompt = IconLoader.getIcon("/icons/ide/speedSearchPrompt.png"); } } public final static class Ide { public final static class Dnd { /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowUp */ @SuppressWarnings("unused") @Deprecated public static final Icon Bottom = AllIcons.General.ArrowUp; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowRight */ @SuppressWarnings("unused") @Deprecated public static final Icon Left = AllIcons.General.ArrowRight; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowLeft */ @SuppressWarnings("unused") @Deprecated public static final Icon Right = AllIcons.General.ArrowLeft; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowDown */ @SuppressWarnings("unused") @Deprecated public static final Icon Top = AllIcons.General.ArrowDown; } /** 6x6 */ public static final Icon ErrorPoint = IconLoader.getIcon("/ide/errorPoint.svg"); /** 14x14 */ public static final Icon External_link_arrow = IconLoader.getIcon("/ide/external_link_arrow.svg"); /** 16x16 */ public static final Icon FatalError_read = IconLoader.getIcon("/ide/fatalError-read.svg"); /** 16x16 */ public static final Icon FatalError = IconLoader.getIcon("/ide/fatalError.svg"); /** 16x16 */ public static final Icon HectorOff = IconLoader.getIcon("/ide/hectorOff.svg"); /** 16x16 */ public static final Icon HectorOn = IconLoader.getIcon("/ide/hectorOn.svg"); /** 16x16 */ public static final Icon HectorSyntax = IconLoader.getIcon("/ide/hectorSyntax.svg"); /** 16x16 */ public static final Icon IncomingChangesOn = IconLoader.getIcon("/ide/incomingChangesOn.svg"); /** 12x12 */ public static final Icon Link = IconLoader.getIcon("/ide/link.svg"); /** 16x16 */ public static final Icon LocalScope = IconLoader.getIcon("/ide/localScope.svg"); /** 12x12 */ public static final Icon LookupAlphanumeric = IconLoader.getIcon("/ide/lookupAlphanumeric.svg"); /** 12x12 */ public static final Icon LookupRelevance = IconLoader.getIcon("/ide/lookupRelevance.svg"); public final static class Macro { /** 16x16 */ public static final Icon Recording_1 = IconLoader.getIcon("/ide/macro/recording_1.svg"); /** 16x16 */ public static final Icon Recording_2 = IconLoader.getIcon("/ide/macro/recording_2.svg"); /** 16x16 */ public static final Icon Recording_3 = IconLoader.getIcon("/ide/macro/recording_3.svg"); /** 16x16 */ public static final Icon Recording_4 = IconLoader.getIcon("/ide/macro/recording_4.svg"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Suspend */ @SuppressWarnings("unused") @Deprecated public static final Icon Recording_stop = AllIcons.Actions.Suspend; } /** 5x15 */ public static final Icon NavBarSeparator = IconLoader.getIcon("/ide/NavBarSeparator.svg"); public final static class Notification { /** 16x16 */ public static final Icon Close = IconLoader.getIcon("/ide/notification/close.svg"); /** 16x16 */ public static final Icon CloseHover = IconLoader.getIcon("/ide/notification/closeHover.svg"); /** 16x16 */ public static final Icon Collapse = IconLoader.getIcon("/ide/notification/collapse.svg"); /** 16x16 */ public static final Icon CollapseHover = IconLoader.getIcon("/ide/notification/collapseHover.svg"); /** 16x16 */ public static final Icon DropTriangle = IconLoader.getIcon("/ide/notification/dropTriangle.svg"); /** 13x13 */ public static final Icon ErrorEvents = IconLoader.getIcon("/ide/notification/errorEvents.svg"); /** 16x16 */ public static final Icon Expand = IconLoader.getIcon("/ide/notification/expand.svg"); /** 16x16 */ public static final Icon ExpandHover = IconLoader.getIcon("/ide/notification/expandHover.svg"); /** 16x16 */ public static final Icon Gear = IconLoader.getIcon("/ide/notification/gear.svg"); /** 16x16 */ public static final Icon GearHover = IconLoader.getIcon("/ide/notification/gearHover.svg"); /** 13x13 */ public static final Icon InfoEvents = IconLoader.getIcon("/ide/notification/infoEvents.svg"); /** 13x13 */ public static final Icon NoEvents = IconLoader.getIcon("/ide/notification/noEvents.svg"); /** 13x13 */ public static final Icon WarningEvents = IconLoader.getIcon("/ide/notification/warningEvents.svg"); } /** 16x16 */ public static final Icon OutgoingChangesOn = IconLoader.getIcon("/ide/outgoingChangesOn.svg"); /** 16x16 */ public static final Icon Pipette = IconLoader.getIcon("/ide/pipette.svg"); /** 16x16 */ public static final Icon Pipette_rollover = IconLoader.getIcon("/ide/pipette_rollover.svg"); /** 11x11 */ public static final Icon Rating = IconLoader.getIcon("/ide/rating.svg"); /** 11x11 */ public static final Icon Rating1 = IconLoader.getIcon("/ide/rating1.svg"); /** 11x11 */ public static final Icon Rating2 = IconLoader.getIcon("/ide/rating2.svg"); /** 11x11 */ public static final Icon Rating3 = IconLoader.getIcon("/ide/rating3.svg"); /** 11x11 */ public static final Icon Rating4 = IconLoader.getIcon("/ide/rating4.svg"); /** 16x16 */ public static final Icon Readonly = IconLoader.getIcon("/ide/readonly.svg"); /** 16x16 */ public static final Icon Readwrite = IconLoader.getIcon("/ide/readwrite.svg"); public final static class Shadow { /** 4x14 */ public static final Icon Bottom = IconLoader.getIcon("/ide/shadow/bottom.svg"); /** 18x22 */ public static final Icon BottomLeft = IconLoader.getIcon("/ide/shadow/bottomLeft.svg"); /** 18x22 */ public static final Icon BottomRight = IconLoader.getIcon("/ide/shadow/bottomRight.svg"); /** 11x4 */ public static final Icon Left = IconLoader.getIcon("/ide/shadow/left.svg"); /** 11x4 */ public static final Icon Right = IconLoader.getIcon("/ide/shadow/right.svg"); /** 4x7 */ public static final Icon Top = IconLoader.getIcon("/ide/shadow/top.svg"); /** 18x14 */ public static final Icon TopLeft = IconLoader.getIcon("/ide/shadow/topLeft.svg"); /** 18x14 */ public static final Icon TopRight = IconLoader.getIcon("/ide/shadow/topRight.svg"); } /** 7x10 */ public static final Icon Statusbar_arrows = IconLoader.getIcon("/ide/statusbar_arrows.svg"); /** 16x16 */ public static final Icon UpDown = IconLoader.getIcon("/ide/upDown.svg"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Ide.FatalError_read */ @SuppressWarnings("unused") @Deprecated public static final Icon EmptyFatalError = AllIcons.Ide.FatalError_read; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Ide.FatalError */ @SuppressWarnings("unused") @Deprecated public static final Icon Error = AllIcons.Ide.FatalError; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.Error */ @SuppressWarnings("unused") @Deprecated public static final Icon Error_notifications = AllIcons.General.Error; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Ide.HectorOff */ @SuppressWarnings("unused") @Deprecated public static final Icon HectorNo = AllIcons.Ide.HectorOff; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon IncomingChangesOff = IconLoader.getIcon("/ide/incomingChangesOff.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.Information */ @SuppressWarnings("unused") @Deprecated public static final Icon Info_notifications = AllIcons.General.Information; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon NoNotifications13 = IconLoader.getIcon("/ide/noNotifications13.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Ide.Notification.NoEvents */ @SuppressWarnings("unused") @Deprecated public static final Icon Notifications = AllIcons.Ide.Notification.NoEvents; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.Warning */ @SuppressWarnings("unused") @Deprecated public static final Icon Warning_notifications = AllIcons.General.Warning; } /** 500x500 */ public static final Icon Idea_logo_background = IconLoader.getIcon("/idea_logo_background.png"); /** 100x100 */ public static final Icon Idea_logo_welcome = IconLoader.getIcon("/idea_logo_welcome.png"); public final static class Javaee { /** 16x16 */ public static final Icon Application_xml = IconLoader.getIcon("/javaee/application_xml.svg"); /** 16x16 */ public static final Icon BuildOnFrameDeactivation = IconLoader.getIcon("/javaee/buildOnFrameDeactivation.svg"); /** 16x16 */ public static final Icon Ejb_jar_xml = IconLoader.getIcon("/javaee/ejb-jar_xml.svg"); /** 16x16 */ public static final Icon EjbClass = IconLoader.getIcon("/javaee/ejbClass.svg"); /** 16x16 */ public static final Icon EjbModule = IconLoader.getIcon("/javaee/ejbModule.svg"); /** 16x16 */ public static final Icon EmbeddedAttributeOverlay = IconLoader.getIcon("/javaee/embeddedAttributeOverlay.svg"); /** 16x16 */ public static final Icon EntityBean = IconLoader.getIcon("/javaee/entityBean.svg"); /** 16x16 */ public static final Icon Home = IconLoader.getIcon("/javaee/home.svg"); /** 16x16 */ public static final Icon InheritedAttributeOverlay = IconLoader.getIcon("/javaee/inheritedAttributeOverlay.svg"); /** 16x16 */ public static final Icon InterceptorClass = IconLoader.getIcon("/javaee/interceptorClass.svg"); /** 16x16 */ public static final Icon InterceptorMethod = IconLoader.getIcon("/javaee/interceptorMethod.svg"); /** 16x16 */ public static final Icon JavaeeAppModule = IconLoader.getIcon("/javaee/JavaeeAppModule.svg"); /** 16x16 */ public static final Icon JpaFacet = IconLoader.getIcon("/javaee/jpaFacet.svg"); /** 16x16 */ public static final Icon MessageBean = IconLoader.getIcon("/javaee/messageBean.svg"); /** 16x16 */ public static final Icon PersistenceAttribute = IconLoader.getIcon("/javaee/persistenceAttribute.svg"); /** 16x16 */ public static final Icon PersistenceEmbeddable = IconLoader.getIcon("/javaee/persistenceEmbeddable.svg"); /** 16x16 */ public static final Icon PersistenceEntity = IconLoader.getIcon("/javaee/persistenceEntity.svg"); /** 16x16 */ public static final Icon PersistenceEntityListener = IconLoader.getIcon("/javaee/persistenceEntityListener.svg"); /** 16x16 */ public static final Icon PersistenceId = IconLoader.getIcon("/javaee/persistenceId.svg"); /** 16x16 */ public static final Icon PersistenceIdRelationship = IconLoader.getIcon("/javaee/persistenceIdRelationship.svg"); /** 16x16 */ public static final Icon PersistenceMappedSuperclass = IconLoader.getIcon("/javaee/persistenceMappedSuperclass.svg"); /** 16x16 */ public static final Icon PersistenceRelationship = IconLoader.getIcon("/javaee/persistenceRelationship.svg"); /** 16x16 */ public static final Icon PersistenceUnit = IconLoader.getIcon("/javaee/persistenceUnit.svg"); /** 16x16 */ public static final Icon Remote = IconLoader.getIcon("/javaee/remote.svg"); /** 16x16 */ public static final Icon SessionBean = IconLoader.getIcon("/javaee/sessionBean.svg"); /** 16x16 */ public static final Icon UpdateRunningApplication = IconLoader.getIcon("/javaee/updateRunningApplication.svg"); /** 16x16 */ public static final Icon Web_xml = IconLoader.getIcon("/javaee/web_xml.svg"); /** 16x16 */ public static final Icon WebModule = IconLoader.getIcon("/javaee/webModule.svg"); /** 16x16 */ public static final Icon WebModuleGroup = IconLoader.getIcon("/javaee/webModuleGroup.svg"); /** 16x16 */ public static final Icon WebService = IconLoader.getIcon("/javaee/WebService.svg"); /** 16x16 */ public static final Icon WebServiceClient = IconLoader.getIcon("/javaee/WebServiceClient.svg"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon DataSourceImport = IconLoader.getIcon("/javaee/dataSourceImport.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon DbSchemaImportBig = IconLoader.getIcon("/javaee/dbSchemaImportBig.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon EntityBeanBig = IconLoader.getIcon("/javaee/entityBeanBig.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Nodes.Interface */ @SuppressWarnings("unused") @Deprecated public static final Icon Local = AllIcons.Nodes.Interface; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Javaee.Home */ @SuppressWarnings("unused") @Deprecated public static final Icon LocalHome = AllIcons.Javaee.Home; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Javaee.WebService */ @SuppressWarnings("unused") @Deprecated public static final Icon WebService2 = AllIcons.Javaee.WebService; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Javaee.WebServiceClient */ @SuppressWarnings("unused") @Deprecated public static final Icon WebServiceClient2 = AllIcons.Javaee.WebServiceClient; } public final static class Json { /** 16x16 */ public static final Icon Array = IconLoader.getIcon("/json/array.svg"); /** 16x16 */ public static final Icon Object = IconLoader.getIcon("/json/object.svg"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Json.Object */ @SuppressWarnings("unused") @Deprecated public static final Icon Property_braces = AllIcons.Json.Object; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Json.Array */ @SuppressWarnings("unused") @Deprecated public static final Icon Property_brackets = AllIcons.Json.Array; } /** 80x80 */ public static final Icon Logo_welcomeScreen = IconLoader.getIcon("/Logo_welcomeScreen.png"); /** 80x80 */ public static final Icon Logo_welcomeScreen_CE = IconLoader.getIcon("/Logo_welcomeScreen_CE.png"); public final static class Mac { /** 55x55 */ public static final Icon AppIconOk512 = IconLoader.getIcon("/mac/appIconOk512.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Text = IconLoader.getIcon("/mac/text.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Tree_black_right_arrow = IconLoader.getIcon("/mac/tree_black_right_arrow.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Tree_white_down_arrow = IconLoader.getIcon("/mac/tree_white_down_arrow.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Tree_white_right_arrow = IconLoader.getIcon("/mac/tree_white_right_arrow.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon YosemiteOptionButtonSelector = IconLoader.getIcon("/mac/yosemiteOptionButtonSelector.png"); } public final static class Modules { /** 16x16 */ public static final Icon AddExcludedRoot = IconLoader.getIcon("/modules/addExcludedRoot.svg"); /** 16x16 */ public static final Icon Annotation = IconLoader.getIcon("/modules/annotation.svg"); /** 16x16 */ public static final Icon EditFolder = IconLoader.getIcon("/modules/editFolder.svg"); /** 16x16 */ public static final Icon ExcludedGeneratedRoot = IconLoader.getIcon("/modules/excludedGeneratedRoot.svg"); /** 16x16 */ public static final Icon ExcludeRoot = IconLoader.getIcon("/modules/excludeRoot.svg"); /** 16x16 */ public static final Icon GeneratedFolder = IconLoader.getIcon("/modules/generatedFolder.svg"); /** 16x16 */ public static final Icon GeneratedSourceRoot = IconLoader.getIcon("/modules/generatedSourceRoot.svg"); /** 16x16 */ public static final Icon GeneratedTestRoot = IconLoader.getIcon("/modules/generatedTestRoot.svg"); /** 16x16 */ public static final Icon Output = IconLoader.getIcon("/modules/output.svg"); /** 16x16 */ public static final Icon ResourcesRoot = IconLoader.getIcon("/modules/resourcesRoot.svg"); /** 16x16 */ public static final Icon SourceRoot = IconLoader.getIcon("/modules/sourceRoot.svg"); /** 16x16 */ public static final Icon SourceRootFileLayer = IconLoader.getIcon("/modules/sourceRootFileLayer.svg"); /** 16x16 */ public static final Icon Split = IconLoader.getIcon("/modules/split.svg"); /** 16x16 */ public static final Icon TestResourcesRoot = IconLoader.getIcon("/modules/testResourcesRoot.svg"); /** 16x16 */ public static final Icon TestRoot = IconLoader.getIcon("/modules/testRoot.svg"); public final static class Types { /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.User */ @SuppressWarnings("unused") @Deprecated public static final Icon UserDefined = AllIcons.General.User; } /** 16x16 */ public static final Icon UnloadedModule = IconLoader.getIcon("/modules/unloadedModule.svg"); /** 16x16 */ public static final Icon UnmarkWebroot = IconLoader.getIcon("/modules/unmarkWebroot.svg"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.Add */ @SuppressWarnings("unused") @Deprecated public static final Icon AddContentEntry = AllIcons.General.Add; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Close */ @SuppressWarnings("unused") @Deprecated public static final Icon DeleteContentFolder = AllIcons.Actions.Close; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.CloseHovered */ @SuppressWarnings("unused") @Deprecated public static final Icon DeleteContentFolderRollover = AllIcons.Actions.CloseHovered; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Close */ @SuppressWarnings("unused") @Deprecated public static final Icon DeleteContentRoot = AllIcons.Actions.Close; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.CloseHovered */ @SuppressWarnings("unused") @Deprecated public static final Icon DeleteContentRootRollover = AllIcons.Actions.CloseHovered; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Edit */ @SuppressWarnings("unused") @Deprecated public static final Icon Edit = AllIcons.Actions.Edit; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Nodes.PpLib */ @SuppressWarnings("unused") @Deprecated public static final Icon Library = AllIcons.Nodes.PpLib; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Vcs.Merge */ @SuppressWarnings("unused") @Deprecated public static final Icon Merge = AllIcons.Vcs.Merge; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Nodes.ModuleGroup */ @SuppressWarnings("unused") @Deprecated public static final Icon ModulesNode = AllIcons.Nodes.ModuleGroup; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.Inline_edit */ @SuppressWarnings("unused") @Deprecated public static final Icon SetPackagePrefix = AllIcons.General.Inline_edit; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.Inline_edit_hovered */ @SuppressWarnings("unused") @Deprecated public static final Icon SetPackagePrefixRollover = AllIcons.General.Inline_edit_hovered; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Nodes.Package */ @SuppressWarnings("unused") @Deprecated public static final Icon SourceFolder = AllIcons.Nodes.Package; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Sources = IconLoader.getIcon("/modules/sources.svg"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Nodes.TestSourceFolder */ @SuppressWarnings("unused") @Deprecated public static final Icon TestSourceFolder = AllIcons.Nodes.TestSourceFolder; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Nodes.WebFolder */ @SuppressWarnings("unused") @Deprecated public static final Icon WebRoot = AllIcons.Nodes.WebFolder; } public final static class Nodes { /** 16x16 */ public static final Icon AbstractClass = IconLoader.getIcon("/nodes/abstractClass.svg"); /** 16x16 */ public static final Icon AbstractException = IconLoader.getIcon("/nodes/abstractException.svg"); /** 16x16 */ public static final Icon AbstractMethod = IconLoader.getIcon("/nodes/abstractMethod.svg"); /** 16x16 */ public static final Icon Alias = IconLoader.getIcon("/nodes/alias.svg"); /** 16x16 */ public static final Icon Annotationtype = IconLoader.getIcon("/nodes/annotationtype.svg"); /** 16x16 */ public static final Icon AnonymousClass = IconLoader.getIcon("/nodes/anonymousClass.svg"); /** 16x16 */ public static final Icon Artifact = IconLoader.getIcon("/nodes/artifact.svg"); /** 16x16 */ public static final Icon Aspect = IconLoader.getIcon("/nodes/aspect.svg"); /** 16x16 */ public static final Icon C_plocal = IconLoader.getIcon("/nodes/c_plocal.svg"); /** 16x16 */ public static final Icon C_private = IconLoader.getIcon("/nodes/c_private.svg"); /** 16x16 */ public static final Icon C_protected = IconLoader.getIcon("/nodes/c_protected.svg"); /** 16x16 */ public static final Icon C_public = IconLoader.getIcon("/nodes/c_public.svg"); /** 16x16 */ public static final Icon Class = IconLoader.getIcon("/nodes/class.svg"); /** 16x16 */ public static final Icon ClassInitializer = IconLoader.getIcon("/nodes/classInitializer.svg"); /** 16x16 */ public static final Icon CompiledClassesFolder = IconLoader.getIcon("/nodes/compiledClassesFolder.svg"); /** 16x16 */ public static final Icon ConfigFolder = IconLoader.getIcon("/nodes/configFolder.svg"); /** 16x16 */ public static final Icon Constant = IconLoader.getIcon("/nodes/constant.svg"); /** 16x16 */ public static final Icon Controller = IconLoader.getIcon("/nodes/controller.svg"); /** 16x16 */ public static final Icon CopyOfFolder = IconLoader.getIcon("/nodes/copyOfFolder.svg"); /** 16x16 */ public static final Icon CustomRegion = IconLoader.getIcon("/nodes/customRegion.svg"); /** 16x16 */ public static final Icon Cvs_global = IconLoader.getIcon("/nodes/cvs_global.svg"); /** 16x16 */ public static final Icon Cvs_roots = IconLoader.getIcon("/nodes/cvs_roots.svg"); /** 16x16 */ public static final Icon DataColumn = IconLoader.getIcon("/nodes/dataColumn.svg"); /** 16x16 */ public static final Icon DataTables = IconLoader.getIcon("/nodes/DataTables.svg"); /** 16x16 */ public static final Icon Deploy = IconLoader.getIcon("/nodes/deploy.svg"); /** 16x16 */ public static final Icon Desktop = IconLoader.getIcon("/nodes/desktop.svg"); /** 16x16 */ public static final Icon Editorconfig = IconLoader.getIcon("/nodes/editorconfig.svg"); /** 16x16 */ public static final Icon Ejb = IconLoader.getIcon("/nodes/ejb.svg"); /** 16x16 */ public static final Icon EjbBusinessMethod = IconLoader.getIcon("/nodes/ejbBusinessMethod.svg"); /** 16x16 */ public static final Icon EjbCmpField = IconLoader.getIcon("/nodes/ejbCmpField.svg"); /** 16x16 */ public static final Icon EjbCmrField = IconLoader.getIcon("/nodes/ejbCmrField.svg"); /** 16x16 */ public static final Icon EjbCreateMethod = IconLoader.getIcon("/nodes/ejbCreateMethod.svg"); /** 16x16 */ public static final Icon EjbFinderMethod = IconLoader.getIcon("/nodes/ejbFinderMethod.svg"); /** 16x16 */ public static final Icon EjbPrimaryKeyClass = IconLoader.getIcon("/nodes/ejbPrimaryKeyClass.svg"); /** 16x16 */ public static final Icon EjbReference = IconLoader.getIcon("/nodes/ejbReference.svg"); /** 16x16 */ public static final Icon EmptyNode = IconLoader.getIcon("/nodes/emptyNode.svg"); /** 16x16 */ public static final Icon EnterpriseProject = IconLoader.getIcon("/nodes/enterpriseProject.svg"); /** 16x16 */ public static final Icon EntryPoints = IconLoader.getIcon("/nodes/entryPoints.svg"); /** 16x16 */ public static final Icon Enum = IconLoader.getIcon("/nodes/enum.svg"); /** 16x16 */ public static final Icon ErrorIntroduction = IconLoader.getIcon("/nodes/errorIntroduction.svg"); /** 16x16 */ public static final Icon ErrorMark = IconLoader.getIcon("/nodes/errorMark.svg"); /** 16x16 */ public static final Icon ExceptionClass = IconLoader.getIcon("/nodes/exceptionClass.svg"); /** 16x16 */ public static final Icon ExcludedFromCompile = IconLoader.getIcon("/nodes/excludedFromCompile.svg"); /** 16x16 */ public static final Icon ExtractedFolder = IconLoader.getIcon("/nodes/extractedFolder.svg"); /** 16x16 */ public static final Icon Favorite = IconLoader.getIcon("/nodes/favorite.svg"); /** 16x16 */ public static final Icon Field = IconLoader.getIcon("/nodes/field.svg"); /** 16x16 */ public static final Icon FieldPK = IconLoader.getIcon("/nodes/fieldPK.svg"); /** 16x16 */ public static final Icon FinalMark = IconLoader.getIcon("/nodes/finalMark.svg"); /** 16x16 */ public static final Icon Folder = IconLoader.getIcon("/nodes/folder.svg"); /** 16x16 */ public static final Icon Function = IconLoader.getIcon("/nodes/function.svg"); /** 16x16 */ public static final Icon HomeFolder = IconLoader.getIcon("/nodes/homeFolder.svg"); /** 16x16 */ public static final Icon IdeaModule = IconLoader.getIcon("/nodes/ideaModule.svg"); /** 16x16 */ public static final Icon IdeaProject = IconLoader.getIcon("/nodes/ideaProject.svg"); /** 16x16 */ public static final Icon InspectionResults = IconLoader.getIcon("/nodes/inspectionResults.svg"); /** 16x16 */ public static final Icon Interface = IconLoader.getIcon("/nodes/interface.svg"); /** 16x16 */ public static final Icon J2eeParameter = IconLoader.getIcon("/nodes/j2eeParameter.svg"); /** 16x16 */ public static final Icon JarDirectory = IconLoader.getIcon("/nodes/jarDirectory.svg"); /** 16x16 */ public static final Icon JavaDocFolder = IconLoader.getIcon("/nodes/javaDocFolder.svg"); /** 16x16 */ public static final Icon JavaModule = IconLoader.getIcon("/nodes/javaModule.svg"); public final static class Jsf { /** 16x16 */ public static final Icon Component = IconLoader.getIcon("/nodes/jsf/component.svg"); /** 16x16 */ public static final Icon Converter = IconLoader.getIcon("/nodes/jsf/converter.svg"); /** 16x16 */ public static final Icon General = IconLoader.getIcon("/nodes/jsf/general.svg"); /** 16x16 */ public static final Icon ManagedBean = IconLoader.getIcon("/nodes/jsf/managedBean.svg"); /** 16x16 */ public static final Icon NavigationRule = IconLoader.getIcon("/nodes/jsf/navigationRule.svg"); /** 16x16 */ public static final Icon Renderer = IconLoader.getIcon("/nodes/jsf/renderer.svg"); /** 16x16 */ public static final Icon RenderKit = IconLoader.getIcon("/nodes/jsf/renderKit.svg"); /** 16x16 */ public static final Icon Validator = IconLoader.getIcon("/nodes/jsf/validator.svg"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Nodes.Parameter */ @SuppressWarnings("unused") @Deprecated public static final Icon GenericValue = AllIcons.Nodes.Parameter; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Nodes.UpFolder */ @SuppressWarnings("unused") @Deprecated public static final Icon NavigationCase = AllIcons.Nodes.UpFolder; } /** 16x16 */ public static final Icon Jsr45 = IconLoader.getIcon("/nodes/jsr45.svg"); /** 16x16 */ public static final Icon JunitTestMark = IconLoader.getIcon("/nodes/junitTestMark.svg"); /** 16x16 */ public static final Icon KeymapAnt = IconLoader.getIcon("/nodes/keymapAnt.svg"); /** 16x16 */ public static final Icon KeymapEditor = IconLoader.getIcon("/nodes/keymapEditor.svg"); /** 16x16 */ public static final Icon KeymapMainMenu = IconLoader.getIcon("/nodes/keymapMainMenu.svg"); /** 16x16 */ public static final Icon KeymapOther = IconLoader.getIcon("/nodes/keymapOther.svg"); /** 16x16 */ public static final Icon KeymapTools = IconLoader.getIcon("/nodes/keymapTools.svg"); /** 16x16 */ public static final Icon Locked = IconLoader.getIcon("/nodes/locked.svg"); /** 16x16 */ public static final Icon LogFolder = IconLoader.getIcon("/nodes/logFolder.svg"); /** 16x16 */ public static final Icon Method = IconLoader.getIcon("/nodes/method.svg"); /** 16x16 */ public static final Icon MethodReference = IconLoader.getIcon("/nodes/methodReference.svg"); /** 16x16 */ public static final Icon ModelClass = IconLoader.getIcon("/nodes/modelClass.svg"); /** 16x16 */ public static final Icon Models = IconLoader.getIcon("/nodes/models.svg"); /** 16x16 */ public static final Icon Module = IconLoader.getIcon("/nodes/Module.svg"); /** 16x16 */ public static final Icon ModuleGroup = IconLoader.getIcon("/nodes/moduleGroup.svg"); /** 16x16 */ public static final Icon NativeLibrariesFolder = IconLoader.getIcon("/nodes/nativeLibrariesFolder.svg"); /** 16x16 */ public static final Icon NewParameter = IconLoader.getIcon("/nodes/newParameter.svg"); /** 16x16 */ public static final Icon NodePlaceholder = IconLoader.getIcon("/nodes/nodePlaceholder.svg"); /** 16x16 */ public static final Icon NotFavoriteOnHover = IconLoader.getIcon("/nodes/notFavoriteOnHover.svg"); /** 16x16 */ public static final Icon ObjectTypeAttribute = IconLoader.getIcon("/nodes/objectTypeAttribute.svg"); /** 16x16 */ public static final Icon Package = IconLoader.getIcon("/nodes/package.svg"); /** 16x16 */ public static final Icon Padlock = IconLoader.getIcon("/nodes/padlock.svg"); /** 16x16 */ public static final Icon Parameter = IconLoader.getIcon("/nodes/parameter.svg"); /** 16x16 */ public static final Icon Plugin = IconLoader.getIcon("/nodes/plugin.svg"); /** 16x16 */ public static final Icon PluginJB = IconLoader.getIcon("/nodes/pluginJB.svg"); /** 32x32 */ public static final Icon PluginLogo = IconLoader.getIcon("/nodes/pluginLogo.svg"); /** 16x16 */ public static final Icon Pluginnotinstalled = IconLoader.getIcon("/nodes/pluginnotinstalled.svg"); /** 16x16 */ public static final Icon Pluginobsolete = IconLoader.getIcon("/nodes/pluginobsolete.svg"); /** 16x16 */ public static final Icon PluginRestart = IconLoader.getIcon("/nodes/pluginRestart.svg"); /** 16x16 */ public static final Icon PpInvalid = IconLoader.getIcon("/nodes/ppInvalid.svg"); /** 16x16 */ public static final Icon PpJar = IconLoader.getIcon("/nodes/ppJar.svg"); /** 16x16 */ public static final Icon PpJdk = IconLoader.getIcon("/nodes/ppJdk.svg"); /** 16x16 */ public static final Icon PpLib = IconLoader.getIcon("/nodes/ppLib.svg"); /** 16x16 */ public static final Icon PpLibFolder = IconLoader.getIcon("/nodes/ppLibFolder.svg"); /** 16x16 */ public static final Icon PpWeb = IconLoader.getIcon("/nodes/ppWeb.svg"); /** 16x16 */ public static final Icon Project = IconLoader.getIcon("/nodes/project.svg"); /** 16x16 */ public static final Icon Property = IconLoader.getIcon("/nodes/property.svg"); /** 16x16 */ public static final Icon PropertyRead = IconLoader.getIcon("/nodes/propertyRead.svg"); /** 16x16 */ public static final Icon PropertyReadStatic = IconLoader.getIcon("/nodes/propertyReadStatic.svg"); /** 16x16 */ public static final Icon PropertyReadWrite = IconLoader.getIcon("/nodes/propertyReadWrite.svg"); /** 16x16 */ public static final Icon PropertyReadWriteStatic = IconLoader.getIcon("/nodes/propertyReadWriteStatic.svg"); /** 16x16 */ public static final Icon PropertyWrite = IconLoader.getIcon("/nodes/propertyWrite.svg"); /** 16x16 */ public static final Icon PropertyWriteStatic = IconLoader.getIcon("/nodes/propertyWriteStatic.svg"); /** 16x16 */ public static final Icon Read_access = IconLoader.getIcon("/nodes/read-access.svg"); /** 16x16 */ public static final Icon ResourceBundle = IconLoader.getIcon("/nodes/resourceBundle.svg"); /** 16x16 */ public static final Icon RunnableMark = IconLoader.getIcon("/nodes/runnableMark.svg"); /** 16x16 */ public static final Icon Rw_access = IconLoader.getIcon("/nodes/rw-access.svg"); /** 16x16 */ public static final Icon SecurityRole = IconLoader.getIcon("/nodes/securityRole.svg"); /** 16x16 */ public static final Icon Servlet = IconLoader.getIcon("/nodes/servlet.svg"); /** 16x16 */ public static final Icon Shared = IconLoader.getIcon("/nodes/shared.svg"); /** 16x16 */ public static final Icon SortBySeverity = IconLoader.getIcon("/nodes/sortBySeverity.svg"); /** 16x16 */ public static final Icon Static = IconLoader.getIcon("/nodes/static.svg"); /** 16x16 */ public static final Icon StaticMark = IconLoader.getIcon("/nodes/staticMark.svg"); /** 16x16 */ public static final Icon Symlink = IconLoader.getIcon("/nodes/symlink.svg"); /** 16x16 */ public static final Icon TabAlert = IconLoader.getIcon("/nodes/tabAlert.svg"); /** 16x16 */ public static final Icon TabPin = IconLoader.getIcon("/nodes/tabPin.svg"); /** 16x16 */ public static final Icon Tag = IconLoader.getIcon("/nodes/tag.svg"); /** 13x13 */ public static final Icon Target = IconLoader.getIcon("/nodes/target.svg"); /** 16x16 */ public static final Icon Test = IconLoader.getIcon("/nodes/test.svg"); /** 16x16 */ public static final Icon TestGroup = IconLoader.getIcon("/nodes/testGroup.svg"); /** 16x16 */ public static final Icon TestIgnored = IconLoader.getIcon("/nodes/testIgnored.svg"); /** 16x16 */ public static final Icon TestSourceFolder = IconLoader.getIcon("/nodes/testSourceFolder.svg"); /** 16x16 */ public static final Icon Type = IconLoader.getIcon("/nodes/type.svg"); /** 16x16 */ public static final Icon Undeploy = IconLoader.getIcon("/nodes/undeploy.svg"); /** 16x16 */ public static final Icon Unknown = IconLoader.getIcon("/nodes/unknown.svg"); /** 16x16 */ public static final Icon UnknownJdk = IconLoader.getIcon("/nodes/unknownJdk.svg"); /** 16x16 */ public static final Icon UpFolder = IconLoader.getIcon("/nodes/upFolder.svg"); /** 16x16 */ public static final Icon UpLevel = IconLoader.getIcon("/nodes/upLevel.svg"); /** 16x16 */ public static final Icon Variable = IconLoader.getIcon("/nodes/variable.svg"); /** 16x16 */ public static final Icon WarningIntroduction = IconLoader.getIcon("/nodes/warningIntroduction.svg"); /** 16x16 */ public static final Icon WebFolder = IconLoader.getIcon("/nodes/webFolder.svg"); /** 16x16 */ public static final Icon Weblistener = IconLoader.getIcon("/nodes/weblistener.svg"); /** 16x16 */ public static final Icon Write_access = IconLoader.getIcon("/nodes/write-access.svg"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Nodes.Tag */ @SuppressWarnings("unused") @Deprecated public static final Icon Advice = AllIcons.Nodes.Tag; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowDown */ @SuppressWarnings("unused") @Deprecated public static final Icon CollapseNode = AllIcons.General.ArrowDown; /** @deprecated to be removed in IDEA 2020 - see DatabaseIcons.View */ @SuppressWarnings("unused") @Deprecated public static final Icon DataSchema = IconLoader.getIcon("/nodes/dataSchema.svg"); /** @deprecated to be removed in IDEA 2020 - see DatabaseIcons.DatabaseGroup */ @SuppressWarnings("unused") @Deprecated public static final Icon DataSource = IconLoader.getIcon("/nodes/DataSource.svg"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon DataView = IconLoader.getIcon("/nodes/dataView.svg"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon DisabledPointcut = IconLoader.getIcon("/nodes/disabledPointcut.svg"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowRight */ @SuppressWarnings("unused") @Deprecated public static final Icon ExpandNode = AllIcons.General.ArrowRight; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Nodes.Favorite */ @SuppressWarnings("unused") @Deprecated public static final Icon FavoriteOnHover = AllIcons.Nodes.Favorite; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Nodes.Module */ @SuppressWarnings("unused") @Deprecated public static final Icon JavaModuleRoot = AllIcons.Nodes.Module; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon NewException = IconLoader.getIcon("/nodes/newException.svg"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Nodes.Folder */ @SuppressWarnings("unused") @Deprecated public static final Icon NewFolder = AllIcons.Nodes.Folder; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Nodes.TabPin */ @SuppressWarnings("unused") @Deprecated public static final Icon PinToolWindow = AllIcons.Nodes.TabPin; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon PluginUpdate = IconLoader.getIcon("/nodes/pluginUpdate.svg"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Pointcut = IconLoader.getIcon("/nodes/pointcut.svg"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Nodes.Folder */ @SuppressWarnings("unused") @Deprecated public static final Icon PpFile = AllIcons.Nodes.Folder; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon PpWebLogo = IconLoader.getIcon("/nodes/ppWebLogo.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Nodes.Package */ @SuppressWarnings("unused") @Deprecated public static final Icon SourceFolder = AllIcons.Nodes.Package; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Nodes.Folder */ @SuppressWarnings("unused") @Deprecated public static final Icon TreeClosed = AllIcons.Nodes.Folder; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowDown */ @SuppressWarnings("unused") @Deprecated public static final Icon TreeCollapseNode = AllIcons.General.ArrowDown; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon TreeDownArrow = IconLoader.getIcon("/nodes/treeDownArrow.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.ArrowRight */ @SuppressWarnings("unused") @Deprecated public static final Icon TreeExpandNode = AllIcons.General.ArrowRight; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Nodes.Folder */ @SuppressWarnings("unused") @Deprecated public static final Icon TreeOpen = AllIcons.Nodes.Folder; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon TreeRightArrow = IconLoader.getIcon("/nodes/treeRightArrow.png"); } public final static class ObjectBrowser { /** 16x16 */ public static final Icon AbbreviatePackageNames = IconLoader.getIcon("/objectBrowser/abbreviatePackageNames.svg"); /** 16x16 */ public static final Icon CompactEmptyPackages = IconLoader.getIcon("/objectBrowser/compactEmptyPackages.svg"); /** 16x16 */ public static final Icon FlattenModules = IconLoader.getIcon("/objectBrowser/flattenModules.svg"); /** 16x16 */ public static final Icon FlattenPackages = IconLoader.getIcon("/objectBrowser/flattenPackages.svg"); /** 16x16 */ public static final Icon ShowLibraryContents = IconLoader.getIcon("/objectBrowser/showLibraryContents.svg"); /** 16x16 */ public static final Icon ShowMembers = IconLoader.getIcon("/objectBrowser/showMembers.svg"); /** 16x16 */ public static final Icon SortByType = IconLoader.getIcon("/objectBrowser/sortByType.svg"); /** 16x16 */ public static final Icon Sorted = IconLoader.getIcon("/objectBrowser/sorted.svg"); /** 16x16 */ public static final Icon SortedByUsage = IconLoader.getIcon("/objectBrowser/sortedByUsage.svg"); /** 16x16 */ public static final Icon VisibilitySort = IconLoader.getIcon("/objectBrowser/visibilitySort.svg"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Edit */ @SuppressWarnings("unused") @Deprecated public static final Icon ShowEditorHighlighting = AllIcons.Actions.Edit; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.GroupByModule */ @SuppressWarnings("unused") @Deprecated public static final Icon ShowModules = AllIcons.Actions.GroupByModule; } public final static class Plugins { /** 12x12 */ public static final Icon Downloads = IconLoader.getIcon("/plugins/downloads.svg"); /** 15x15 */ public static final Icon ModifierInvalid = IconLoader.getIcon("/plugins/modifierInvalid.svg"); /** 14x14 */ public static final Icon ModifierJBLogo = IconLoader.getIcon("/plugins/modifierJBLogo.svg"); /** 40x40 */ public static final Icon PluginLogo = IconLoader.getIcon("/plugins/pluginLogo.svg"); /** 40x40 */ public static final Icon PluginLogo_40 = IconLoader.getIcon("/plugins/pluginLogo_40.png"); /** 80x80 */ public static final Icon PluginLogo_80 = IconLoader.getIcon("/plugins/pluginLogo_80.png"); /** 40x40 */ public static final Icon PluginLogoDisabled_40 = IconLoader.getIcon("/plugins/pluginLogoDisabled_40.png"); /** 80x80 */ public static final Icon PluginLogoDisabled_80 = IconLoader.getIcon("/plugins/pluginLogoDisabled_80.png"); /** 12x12 */ public static final Icon Rating = IconLoader.getIcon("/plugins/rating.svg"); /** 12x12 */ public static final Icon Updated = IconLoader.getIcon("/plugins/updated.svg"); } public final static class Preferences { /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Appearance = IconLoader.getIcon("/preferences/Appearance.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon CodeStyle = IconLoader.getIcon("/preferences/CodeStyle.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Compiler = IconLoader.getIcon("/preferences/Compiler.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Editor = IconLoader.getIcon("/preferences/Editor.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon FileColors = IconLoader.getIcon("/preferences/FileColors.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon FileTypes = IconLoader.getIcon("/preferences/FileTypes.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon General = IconLoader.getIcon("/preferences/General.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Keymap = IconLoader.getIcon("/preferences/Keymap.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Plugins = IconLoader.getIcon("/preferences/Plugins.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Updates = IconLoader.getIcon("/preferences/Updates.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon VersionControl = IconLoader.getIcon("/preferences/VersionControl.png"); } public final static class Process { public final static class Big { /** 32x32 */ public static final Icon Step_1 = IconLoader.getIcon("/process/big/step_1.svg"); /** 32x32 */ public static final Icon Step_2 = IconLoader.getIcon("/process/big/step_2.svg"); /** 32x32 */ public static final Icon Step_3 = IconLoader.getIcon("/process/big/step_3.svg"); /** 32x32 */ public static final Icon Step_4 = IconLoader.getIcon("/process/big/step_4.svg"); /** 32x32 */ public static final Icon Step_5 = IconLoader.getIcon("/process/big/step_5.svg"); /** 32x32 */ public static final Icon Step_6 = IconLoader.getIcon("/process/big/step_6.svg"); /** 32x32 */ public static final Icon Step_7 = IconLoader.getIcon("/process/big/step_7.svg"); /** 32x32 */ public static final Icon Step_8 = IconLoader.getIcon("/process/big/step_8.svg"); /** 32x32 */ public static final Icon Step_passive = IconLoader.getIcon("/process/big/step_passive.svg"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated /** 32x32 */ public static final Icon Step_10 = IconLoader.getIcon("/process/big/step_4.svg"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated /** 32x32 */ public static final Icon Step_11 = IconLoader.getIcon("/process/big/step_6.svg"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated /** 32x32 */ public static final Icon Step_12 = IconLoader.getIcon("/process/big/step_8.svg"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated /** 32x32 */ public static final Icon Step_9 = IconLoader.getIcon("/process/big/step_2.svg"); } public final static class FS { /** 16x16 */ public static final Icon Step_1 = IconLoader.getIcon("/process/fs/step_1.png"); /** 16x16 */ public static final Icon Step_10 = IconLoader.getIcon("/process/fs/step_10.png"); /** 16x16 */ public static final Icon Step_11 = IconLoader.getIcon("/process/fs/step_11.png"); /** 16x16 */ public static final Icon Step_12 = IconLoader.getIcon("/process/fs/step_12.png"); /** 16x16 */ public static final Icon Step_13 = IconLoader.getIcon("/process/fs/step_13.png"); /** 16x16 */ public static final Icon Step_14 = IconLoader.getIcon("/process/fs/step_14.png"); /** 16x16 */ public static final Icon Step_15 = IconLoader.getIcon("/process/fs/step_15.png"); /** 16x16 */ public static final Icon Step_16 = IconLoader.getIcon("/process/fs/step_16.png"); /** 16x16 */ public static final Icon Step_17 = IconLoader.getIcon("/process/fs/step_17.png"); /** 16x16 */ public static final Icon Step_18 = IconLoader.getIcon("/process/fs/step_18.png"); /** 16x16 */ public static final Icon Step_2 = IconLoader.getIcon("/process/fs/step_2.png"); /** 16x16 */ public static final Icon Step_3 = IconLoader.getIcon("/process/fs/step_3.png"); /** 16x16 */ public static final Icon Step_4 = IconLoader.getIcon("/process/fs/step_4.png"); /** 16x16 */ public static final Icon Step_5 = IconLoader.getIcon("/process/fs/step_5.png"); /** 16x16 */ public static final Icon Step_6 = IconLoader.getIcon("/process/fs/step_6.png"); /** 16x16 */ public static final Icon Step_7 = IconLoader.getIcon("/process/fs/step_7.png"); /** 16x16 */ public static final Icon Step_8 = IconLoader.getIcon("/process/fs/step_8.png"); /** 16x16 */ public static final Icon Step_9 = IconLoader.getIcon("/process/fs/step_9.png"); /** 16x16 */ public static final Icon Step_mask = IconLoader.getIcon("/process/fs/step_mask.png"); /** 16x16 */ public static final Icon Step_passive = IconLoader.getIcon("/process/fs/step_passive.png"); } /** 14x14 */ public static final Icon ProgressPause = IconLoader.getIcon("/process/progressPause.svg"); /** 14x14 */ public static final Icon ProgressPauseHover = IconLoader.getIcon("/process/progressPauseHover.svg"); /** 12x12 */ public static final Icon ProgressPauseSmall = IconLoader.getIcon("/process/progressPauseSmall.svg"); /** 12x12 */ public static final Icon ProgressPauseSmallHover = IconLoader.getIcon("/process/progressPauseSmallHover.svg"); /** 14x14 */ public static final Icon ProgressResume = IconLoader.getIcon("/process/progressResume.svg"); /** 14x14 */ public static final Icon ProgressResumeHover = IconLoader.getIcon("/process/progressResumeHover.svg"); /** 12x12 */ public static final Icon ProgressResumeSmall = IconLoader.getIcon("/process/progressResumeSmall.svg"); /** 12x12 */ public static final Icon ProgressResumeSmallHover = IconLoader.getIcon("/process/progressResumeSmallHover.svg"); public final static class State { /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon GreenOK = IconLoader.getIcon("/process/state/GreenOK.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon GreyProgr = IconLoader.getIcon("/process/state/GreyProgr.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon GreyProgr_1 = IconLoader.getIcon("/process/state/GreyProgr_1.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon GreyProgr_2 = IconLoader.getIcon("/process/state/GreyProgr_2.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon GreyProgr_3 = IconLoader.getIcon("/process/state/GreyProgr_3.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon GreyProgr_4 = IconLoader.getIcon("/process/state/GreyProgr_4.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon GreyProgr_5 = IconLoader.getIcon("/process/state/GreyProgr_5.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon GreyProgr_6 = IconLoader.getIcon("/process/state/GreyProgr_6.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon GreyProgr_7 = IconLoader.getIcon("/process/state/GreyProgr_7.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon GreyProgr_8 = IconLoader.getIcon("/process/state/GreyProgr_8.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon RedExcl = IconLoader.getIcon("/process/state/RedExcl.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon YellowStr = IconLoader.getIcon("/process/state/YellowStr.png"); } /** 16x16 */ public static final Icon Step_1 = IconLoader.getIcon("/process/step_1.svg"); /** 16x16 */ public static final Icon Step_2 = IconLoader.getIcon("/process/step_2.svg"); /** 16x16 */ public static final Icon Step_3 = IconLoader.getIcon("/process/step_3.svg"); /** 16x16 */ public static final Icon Step_4 = IconLoader.getIcon("/process/step_4.svg"); /** 16x16 */ public static final Icon Step_5 = IconLoader.getIcon("/process/step_5.svg"); /** 16x16 */ public static final Icon Step_6 = IconLoader.getIcon("/process/step_6.svg"); /** 16x16 */ public static final Icon Step_7 = IconLoader.getIcon("/process/step_7.svg"); /** 16x16 */ public static final Icon Step_8 = IconLoader.getIcon("/process/step_8.svg"); /** 16x16 */ public static final Icon Step_mask = IconLoader.getIcon("/process/step_mask.svg"); /** 16x16 */ public static final Icon Step_passive = IconLoader.getIcon("/process/step_passive.svg"); /** 14x14 */ public static final Icon Stop = IconLoader.getIcon("/process/stop.svg"); /** 14x14 */ public static final Icon StopHovered = IconLoader.getIcon("/process/stopHovered.svg"); /** 12x12 */ public static final Icon StopSmall = IconLoader.getIcon("/process/stopSmall.svg"); /** 12x12 */ public static final Icon StopSmallHovered = IconLoader.getIcon("/process/stopSmallHovered.svg"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon DisabledDebug = IconLoader.getIcon("/process/disabledDebug.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon DisabledRun = IconLoader.getIcon("/process/disabledRun.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated /** 16x16 */ public static final Icon Step_10 = IconLoader.getIcon("/process/step_4.svg"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated /** 16x16 */ public static final Icon Step_11 = IconLoader.getIcon("/process/step_6.svg"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated /** 16x16 */ public static final Icon Step_12 = IconLoader.getIcon("/process/step_8.svg"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated /** 16x16 */ public static final Icon Step_9 = IconLoader.getIcon("/process/step_2.svg"); } public final static class Providers { /** 16x16 */ public static final Icon Apache = IconLoader.getIcon("/providers/apache.svg"); /** 16x16 */ public static final Icon ApacheDerby = IconLoader.getIcon("/providers/apacheDerby.svg"); /** 16x16 */ public static final Icon Azure = IconLoader.getIcon("/providers/azure.svg"); /** 16x16 */ public static final Icon Cassandra = IconLoader.getIcon("/providers/cassandra.svg"); /** 16x16 */ public static final Icon ClickHouse = IconLoader.getIcon("/providers/clickHouse.svg"); /** 16x16 */ public static final Icon DB2 = IconLoader.getIcon("/providers/DB2.svg"); /** 16x16 */ public static final Icon Eclipse = IconLoader.getIcon("/providers/eclipse.svg"); /** 16x16 */ public static final Icon Exasol = IconLoader.getIcon("/providers/exasol.svg"); /** 16x16 */ public static final Icon Firebird = IconLoader.getIcon("/providers/firebird.svg"); /** 16x16 */ public static final Icon Greenplum = IconLoader.getIcon("/providers/greenplum.svg"); /** 16x16 */ public static final Icon H2 = IconLoader.getIcon("/providers/h2.svg"); /** 16x16 */ public static final Icon HANA = IconLoader.getIcon("/providers/HANA.svg"); /** 16x16 */ public static final Icon Hibernate = IconLoader.getIcon("/providers/hibernate.svg"); /** 16x16 */ public static final Icon Hive = IconLoader.getIcon("/providers/hive.svg"); /** 16x16 */ public static final Icon Hsqldb = IconLoader.getIcon("/providers/hsqldb.svg"); /** 16x16 */ public static final Icon Ibm = IconLoader.getIcon("/providers/ibm.svg"); /** 16x16 */ public static final Icon Informix = IconLoader.getIcon("/providers/informix.svg"); /** 16x16 */ public static final Icon Mariadb = IconLoader.getIcon("/providers/mariadb.svg"); /** 16x16 */ public static final Icon Microsoft = IconLoader.getIcon("/providers/microsoft.svg"); /** 16x16 */ public static final Icon Mysql = IconLoader.getIcon("/providers/mysql.svg"); /** 16x16 */ public static final Icon Oracle = IconLoader.getIcon("/providers/oracle.svg"); /** 16x16 */ public static final Icon Postgresql = IconLoader.getIcon("/providers/postgresql.svg"); /** 16x16 */ public static final Icon Presto = IconLoader.getIcon("/providers/presto.svg"); /** 16x16 */ public static final Icon Redshift = IconLoader.getIcon("/providers/redshift.svg"); /** 16x16 */ public static final Icon Snowflake = IconLoader.getIcon("/providers/snowflake.svg"); /** 16x16 */ public static final Icon Spark = IconLoader.getIcon("/providers/spark.svg"); /** 16x16 */ public static final Icon Sqlite = IconLoader.getIcon("/providers/sqlite.svg"); /** 16x16 */ public static final Icon SqlServer = IconLoader.getIcon("/providers/sqlServer.svg"); /** 16x16 */ public static final Icon Sun = IconLoader.getIcon("/providers/sun.svg"); /** 16x16 */ public static final Icon Sybase = IconLoader.getIcon("/providers/sybase.svg"); /** 16x16 */ public static final Icon Teradata = IconLoader.getIcon("/providers/teradata.svg"); /** 16x16 */ public static final Icon Vertica = IconLoader.getIcon("/providers/vertica.svg"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Bea = IconLoader.getIcon("/providers/bea.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Nodes.Cvs_global */ @SuppressWarnings("unused") @Deprecated public static final Icon Cvs = AllIcons.Nodes.Cvs_global; } public final static class RunConfigurations { /** 16x16 */ public static final Icon Applet = IconLoader.getIcon("/runConfigurations/applet.svg"); /** 16x16 */ public static final Icon Application = IconLoader.getIcon("/runConfigurations/application.svg"); /** 16x16 */ public static final Icon Compound = IconLoader.getIcon("/runConfigurations/compound.svg"); /** 16x16 */ public static final Icon HidePassed = IconLoader.getIcon("/runConfigurations/hidePassed.svg"); /** 16x16 */ public static final Icon IgnoredTest = IconLoader.getIcon("/runConfigurations/ignoredTest.svg"); /** 16x16 */ public static final Icon InvalidConfigurationLayer = IconLoader.getIcon("/runConfigurations/invalidConfigurationLayer.svg"); /** 16x16 */ public static final Icon Junit = IconLoader.getIcon("/runConfigurations/junit.svg"); /** 16x16 */ public static final Icon Remote = IconLoader.getIcon("/runConfigurations/remote.svg"); /** 16x16 */ public static final Icon RerunFailedTests = IconLoader.getIcon("/runConfigurations/rerunFailedTests.svg"); /** 16x16 */ public static final Icon Scroll_down = IconLoader.getIcon("/runConfigurations/scroll_down.svg"); /** 16x16 */ public static final Icon ShowIgnored = IconLoader.getIcon("/runConfigurations/showIgnored.svg"); /** 16x16 */ public static final Icon ShowPassed = IconLoader.getIcon("/runConfigurations/showPassed.svg"); /** 16x16 */ public static final Icon SortbyDuration = IconLoader.getIcon("/runConfigurations/sortbyDuration.svg"); /** 16x16 */ public static final Icon TestCustom = IconLoader.getIcon("/runConfigurations/testCustom.svg"); /** 16x16 */ public static final Icon TestError = IconLoader.getIcon("/runConfigurations/testError.svg"); /** 16x16 */ public static final Icon TestFailed = IconLoader.getIcon("/runConfigurations/testFailed.svg"); /** 16x16 */ public static final Icon TestIgnored = IconLoader.getIcon("/runConfigurations/testIgnored.svg"); /** 16x16 */ public static final Icon TestMark = IconLoader.getIcon("/runConfigurations/testMark.svg"); /** 16x16 */ public static final Icon TestNotRan = IconLoader.getIcon("/runConfigurations/testNotRan.svg"); /** 16x16 */ public static final Icon TestPassed = IconLoader.getIcon("/runConfigurations/testPassed.svg"); /** 16x16 */ public static final Icon TestPaused = IconLoader.getIcon("/runConfigurations/testPaused.svg"); /** 16x16 */ public static final Icon TestSkipped = IconLoader.getIcon("/runConfigurations/testSkipped.svg"); public final static class TestState { /** 12x12 */ public static final Icon Green2 = IconLoader.getIcon("/runConfigurations/testState/green2.svg"); /** 12x12 */ public static final Icon Red2 = IconLoader.getIcon("/runConfigurations/testState/red2.svg"); /** 12x12 */ public static final Icon Run = IconLoader.getIcon("/runConfigurations/testState/run.svg"); /** 12x12 */ public static final Icon Run_run = IconLoader.getIcon("/runConfigurations/testState/run_run.svg"); /** 12x12 */ public static final Icon Yellow2 = IconLoader.getIcon("/runConfigurations/testState/yellow2.svg"); } /** 16x16 */ public static final Icon TestTerminated = IconLoader.getIcon("/runConfigurations/testTerminated.svg"); /** 16x16 */ public static final Icon TestUnknown = IconLoader.getIcon("/runConfigurations/testUnknown.svg"); /** 16x16 */ public static final Icon Tomcat = IconLoader.getIcon("/runConfigurations/tomcat.svg"); /** 16x16 */ public static final Icon ToolbarError = IconLoader.getIcon("/runConfigurations/toolbarError.svg"); /** 16x16 */ public static final Icon ToolbarFailed = IconLoader.getIcon("/runConfigurations/toolbarFailed.svg"); /** 16x16 */ public static final Icon ToolbarPassed = IconLoader.getIcon("/runConfigurations/toolbarPassed.svg"); /** 16x16 */ public static final Icon ToolbarSkipped = IconLoader.getIcon("/runConfigurations/toolbarSkipped.svg"); /** 16x16 */ public static final Icon ToolbarTerminated = IconLoader.getIcon("/runConfigurations/toolbarTerminated.svg"); /** 16x16 */ public static final Icon TrackCoverage = IconLoader.getIcon("/runConfigurations/trackCoverage.svg"); /** 16x16 */ public static final Icon Web_app = IconLoader.getIcon("/runConfigurations/web_app.svg"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.BalloonError */ @SuppressWarnings("unused") @Deprecated public static final Icon ConfigurationWarning = AllIcons.General.BalloonError; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon HideIgnored = IconLoader.getIcon("/runConfigurations/hideIgnored.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon IncludeNonStartedTests_Rerun = IconLoader.getIcon("/runConfigurations/includeNonStartedTests_Rerun.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon LoadingTree = IconLoader.getIcon("/runConfigurations/loadingTree.png"); /** @deprecated to be removed in IDEA 2020 - use DatabaseIcons.ConsoleRun */ @SuppressWarnings("unused") @Deprecated public static final Icon Ql_console = IconLoader.getIcon("/runConfigurations/ql_console.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Menu_saveall */ @SuppressWarnings("unused") @Deprecated public static final Icon SaveTempConfig = AllIcons.Actions.Menu_saveall; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon ScrollToStackTrace = IconLoader.getIcon("/runConfigurations/scrollToStackTrace.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon SelectFirstDefect = IconLoader.getIcon("/runConfigurations/selectFirstDefect.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon SourceAtException = IconLoader.getIcon("/runConfigurations/sourceAtException.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Process.Step_1 */ @SuppressWarnings("unused") @Deprecated public static final Icon TestInProgress1 = AllIcons.Process.Step_1; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Process.Step_2 */ @SuppressWarnings("unused") @Deprecated public static final Icon TestInProgress2 = AllIcons.Process.Step_2; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Process.Step_3 */ @SuppressWarnings("unused") @Deprecated public static final Icon TestInProgress3 = AllIcons.Process.Step_3; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Process.Step_4 */ @SuppressWarnings("unused") @Deprecated public static final Icon TestInProgress4 = AllIcons.Process.Step_4; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Process.Step_5 */ @SuppressWarnings("unused") @Deprecated public static final Icon TestInProgress5 = AllIcons.Process.Step_5; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Process.Step_6 */ @SuppressWarnings("unused") @Deprecated public static final Icon TestInProgress6 = AllIcons.Process.Step_6; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Process.Step_7 */ @SuppressWarnings("unused") @Deprecated public static final Icon TestInProgress7 = AllIcons.Process.Step_7; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Process.Step_8 */ @SuppressWarnings("unused") @Deprecated public static final Icon TestInProgress8 = AllIcons.Process.Step_8; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Nodes.Jsf.Renderer */ @SuppressWarnings("unused") @Deprecated public static final Icon TrackTests = AllIcons.Nodes.Jsf.Renderer; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Help */ @SuppressWarnings("unused") @Deprecated public static final Icon Unknown = AllIcons.Actions.Help; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.ListFiles */ @SuppressWarnings("unused") @Deprecated public static final Icon Variables = AllIcons.Actions.ListFiles; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon WithCoverageLayer = IconLoader.getIcon("/runConfigurations/withCoverageLayer.png"); } public final static class Scope { /** 16x16 */ public static final Icon ChangedFiles = IconLoader.getIcon("/scope/changedFiles.svg"); /** 16x16 */ public static final Icon ChangedFilesAll = IconLoader.getIcon("/scope/changedFilesAll.svg"); /** 16x16 */ public static final Icon Problems = IconLoader.getIcon("/scope/problems.svg"); /** 16x16 */ public static final Icon Production = IconLoader.getIcon("/scope/production.svg"); /** 16x16 */ public static final Icon Scratches = IconLoader.getIcon("/scope/scratches.svg"); /** 16x16 */ public static final Icon Tests = IconLoader.getIcon("/scope/tests.svg"); } public final static class Toolbar { /** 16x16 */ public static final Icon Filterdups = IconLoader.getIcon("/toolbar/filterdups.svg"); /** 16x16 */ public static final Icon Unknown = IconLoader.getIcon("/toolbar/unknown.svg"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.GroupByPackage */ @SuppressWarnings("unused") @Deprecated public static final Icon Folders = AllIcons.Actions.GroupByPackage; } public final static class ToolbarDecorator { /** 16x16 */ public static final Icon AddBlankLine = IconLoader.getIcon("/toolbarDecorator/addBlankLine.svg"); /** 16x16 */ public static final Icon AddClass = IconLoader.getIcon("/toolbarDecorator/addClass.svg"); /** 16x16 */ public static final Icon AddFolder = IconLoader.getIcon("/toolbarDecorator/addFolder.svg"); /** 16x16 */ public static final Icon AddIcon = IconLoader.getIcon("/toolbarDecorator/addIcon.svg"); /** 16x16 */ public static final Icon AddJira = IconLoader.getIcon("/toolbarDecorator/addJira.svg"); /** 16x16 */ public static final Icon AddLink = IconLoader.getIcon("/toolbarDecorator/addLink.svg"); /** 16x16 */ public static final Icon AddPattern = IconLoader.getIcon("/toolbarDecorator/addPattern.svg"); /** 16x16 */ public static final Icon AddRemoteDatasource = IconLoader.getIcon("/toolbarDecorator/addRemoteDatasource.svg"); /** 16x16 */ public static final Icon AddYouTrack = IconLoader.getIcon("/toolbarDecorator/addYouTrack.svg"); /** 16x16 */ public static final Icon Export = IconLoader.getIcon("/toolbarDecorator/export.svg"); /** 16x16 */ public static final Icon Import = IconLoader.getIcon("/toolbarDecorator/import.svg"); public final static class Mac { /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.Add */ @SuppressWarnings("unused") @Deprecated public static final Icon Add = AllIcons.General.Add; /** @deprecated to be removed in IDEA 2020 - use AllIcons.ToolbarDecorator.AddBlankLine */ @SuppressWarnings("unused") @Deprecated public static final Icon AddBlankLine = AllIcons.ToolbarDecorator.AddBlankLine; /** @deprecated to be removed in IDEA 2020 - use AllIcons.ToolbarDecorator.AddClass */ @SuppressWarnings("unused") @Deprecated public static final Icon AddClass = AllIcons.ToolbarDecorator.AddClass; /** @deprecated to be removed in IDEA 2020 - use AllIcons.ToolbarDecorator.AddFolder */ @SuppressWarnings("unused") @Deprecated public static final Icon AddFolder = AllIcons.ToolbarDecorator.AddFolder; /** @deprecated to be removed in IDEA 2020 - use AllIcons.ToolbarDecorator.AddIcon */ @SuppressWarnings("unused") @Deprecated public static final Icon AddIcon = AllIcons.ToolbarDecorator.AddIcon; /** @deprecated to be removed in IDEA 2020 - use AllIcons.ToolbarDecorator.AddJira */ @SuppressWarnings("unused") @Deprecated public static final Icon AddJira = AllIcons.ToolbarDecorator.AddJira; /** @deprecated to be removed in IDEA 2020 - use AllIcons.ToolbarDecorator.AddLink */ @SuppressWarnings("unused") @Deprecated public static final Icon AddLink = AllIcons.ToolbarDecorator.AddLink; /** @deprecated to be removed in IDEA 2020 - use AllIcons.ToolbarDecorator.AddFolder */ @SuppressWarnings("unused") @Deprecated public static final Icon AddPackage = AllIcons.ToolbarDecorator.AddFolder; /** @deprecated to be removed in IDEA 2020 - use AllIcons.ToolbarDecorator.AddPattern */ @SuppressWarnings("unused") @Deprecated public static final Icon AddPattern = AllIcons.ToolbarDecorator.AddPattern; /** @deprecated to be removed in IDEA 2020 - use AllIcons.ToolbarDecorator.AddRemoteDatasource */ @SuppressWarnings("unused") @Deprecated public static final Icon AddRemoteDatasource = AllIcons.ToolbarDecorator.AddRemoteDatasource; /** @deprecated to be removed in IDEA 2020 - use AllIcons.ToolbarDecorator.AddYouTrack */ @SuppressWarnings("unused") @Deprecated public static final Icon AddYouTrack = AllIcons.ToolbarDecorator.AddYouTrack; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Analyze = IconLoader.getIcon("/toolbarDecorator/mac/analyze.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Edit */ @SuppressWarnings("unused") @Deprecated public static final Icon Edit = AllIcons.Actions.Edit; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.MoveDown */ @SuppressWarnings("unused") @Deprecated public static final Icon MoveDown = AllIcons.Actions.MoveDown; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.MoveUp */ @SuppressWarnings("unused") @Deprecated public static final Icon MoveUp = AllIcons.Actions.MoveUp; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.Remove */ @SuppressWarnings("unused") @Deprecated public static final Icon Remove = AllIcons.General.Remove; } /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.Add */ @SuppressWarnings("unused") @Deprecated public static final Icon Add = AllIcons.General.Add; /** @deprecated to be removed in IDEA 2020 - use AllIcons.ToolbarDecorator.AddFolder */ @SuppressWarnings("unused") @Deprecated public static final Icon AddPackage = AllIcons.ToolbarDecorator.AddFolder; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon Analyze = IconLoader.getIcon("/toolbarDecorator/analyze.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Edit */ @SuppressWarnings("unused") @Deprecated public static final Icon Edit = AllIcons.Actions.Edit; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.MoveDown */ @SuppressWarnings("unused") @Deprecated public static final Icon MoveDown = AllIcons.Actions.MoveDown; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.MoveUp */ @SuppressWarnings("unused") @Deprecated public static final Icon MoveUp = AllIcons.Actions.MoveUp; /** @deprecated to be removed in IDEA 2020 - use AllIcons.General.Remove */ @SuppressWarnings("unused") @Deprecated public static final Icon Remove = AllIcons.General.Remove; } public final static class Toolwindows { /** 13x13 */ public static final Icon Documentation = IconLoader.getIcon("/toolwindows/documentation.svg"); /** 13x13 */ public static final Icon Problems = IconLoader.getIcon("/toolwindows/problems.svg"); /** 13x13 */ public static final Icon ProblemsEmpty = IconLoader.getIcon("/toolwindows/problemsEmpty.svg"); /** 13x13 */ public static final Icon ToolWindowAnt = IconLoader.getIcon("/toolwindows/toolWindowAnt.svg"); /** 13x13 */ public static final Icon ToolWindowBuild = IconLoader.getIcon("/toolwindows/toolWindowBuild.svg"); /** 13x13 */ public static final Icon ToolWindowChanges = IconLoader.getIcon("/toolwindows/toolWindowChanges.svg"); /** 13x13 */ public static final Icon ToolWindowCommander = IconLoader.getIcon("/toolwindows/toolWindowCommander.svg"); /** 13x13 */ public static final Icon ToolWindowCoverage = IconLoader.getIcon("/toolwindows/toolWindowCoverage.svg"); /** 13x13 */ public static final Icon ToolWindowDebugger = IconLoader.getIcon("/toolwindows/toolWindowDebugger.svg"); /** 13x13 */ public static final Icon ToolWindowFavorites = IconLoader.getIcon("/toolwindows/toolWindowFavorites.svg"); /** 13x13 */ public static final Icon ToolWindowFind = IconLoader.getIcon("/toolwindows/toolWindowFind.svg"); /** 13x13 */ public static final Icon ToolWindowHierarchy = IconLoader.getIcon("/toolwindows/toolWindowHierarchy.svg"); /** 13x13 */ public static final Icon ToolWindowInspection = IconLoader.getIcon("/toolwindows/toolWindowInspection.svg"); /** 13x13 */ public static final Icon ToolWindowMessages = IconLoader.getIcon("/toolwindows/toolWindowMessages.svg"); /** 13x13 */ public static final Icon ToolWindowModuleDependencies = IconLoader.getIcon("/toolwindows/toolWindowModuleDependencies.svg"); /** 13x13 */ public static final Icon ToolWindowPalette = IconLoader.getIcon("/toolwindows/toolWindowPalette.svg"); /** 13x13 */ public static final Icon ToolWindowPreview = IconLoader.getIcon("/toolwindows/toolWindowPreview.png"); /** 13x13 */ public static final Icon ToolWindowProfiler = IconLoader.getIcon("/toolwindows/toolWindowProfiler.svg"); /** 13x13 */ public static final Icon ToolWindowProject = IconLoader.getIcon("/toolwindows/toolWindowProject.svg"); /** 13x13 */ public static final Icon ToolWindowRun = IconLoader.getIcon("/toolwindows/toolWindowRun.svg"); /** 13x13 */ public static final Icon ToolWindowStructure = IconLoader.getIcon("/toolwindows/toolWindowStructure.svg"); /** 13x13 */ public static final Icon ToolWindowTodo = IconLoader.getIcon("/toolwindows/toolWindowTodo.svg"); /** 13x13 */ public static final Icon ToolWindowUIDesigner = IconLoader.getIcon("/toolwindows/toolWindowUIDesigner.svg"); /** 13x13 */ public static final Icon WebToolWindow = IconLoader.getIcon("/toolwindows/webToolWindow.svg"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon ToolWindowCvs = IconLoader.getIcon("/toolwindows/toolWindowCvs.png"); } public final static class Vcs { /** 16x16 */ public static final Icon Arrow_left = IconLoader.getIcon("/vcs/arrow_left.svg"); /** 16x16 */ public static final Icon Arrow_right = IconLoader.getIcon("/vcs/arrow_right.svg"); /** 16x16 */ public static final Icon Branch = IconLoader.getIcon("/vcs/branch.svg"); /** 16x16 */ public static final Icon Changelist = IconLoader.getIcon("/vcs/changelist.svg"); /** 16x16 */ public static final Icon CommitNode = IconLoader.getIcon("/vcs/commitNode.svg"); /** 16x16 */ public static final Icon Equal = IconLoader.getIcon("/vcs/equal.svg"); /** 16x16 */ public static final Icon Folders = IconLoader.getIcon("/vcs/folders.svg"); /** 16x16 */ public static final Icon History = IconLoader.getIcon("/vcs/history.svg"); /** 16x16 */ public static final Icon Ignore_file = IconLoader.getIcon("/vcs/ignore_file.svg"); /** 16x16 */ public static final Icon Merge = IconLoader.getIcon("/vcs/merge.svg"); /** 16x16 */ public static final Icon Not_equal = IconLoader.getIcon("/vcs/not_equal.svg"); /** 16x16 */ public static final Icon Patch = IconLoader.getIcon("/vcs/patch.svg"); /** 16x16 */ public static final Icon Patch_applied = IconLoader.getIcon("/vcs/patch_applied.svg"); /** 16x16 */ public static final Icon Patch_file = IconLoader.getIcon("/vcs/patch_file.svg"); /** 16x16 */ public static final Icon Push = IconLoader.getIcon("/vcs/push.svg"); /** 16x16 */ public static final Icon Remove = IconLoader.getIcon("/vcs/remove.svg"); /** 16x16 */ public static final Icon Shelve = IconLoader.getIcon("/vcs/Shelve.svg"); /** 16x16 */ public static final Icon ShelveSilent = IconLoader.getIcon("/vcs/shelveSilent.svg"); /** 16x16 */ public static final Icon ShowUnversionedFiles = IconLoader.getIcon("/vcs/ShowUnversionedFiles.svg"); /** 16x16 */ public static final Icon Unshelve = IconLoader.getIcon("/vcs/Unshelve.svg"); /** 16x16 */ public static final Icon UnshelveSilent = IconLoader.getIcon("/vcs/unshelveSilent.svg"); public final static class Vendors { /** 16x16 */ public static final Icon Github = IconLoader.getIcon("/vcs/vendors/github.svg"); } /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon CheckSpelling = IconLoader.getIcon("/vcs/checkSpelling.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.Vcs.Folders */ @SuppressWarnings("unused") @Deprecated public static final Icon MapBase = AllIcons.Vcs.Folders; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.ShowAsTree */ @SuppressWarnings("unused") @Deprecated public static final Icon MergeSourcesTree = AllIcons.Actions.ShowAsTree; /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon ResetStrip = IconLoader.getIcon("/vcs/resetStrip.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon RestoreDefaultSize = IconLoader.getIcon("/vcs/restoreDefaultSize.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon StripDown = IconLoader.getIcon("/vcs/stripDown.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon StripNull = IconLoader.getIcon("/vcs/stripNull.png"); /** @deprecated to be removed in IDEA 2020 */ @SuppressWarnings("unused") @Deprecated public static final Icon StripUp = IconLoader.getIcon("/vcs/stripUp.png"); } public final static class Webreferences { /** 16x16 */ public static final Icon Server = IconLoader.getIcon("/webreferences/server.svg"); } public final static class Welcome { /** 32x32 */ public static final Icon CreateDesktopEntry = IconLoader.getIcon("/welcome/createDesktopEntry.png"); /** 16x16 */ public static final Icon CreateNewProject = IconLoader.getIcon("/welcome/createNewProject.svg"); /** 16x16 */ public static final Icon FromVCS = IconLoader.getIcon("/welcome/fromVCS.svg"); public final static class Project { /** 10x10 */ public static final Icon Remove_hover = IconLoader.getIcon("/welcome/project/remove-hover.svg"); /** 10x10 */ public static final Icon Remove = IconLoader.getIcon("/welcome/project/remove.svg"); } /** 32x32 */ public static final Icon Register = IconLoader.getIcon("/welcome/register.png"); /** @deprecated to be removed in IDEA 2020 - use AllIcons.ToolbarDecorator.Import */ @SuppressWarnings("unused") @Deprecated public static final Icon CreateNewProjectfromExistingFiles = AllIcons.ToolbarDecorator.Import; /** @deprecated to be removed in IDEA 2020 - use AllIcons.ToolbarDecorator.Import */ @SuppressWarnings("unused") @Deprecated public static final Icon ImportProject = AllIcons.ToolbarDecorator.Import; /** @deprecated to be removed in IDEA 2020 - use AllIcons.Actions.Menu_open */ @SuppressWarnings("unused") @Deprecated public static final Icon OpenProject = AllIcons.Actions.Menu_open; } public final static class Windows { /** 16x16 */ public static final Icon CloseActive = IconLoader.getIcon("/windows/closeActive.svg"); /** 16x16 */ public static final Icon CloseHover = IconLoader.getIcon("/windows/closeHover.svg"); /** 16x16 */ public static final Icon CloseInactive = IconLoader.getIcon("/windows/closeInactive.svg"); /** 16x16 */ public static final Icon CloseSmall = IconLoader.getIcon("/windows/closeSmall.svg"); /** 16x16 */ public static final Icon Help = IconLoader.getIcon("/windows/help.svg"); /** 16x16 */ public static final Icon HelpButton = IconLoader.getIcon("/windows/helpButton.svg"); /** 16x16 */ public static final Icon HelpButtonInactive = IconLoader.getIcon("/windows/helpButtonInactive.svg"); /** 16x16 */ public static final Icon HelpInactive = IconLoader.getIcon("/windows/helpInactive.svg"); /** 16x16 */ public static final Icon Maximize = IconLoader.getIcon("/windows/maximize.svg"); /** 16x16 */ public static final Icon MaximizeInactive = IconLoader.getIcon("/windows/maximizeInactive.svg"); /** 16x16 */ public static final Icon MaximizeSmall = IconLoader.getIcon("/windows/maximizeSmall.svg"); /** 16x16 */ public static final Icon Minimize = IconLoader.getIcon("/windows/minimize.svg"); /** 16x16 */ public static final Icon MinimizeInactive = IconLoader.getIcon("/windows/minimizeInactive.svg"); /** 16x16 */ public static final Icon MinimizeSmall = IconLoader.getIcon("/windows/minimizeSmall.svg"); /** 16x16 */ public static final Icon Restore = IconLoader.getIcon("/windows/restore.svg"); /** 16x16 */ public static final Icon RestoreInactive = IconLoader.getIcon("/windows/restoreInactive.svg"); /** 16x16 */ public static final Icon RestoreSmall = IconLoader.getIcon("/windows/restoreSmall.svg"); } public final static class Xml { public final static class Browsers { /** 16x16 */ public static final Icon Canary16 = IconLoader.getIcon("/xml/browsers/canary16.svg"); /** 16x16 */ public static final Icon Chrome16 = IconLoader.getIcon("/xml/browsers/chrome16.svg"); /** 16x16 */ public static final Icon Chromium16 = IconLoader.getIcon("/xml/browsers/chromium16.svg"); /** 16x16 */ public static final Icon Edge16 = IconLoader.getIcon("/xml/browsers/edge16.svg"); /** 16x16 */ public static final Icon Explorer16 = IconLoader.getIcon("/xml/browsers/explorer16.svg"); /** 16x16 */ public static final Icon Firefox16 = IconLoader.getIcon("/xml/browsers/firefox16.svg"); /** 16x16 */ public static final Icon Nwjs16 = IconLoader.getIcon("/xml/browsers/nwjs16.svg"); /** 16x16 */ public static final Icon Opera16 = IconLoader.getIcon("/xml/browsers/opera16.svg"); /** 16x16 */ public static final Icon Safari16 = IconLoader.getIcon("/xml/browsers/safari16.svg"); /** 16x16 */ public static final Icon Yandex16 = IconLoader.getIcon("/xml/browsers/yandex16.svg"); } /** 16x16 */ public static final Icon Css_class = IconLoader.getIcon("/xml/css_class.svg"); /** 16x16 */ public static final Icon Html5 = IconLoader.getIcon("/xml/html5.svg"); /** 16x16 */ public static final Icon Html_id = IconLoader.getIcon("/xml/html_id.svg"); } }
Fix CommunityIconClassesTest
platform/util/src/com/intellij/icons/AllIcons.java
Fix CommunityIconClassesTest
Java
apache-2.0
6e21109499f6a18a795ede111c1ac8cc46a431d0
0
apache/solr,apache/solr,apache/solr,apache/solr,apache/solr
/** * 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.solr.handler; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.io.Writer; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import org.apache.commons.io.IOUtils; import org.apache.solr.core.SolrCore; import org.apache.solr.core.SolrException; import org.apache.solr.util.ContentStream; import org.apache.solr.request.SolrQueryRequest; import org.apache.solr.request.SolrQueryResponse; import org.apache.solr.schema.IndexSchema; import org.apache.solr.schema.SchemaField; import org.apache.solr.update.AddUpdateCommand; import org.apache.solr.update.CommitUpdateCommand; import org.apache.solr.update.DeleteUpdateCommand; import org.apache.solr.update.DocumentBuilder; import org.apache.solr.update.UpdateHandler; import org.apache.solr.util.NamedList; import org.apache.solr.util.StrUtils; import org.apache.solr.util.XML; import org.apache.solr.util.SimpleOrderedMap; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; public class XmlUpdateRequestHandler extends RequestHandlerBase { public static Logger log = Logger.getLogger(XmlUpdateRequestHandler.class.getName()); private XmlPullParserFactory factory; // This must be called AFTER solrCore has initalized! // otherwise you get a big bad error loop public void init(NamedList args) { super.init( args ); try { factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(false); } catch (XmlPullParserException e) { throw new RuntimeException(e); } } @Override public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception { Iterable<ContentStream> streams = req.getContentStreams(); if( streams == null ) { if( !RequestHandlerUtils.handleCommit(req, rsp, false) ) { throw new SolrException( 400, "missing content stream" ); } return; } // Cycle through each stream for( ContentStream stream : req.getContentStreams() ) { Reader reader = stream.getReader(); try { rsp.add( "update", this.update( reader ) ); } finally { IOUtils.closeQuietly(reader); } } // perhaps commit when we are done RequestHandlerUtils.handleCommit(req, rsp, false); } public NamedList update( Reader reader ) throws Exception { SolrCore core = SolrCore.getSolrCore(); IndexSchema schema = core.getSchema(); UpdateHandler updateHandler = core.getUpdateHandler(); // TODO: What results should be returned? SimpleOrderedMap res = new SimpleOrderedMap(); XmlPullParser xpp = factory.newPullParser(); long startTime=System.currentTimeMillis(); xpp.setInput(reader); xpp.nextTag(); String currTag = xpp.getName(); if ("add".equals(currTag)) { log.finest("SolrCore.update(add)"); AddUpdateCommand cmd = new AddUpdateCommand(); cmd.allowDups=false; // the default int status=0; boolean pendingAttr=false, committedAttr=false; int attrcount = xpp.getAttributeCount(); for (int i=0; i<attrcount; i++) { String attrName = xpp.getAttributeName(i); String attrVal = xpp.getAttributeValue(i); if ("allowDups".equals(attrName)) { cmd.allowDups = StrUtils.parseBoolean(attrVal); } else if ("overwritePending".equals(attrName)) { cmd.overwritePending = StrUtils.parseBoolean(attrVal); pendingAttr=true; } else if ("overwriteCommitted".equals(attrName)) { cmd.overwriteCommitted = StrUtils.parseBoolean(attrVal); committedAttr=true; } else { log.warning("Unknown attribute id in add:" + attrName); } } //set defaults for committed and pending based on allowDups value if (!pendingAttr) cmd.overwritePending=!cmd.allowDups; if (!committedAttr) cmd.overwriteCommitted=!cmd.allowDups; DocumentBuilder builder = new DocumentBuilder(schema); SchemaField uniqueKeyField = schema.getUniqueKeyField(); int eventType=0; // accumulate responses List<String> added = new ArrayList<String>(10); while(true) { // this may be our second time through the loop in the case // that there are multiple docs in the add... so make sure that // objects can handle that. cmd.indexedId = null; // reset the id for this add if (eventType !=0) { eventType=xpp.getEventType(); if (eventType==XmlPullParser.END_DOCUMENT) break; } // eventType = xpp.next(); eventType = xpp.nextTag(); if (eventType == XmlPullParser.END_TAG || eventType == XmlPullParser.END_DOCUMENT) break; // should match </add> readDoc(builder,xpp); builder.endDoc(); cmd.doc = builder.getDoc(); log.finest("adding doc..."); updateHandler.addDoc(cmd); String docId = null; if (uniqueKeyField!=null) docId = schema.printableUniqueKey(cmd.doc); added.add(docId); } // end while // write log and result StringBuilder out = new StringBuilder(); for (String docId: added) if(docId != null) out.append(docId + ","); String outMsg = out.toString(); if(outMsg.length() > 0) outMsg = outMsg.substring(0, outMsg.length() - 1); log.info("added id={" + outMsg + "} in " + (System.currentTimeMillis()-startTime) + "ms"); // Add output res.add( "added", outMsg ); } // end add else if ("commit".equals(currTag) || "optimize".equals(currTag)) { log.finest("parsing "+currTag); CommitUpdateCommand cmd = new CommitUpdateCommand("optimize".equals(currTag)); boolean sawWaitSearcher=false, sawWaitFlush=false; int attrcount = xpp.getAttributeCount(); for (int i=0; i<attrcount; i++) { String attrName = xpp.getAttributeName(i); String attrVal = xpp.getAttributeValue(i); if ("waitFlush".equals(attrName)) { cmd.waitFlush = StrUtils.parseBoolean(attrVal); sawWaitFlush=true; } else if ("waitSearcher".equals(attrName)) { cmd.waitSearcher = StrUtils.parseBoolean(attrVal); sawWaitSearcher=true; } else { log.warning("unexpected attribute commit/@" + attrName); } } // If waitFlush is specified and waitSearcher wasn't, then // clear waitSearcher. if (sawWaitFlush && !sawWaitSearcher) { cmd.waitSearcher=false; } updateHandler.commit(cmd); if ("optimize".equals(currTag)) { log.info("optimize 0 "+(System.currentTimeMillis()-startTime)); } else { log.info("commit 0 "+(System.currentTimeMillis()-startTime)); } while (true) { int eventType = xpp.nextTag(); if (eventType == XmlPullParser.END_TAG) break; // match </commit> } // add debug output res.add( cmd.optimize?"optimize":"commit", "" ); } // end commit else if ("delete".equals(currTag)) { log.finest("parsing delete"); DeleteUpdateCommand cmd = new DeleteUpdateCommand(); cmd.fromPending=true; cmd.fromCommitted=true; int attrcount = xpp.getAttributeCount(); for (int i=0; i<attrcount; i++) { String attrName = xpp.getAttributeName(i); String attrVal = xpp.getAttributeValue(i); if ("fromPending".equals(attrName)) { cmd.fromPending = StrUtils.parseBoolean(attrVal); } else if ("fromCommitted".equals(attrName)) { cmd.fromCommitted = StrUtils.parseBoolean(attrVal); } else { log.warning("unexpected attribute delete/@" + attrName); } } int eventType = xpp.nextTag(); currTag = xpp.getName(); String val = xpp.nextText(); if ("id".equals(currTag)) { cmd.id = val; updateHandler.delete(cmd); log.info("delete(id " + val + ") 0 " + (System.currentTimeMillis()-startTime)); } else if ("query".equals(currTag)) { cmd.query = val; updateHandler.deleteByQuery(cmd); log.info("deleteByQuery(query " + val + ") 0 " + (System.currentTimeMillis()-startTime)); } else { log.warning("unexpected XML tag /delete/"+currTag); throw new SolrException(400,"unexpected XML tag /delete/"+currTag); } res.add( "delete", "" ); while (xpp.nextTag() != XmlPullParser.END_TAG); } // end delete return res; } private void readDoc(DocumentBuilder builder, XmlPullParser xpp) throws IOException, XmlPullParserException { // xpp should be at <doc> at this point builder.startDoc(); int attrcount = xpp.getAttributeCount(); float docBoost = 1.0f; for (int i=0; i<attrcount; i++) { String attrName = xpp.getAttributeName(i); String attrVal = xpp.getAttributeValue(i); if ("boost".equals(attrName)) { docBoost = Float.parseFloat(attrVal); builder.setBoost(docBoost); } else { log.warning("Unknown attribute doc/@" + attrName); } } if (docBoost != 1.0f) builder.setBoost(docBoost); // while (findNextTag(xpp,"field") != XmlPullParser.END_DOCUMENT) { while(true) { int eventType = xpp.nextTag(); if (eventType == XmlPullParser.END_TAG) break; // </doc> String tname=xpp.getName(); // System.out.println("FIELD READER AT TAG " + tname); if (!"field".equals(tname)) { log.warning("unexpected XML tag doc/"+tname); throw new SolrException(400,"unexpected XML tag doc/"+tname); } // // get field name and parse field attributes // attrcount = xpp.getAttributeCount(); String name=null; float boost=1.0f; boolean isNull=false; for (int i=0; i<attrcount; i++) { String attrName = xpp.getAttributeName(i); String attrVal = xpp.getAttributeValue(i); if ("name".equals(attrName)) { name=attrVal; } else if ("boost".equals(attrName)) { boost=Float.parseFloat(attrVal); } else if ("null".equals(attrName)) { isNull=StrUtils.parseBoolean(attrVal); } else { log.warning("Unknown attribute doc/field/@" + attrName); } } // now get the field value String val = xpp.nextText(); // todo... text event for <field></field>??? // need this line for isNull??? // Don't add fields marked as null (for now at least) if (!isNull) { if (boost != 1.0f) { builder.addField(name,val,boost); } else { builder.addField(name,val); } } // do I have to do a nextTag here to read the end_tag? } // end field loop } /** * A Convenience method for getting back a simple XML string indicating * successs or failure from an XML formated Update (from the Reader) */ public void doLegacyUpdate(Reader input, Writer output) { try { NamedList ignored = this.update( input ); output.write("<result status=\"0\"></result>"); } catch( Exception ex ) { try { XML.writeXML(output,"result",SolrException.toStr(ex),"status","1"); } catch (Exception ee) { log.severe("Error writing to output stream: "+ee); } } } //////////////////////// SolrInfoMBeans methods ////////////////////// @Override public String getDescription() { return "Add documents with XML"; } @Override public String getVersion() { return "$Revision$"; } @Override public String getSourceId() { return "$Id$"; } @Override public String getSource() { return "$URL$"; } }
src/java/org/apache/solr/handler/XmlUpdateRequestHandler.java
/** * 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.solr.handler; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.io.Writer; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import org.apache.commons.io.IOUtils; import org.apache.solr.core.SolrCore; import org.apache.solr.core.SolrException; import org.apache.solr.util.ContentStream; import org.apache.solr.request.SolrQueryRequest; import org.apache.solr.request.SolrQueryResponse; import org.apache.solr.schema.IndexSchema; import org.apache.solr.schema.SchemaField; import org.apache.solr.update.AddUpdateCommand; import org.apache.solr.update.CommitUpdateCommand; import org.apache.solr.update.DeleteUpdateCommand; import org.apache.solr.update.DocumentBuilder; import org.apache.solr.update.UpdateHandler; import org.apache.solr.util.NamedList; import org.apache.solr.util.StrUtils; import org.apache.solr.util.XML; import org.apache.solr.util.SimpleOrderedMap; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; public class XmlUpdateRequestHandler extends RequestHandlerBase { public static Logger log = Logger.getLogger(XmlUpdateRequestHandler.class.getName()); private XmlPullParserFactory factory; // This must be called AFTER solrCore has initalized! // otherwise you get a big bad error loop public void init(NamedList args) { super.init( args ); try { factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(false); } catch (XmlPullParserException e) { throw new RuntimeException(e); } } @Override public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception { Iterable<ContentStream> streams = req.getContentStreams(); if( streams == null ) { if( !RequestHandlerUtils.handleCommit(req, rsp, false) ) { throw new SolrException( 400, "missing content stream" ); } return; } // Cycle through each stream for( ContentStream stream : req.getContentStreams() ) { Reader reader = stream.getReader(); try { rsp.add( "update", this.update( reader ) ); } finally { IOUtils.closeQuietly(reader); } } // perhaps commit when we are done RequestHandlerUtils.handleCommit(req, rsp, false); } public NamedList update( Reader reader ) throws Exception { SolrCore core = SolrCore.getSolrCore(); IndexSchema schema = core.getSchema(); UpdateHandler updateHandler = core.getUpdateHandler(); // TODO: What results should be returned? SimpleOrderedMap res = new SimpleOrderedMap(); XmlPullParser xpp = factory.newPullParser(); long startTime=System.currentTimeMillis(); xpp.setInput(reader); xpp.nextTag(); String currTag = xpp.getName(); if ("add".equals(currTag)) { log.finest("SolrCore.update(add)"); AddUpdateCommand cmd = new AddUpdateCommand(); cmd.allowDups=false; // the default int status=0; boolean pendingAttr=false, committedAttr=false; int attrcount = xpp.getAttributeCount(); for (int i=0; i<attrcount; i++) { String attrName = xpp.getAttributeName(i); String attrVal = xpp.getAttributeValue(i); if ("allowDups".equals(attrName)) { cmd.allowDups = StrUtils.parseBoolean(attrVal); } else if ("overwritePending".equals(attrName)) { cmd.overwritePending = StrUtils.parseBoolean(attrVal); pendingAttr=true; } else if ("overwriteCommitted".equals(attrName)) { cmd.overwriteCommitted = StrUtils.parseBoolean(attrVal); committedAttr=true; } else { log.warning("Unknown attribute id in add:" + attrName); } } //set defaults for committed and pending based on allowDups value if (!pendingAttr) cmd.overwritePending=!cmd.allowDups; if (!committedAttr) cmd.overwriteCommitted=!cmd.allowDups; DocumentBuilder builder = new DocumentBuilder(schema); SchemaField uniqueKeyField = schema.getUniqueKeyField(); int eventType=0; // accumulate responses List<String> added = new ArrayList<String>(10); while(true) { // this may be our second time through the loop in the case // that there are multiple docs in the add... so make sure that // objects can handle that. cmd.indexedId = null; // reset the id for this add if (eventType !=0) { eventType=xpp.getEventType(); if (eventType==XmlPullParser.END_DOCUMENT) break; } // eventType = xpp.next(); eventType = xpp.nextTag(); if (eventType == XmlPullParser.END_TAG || eventType == XmlPullParser.END_DOCUMENT) break; // should match </add> readDoc(builder,xpp); builder.endDoc(); cmd.doc = builder.getDoc(); log.finest("adding doc..."); updateHandler.addDoc(cmd); String docId = null; if (uniqueKeyField!=null) docId = schema.printableUniqueKey(cmd.doc); added.add(docId); } // end while // write log and result StringBuilder out = new StringBuilder(); for (String docId: added) if(docId != null) out.append(docId + ","); String outMsg = out.toString(); if(outMsg.length() > 0) outMsg = outMsg.substring(0, outMsg.length() - 1); log.info("added id={" + outMsg + "} in " + (System.currentTimeMillis()-startTime) + "ms"); // Add output res.add( "added", outMsg ); } // end add else if ("commit".equals(currTag) || "optimize".equals(currTag)) { log.finest("parsing "+currTag); CommitUpdateCommand cmd = new CommitUpdateCommand("optimize".equals(currTag)); boolean sawWaitSearcher=false, sawWaitFlush=false; int attrcount = xpp.getAttributeCount(); for (int i=0; i<attrcount; i++) { String attrName = xpp.getAttributeName(i); String attrVal = xpp.getAttributeValue(i); if ("waitFlush".equals(attrName)) { cmd.waitFlush = StrUtils.parseBoolean(attrVal); sawWaitFlush=true; } else if ("waitSearcher".equals(attrName)) { cmd.waitSearcher = StrUtils.parseBoolean(attrVal); sawWaitSearcher=true; } else { log.warning("unexpected attribute commit/@" + attrName); } } // If waitFlush is specified and waitSearcher wasn't, then // clear waitSearcher. if (sawWaitFlush && !sawWaitSearcher) { cmd.waitSearcher=false; } updateHandler.commit(cmd); if ("optimize".equals(currTag)) { log.info("optimize 0 "+(System.currentTimeMillis()-startTime)); } else { log.info("commit 0 "+(System.currentTimeMillis()-startTime)); } while (true) { int eventType = xpp.nextTag(); if (eventType == XmlPullParser.END_TAG) break; // match </commit> } // add debug output res.add( cmd.optimize?"optimize":"commit", "" ); } // end commit else if ("delete".equals(currTag)) { log.finest("parsing delete"); DeleteUpdateCommand cmd = new DeleteUpdateCommand(); cmd.fromPending=true; cmd.fromCommitted=true; int attrcount = xpp.getAttributeCount(); for (int i=0; i<attrcount; i++) { String attrName = xpp.getAttributeName(i); String attrVal = xpp.getAttributeValue(i); if ("fromPending".equals(attrName)) { cmd.fromPending = StrUtils.parseBoolean(attrVal); } else if ("fromCommitted".equals(attrName)) { cmd.fromCommitted = StrUtils.parseBoolean(attrVal); } else { log.warning("unexpected attribute delete/@" + attrName); } } int eventType = xpp.nextTag(); currTag = xpp.getName(); String val = xpp.nextText(); if ("id".equals(currTag)) { cmd.id = val; updateHandler.delete(cmd); log.info("delete(id " + val + ") 0 " + (System.currentTimeMillis()-startTime)); } else if ("query".equals(currTag)) { cmd.query = val; updateHandler.deleteByQuery(cmd); log.info("deleteByQuery(query " + val + ") 0 " + (System.currentTimeMillis()-startTime)); } else { log.warning("unexpected XML tag /delete/"+currTag); throw new SolrException(400,"unexpected XML tag /delete/"+currTag); } res.add( "delete", "" ); while (xpp.nextTag() != XmlPullParser.END_TAG); } // end delete return res; } private void readDoc(DocumentBuilder builder, XmlPullParser xpp) throws IOException, XmlPullParserException { // xpp should be at <doc> at this point builder.startDoc(); int attrcount = xpp.getAttributeCount(); float docBoost = 1.0f; for (int i=0; i<attrcount; i++) { String attrName = xpp.getAttributeName(i); String attrVal = xpp.getAttributeValue(i); if ("boost".equals(attrName)) { docBoost = Float.parseFloat(attrVal); builder.setBoost(docBoost); } else { log.warning("Unknown attribute doc/@" + attrName); } } if (docBoost != 1.0f) builder.setBoost(docBoost); // while (findNextTag(xpp,"field") != XmlPullParser.END_DOCUMENT) { while(true) { int eventType = xpp.nextTag(); if (eventType == XmlPullParser.END_TAG) break; // </doc> String tname=xpp.getName(); // System.out.println("FIELD READER AT TAG " + tname); if (!"field".equals(tname)) { log.warning("unexpected XML tag doc/"+tname); throw new SolrException(400,"unexpected XML tag doc/"+tname); } // // get field name and parse field attributes // attrcount = xpp.getAttributeCount(); String name=null; float boost=1.0f; boolean isNull=false; for (int i=0; i<attrcount; i++) { String attrName = xpp.getAttributeName(i); String attrVal = xpp.getAttributeValue(i); if ("name".equals(attrName)) { name=attrVal; } else if ("boost".equals(attrName)) { boost=Float.parseFloat(attrVal); } else if ("null".equals(attrName)) { isNull=StrUtils.parseBoolean(attrVal); } else { log.warning("Unknown attribute doc/field/@" + attrName); } } // now get the field value String val = xpp.nextText(); // todo... text event for <field></field>??? // need this line for isNull??? // Don't add fields marked as null (for now at least) if (!isNull) { if (boost != 1.0f) { builder.addField(name,val,boost); } else { builder.addField(name,val); } } // do I have to do a nextTag here to read the end_tag? } // end field loop } /** * A Convinince method for getting back a simple XML string indicating * successs of failure from an XML formated Update (from the Reader) */ public void doLegacyUpdate(Reader input, Writer output) { try { NamedList ignored = this.update( input ); output.write("<result status=\"0\"></result>"); } catch( Exception ex ) { try { XML.writeXML(output,"result",SolrException.toStr(ex),"status","1"); } catch (Exception ee) { log.severe("Error writing to output stream: "+ee); } } } //////////////////////// SolrInfoMBeans methods ////////////////////// @Override public String getDescription() { return "Add documents with XML"; } @Override public String getVersion() { return "$Revision$"; } @Override public String getSourceId() { return "$Id$"; } @Override public String getSource() { return "$URL$"; } }
Spelling correction git-svn-id: 3b1ff1236863b4d63a22e4dae568675c2e247730@526626 13f79535-47bb-0310-9956-ffa450edef68
src/java/org/apache/solr/handler/XmlUpdateRequestHandler.java
Spelling correction
Java
apache-2.0
98bb60e4baeb4e0c4d5cdd93e2422a4622283412
0
nknize/elasticsearch,robin13/elasticsearch,vroyer/elassandra,scorpionvicky/elasticsearch,coding0011/elasticsearch,uschindler/elasticsearch,strapdata/elassandra,robin13/elasticsearch,HonzaKral/elasticsearch,strapdata/elassandra,nknize/elasticsearch,gfyoung/elasticsearch,scorpionvicky/elasticsearch,gingerwizard/elasticsearch,GlenRSmith/elasticsearch,strapdata/elassandra,vroyer/elassandra,scorpionvicky/elasticsearch,coding0011/elasticsearch,gfyoung/elasticsearch,scorpionvicky/elasticsearch,GlenRSmith/elasticsearch,strapdata/elassandra,GlenRSmith/elasticsearch,robin13/elasticsearch,nknize/elasticsearch,gfyoung/elasticsearch,nknize/elasticsearch,gfyoung/elasticsearch,gingerwizard/elasticsearch,gingerwizard/elasticsearch,strapdata/elassandra,coding0011/elasticsearch,uschindler/elasticsearch,uschindler/elasticsearch,scorpionvicky/elasticsearch,HonzaKral/elasticsearch,HonzaKral/elasticsearch,gfyoung/elasticsearch,coding0011/elasticsearch,robin13/elasticsearch,uschindler/elasticsearch,nknize/elasticsearch,vroyer/elassandra,gingerwizard/elasticsearch,GlenRSmith/elasticsearch,coding0011/elasticsearch,uschindler/elasticsearch,gingerwizard/elasticsearch,GlenRSmith/elasticsearch,HonzaKral/elasticsearch,gingerwizard/elasticsearch,gingerwizard/elasticsearch,robin13/elasticsearch
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ package org.elasticsearch.alerts; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.ElasticsearchIllegalArgumentException; import org.elasticsearch.action.admin.indices.refresh.RefreshRequest; import org.elasticsearch.action.delete.DeleteResponse; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.alerts.actions.AlertAction; import org.elasticsearch.alerts.actions.AlertActionRegistry; import org.elasticsearch.alerts.triggers.TriggerManager; import org.elasticsearch.client.Client; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.common.ParseField; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.collect.Tuple; import org.elasticsearch.common.component.AbstractComponent; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.joda.time.DateTime; import org.elasticsearch.common.lucene.uid.Versions; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.util.concurrent.ConcurrentCollections; import org.elasticsearch.common.xcontent.XContentHelper; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.search.SearchHit; import java.io.IOException; import java.util.List; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicBoolean; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; /** */ public class AlertsStore extends AbstractComponent { public static final String ALERT_INDEX = ".alerts"; public static final String ALERT_TYPE = "alert"; public static final ParseField SCHEDULE_FIELD = new ParseField("schedule"); public static final ParseField TRIGGER_FIELD = new ParseField("trigger"); public static final ParseField ACTION_FIELD = new ParseField("actions"); public static final ParseField LAST_ACTION_FIRE = new ParseField("last_action_fire"); public static final ParseField ENABLE = new ParseField("enable"); public static final ParseField REQUEST_FIELD = new ParseField("request"); public static final ParseField THROTTLE_PERIOD_FIELD = new ParseField("throttle_period"); public static final ParseField LAST_ACTION_EXECUTED_FIELD = new ParseField("last_action_executed"); public static final ParseField ACK_STATE_FIELD = new ParseField("ack_state"); private final Client client; private final TriggerManager triggerManager; private final TemplateHelper templateHelper; private final ConcurrentMap<String, Alert> alertMap; private final AlertActionRegistry alertActionRegistry; private final AtomicBoolean started = new AtomicBoolean(false); private final int scrollSize; private final TimeValue scrollTimeout; @Inject public AlertsStore(Settings settings, Client client, AlertActionRegistry alertActionRegistry, TriggerManager triggerManager, TemplateHelper templateHelper) { super(settings); this.client = client; this.alertActionRegistry = alertActionRegistry; this.templateHelper = templateHelper; this.alertMap = ConcurrentCollections.newConcurrentMap(); // Not using component settings, to let AlertsStore and AlertActionManager share the same settings this.scrollSize = settings.getAsInt("alerts.scroll.size", 100); this.scrollTimeout = settings.getAsTime("alerts.scroll.timeout", TimeValue.timeValueSeconds(30)); this.triggerManager = triggerManager; } /** * Returns the alert with the specified name otherwise <code>null</code> is returned. */ public Alert getAlert(String name) { return alertMap.get(name); } /** * Creates an alert with the specified name and source. If an alert with the specified name already exists it will * get overwritten. */ public Tuple<Alert, IndexResponse> addAlert(String name, BytesReference alertSource) { Alert alert = parseAlert(name, alertSource); IndexResponse response = persistAlert(name, alertSource, IndexRequest.OpType.CREATE); alert.version(response.getVersion()); alertMap.put(name, alert); return new Tuple<>(alert, response); } /** * Updates the specified alert by making sure that the made changes are persisted. */ public IndexResponse updateAlert(Alert alert) throws IOException { IndexResponse response = client.prepareIndex(ALERT_INDEX, ALERT_TYPE, alert.alertName()) .setSource(jsonBuilder().value(alert)) // TODO: the content type should be based on the provided content type when the alert was initially added. .setVersion(alert.version()) .setOpType(IndexRequest.OpType.INDEX) .get(); alert.version(response.getVersion()); // Don'<></> need to update the alertMap, since we are working on an instance from it. assert verifySameInstance(alert); return response; } private boolean verifySameInstance(Alert alert) { Alert found = alertMap.get(alert.alertName()); assert found == alert : "expected " + alert + " but got" + found; return true; } /** * Deletes the alert with the specified name if exists */ public DeleteResponse deleteAlert(String name) { Alert alert = alertMap.remove(name); if (alert == null) { return new DeleteResponse(ALERT_INDEX, ALERT_TYPE, name, Versions.MATCH_ANY, false); } DeleteResponse deleteResponse = client.prepareDelete(ALERT_INDEX, ALERT_TYPE, name) .setVersion(alert.version()) .get(); assert deleteResponse.isFound(); return deleteResponse; } /** * Clears the in-memory representation of the alerts */ public void clear() { alertMap.clear(); } public ConcurrentMap<String, Alert> getAlerts() { return alertMap; } public boolean start(ClusterState state) { if (started.get()) { return true; } IndexMetaData alertIndexMetaData = state.getMetaData().index(ALERT_INDEX); if (alertIndexMetaData != null) { logger.debug("Previous alerting index"); if (state.routingTable().index(ALERT_INDEX).allPrimaryShardsActive()) { logger.debug("Previous alerting index with active primary shards"); try { loadAlerts(); } catch (Exception e) { logger.warn("Failed to load alerts", e); } templateHelper.checkAndUploadIndexTemplate(state, "alerts"); started.set(true); return true; } else { logger.info("Not all primary shards of the .alerts index are started"); return false; } } else { logger.info("No previous .alert index, skip loading of alerts"); templateHelper.checkAndUploadIndexTemplate(state, "alerts"); started.set(true); return true; } } public boolean started() { return started.get(); } public void stop() { if (started.compareAndSet(true, false)) { clear(); logger.info("Stopped alert store"); } } private IndexResponse persistAlert(String alertName, BytesReference alertSource, IndexRequest.OpType opType) { IndexRequest indexRequest = new IndexRequest(ALERT_INDEX, ALERT_TYPE, alertName); indexRequest.listenerThreaded(false); indexRequest.source(alertSource, false); indexRequest.opType(opType); return client.index(indexRequest).actionGet(); } private void loadAlerts() { client.admin().indices().refresh(new RefreshRequest(ALERT_INDEX)).actionGet(); SearchResponse response = client.prepareSearch(ALERT_INDEX) .setTypes(ALERT_TYPE) .setSearchType(SearchType.SCAN) .setScroll(scrollTimeout) .setSize(scrollSize) .setVersion(true) .get(); try { if (response.getHits().getTotalHits() > 0) { response = client.prepareSearchScroll(response.getScrollId()).setScroll(scrollTimeout).get(); while (response.getHits().hits().length != 0) { for (SearchHit sh : response.getHits()) { String alertId = sh.getId(); Alert alert = parseAlert(alertId, sh); alertMap.put(alertId, alert); } response = client.prepareSearchScroll(response.getScrollId()).setScroll(scrollTimeout).get(); } } } finally { client.prepareClearScroll().addScrollId(response.getScrollId()).get(); } logger.info("Loaded [{}] alerts from the alert index.", alertMap.size()); } private Alert parseAlert(String alertId, SearchHit sh) { Alert alert = parseAlert(alertId, sh.getSourceRef()); alert.version(sh.version()); return alert; } protected Alert parseAlert(String alertName, BytesReference source) { Alert alert = new Alert(); alert.alertName(alertName); try (XContentParser parser = XContentHelper.createParser(source)) { String currentFieldName = null; XContentParser.Token token = parser.nextToken(); assert token == XContentParser.Token.START_OBJECT; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (token == XContentParser.Token.START_OBJECT) { if (TRIGGER_FIELD.match(currentFieldName)) { alert.trigger(triggerManager.instantiateAlertTrigger(parser)); } else if (ACTION_FIELD.match(currentFieldName)) { List<AlertAction> actions = alertActionRegistry.instantiateAlertActions(parser); alert.actions(actions); } else if (REQUEST_FIELD.match(currentFieldName)) { alert.setSearchRequest(AlertUtils.readSearchRequest(parser)); } else { throw new ElasticsearchIllegalArgumentException("Unexpected field [" + currentFieldName + "]"); } } else if (token.isValue()) { if (SCHEDULE_FIELD.match(currentFieldName)) { alert.schedule(parser.textOrNull()); } else if (ENABLE.match(currentFieldName)) { alert.enabled(parser.booleanValue()); } else if (LAST_ACTION_FIRE.match(currentFieldName)) { alert.lastActionFire(DateTime.parse(parser.textOrNull())); } else if (LAST_ACTION_EXECUTED_FIELD.match(currentFieldName)) { alert.setTimeLastActionExecuted(DateTime.parse(parser.textOrNull())); } else if (THROTTLE_PERIOD_FIELD.match(currentFieldName)) { alert.setThrottlePeriod(TimeValue.parseTimeValue(parser.textOrNull(), new TimeValue(0))); } else if (ACK_STATE_FIELD.match(currentFieldName)) { alert.setAckState(AlertAckState.fromString(parser.textOrNull())); } else { throw new ElasticsearchIllegalArgumentException("Unexpected field [" + currentFieldName + "]"); } } else { throw new ElasticsearchIllegalArgumentException("Unexpected token [" + token + "]"); } } } catch (IOException e) { throw new ElasticsearchException("Error during parsing alert", e); } if (alert.lastActionFire() == null) { alert.lastActionFire(new DateTime(0)); } if (alert.schedule() == null) { throw new ElasticsearchIllegalArgumentException("Schedule is a required field"); } if (alert.trigger() == null) { throw new ElasticsearchIllegalArgumentException("Trigger is a required field"); } return alert; } }
src/main/java/org/elasticsearch/alerts/AlertsStore.java
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ package org.elasticsearch.alerts; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.ElasticsearchIllegalArgumentException; import org.elasticsearch.action.admin.indices.refresh.RefreshRequest; import org.elasticsearch.action.delete.DeleteResponse; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.alerts.actions.AlertAction; import org.elasticsearch.alerts.actions.AlertActionRegistry; import org.elasticsearch.alerts.triggers.TriggerManager; import org.elasticsearch.client.Client; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.common.ParseField; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.collect.Tuple; import org.elasticsearch.common.component.AbstractComponent; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.joda.time.DateTime; import org.elasticsearch.common.lucene.uid.Versions; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.util.concurrent.ConcurrentCollections; import org.elasticsearch.common.xcontent.XContentHelper; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.search.SearchHit; import java.io.IOException; import java.util.List; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicBoolean; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; /** */ public class AlertsStore extends AbstractComponent { public static final String ALERT_INDEX = ".alerts"; public static final String ALERT_TYPE = "alert"; public static final ParseField SCHEDULE_FIELD = new ParseField("schedule"); public static final ParseField TRIGGER_FIELD = new ParseField("trigger"); public static final ParseField ACTION_FIELD = new ParseField("actions"); public static final ParseField LAST_ACTION_FIRE = new ParseField("last_action_fire"); public static final ParseField ENABLE = new ParseField("enable"); public static final ParseField REQUEST_FIELD = new ParseField("request"); public static final ParseField THROTTLE_PERIOD_FIELD = new ParseField("throttle_period"); public static final ParseField LAST_ACTION_EXECUTED_FIELD = new ParseField("last_action_executed"); public static final ParseField ACK_STATE_FIELD = new ParseField("ack_state"); private final Client client; private final TriggerManager triggerManager; private final TemplateHelper templateHelper; private final ConcurrentMap<String, Alert> alertMap; private final AlertActionRegistry alertActionRegistry; private final AtomicBoolean started = new AtomicBoolean(false); private final int scrollSize; private final TimeValue scrollTimeout; @Inject public AlertsStore(Settings settings, Client client, AlertActionRegistry alertActionRegistry, TriggerManager triggerManager, TemplateHelper templateHelper) { super(settings); this.client = client; this.alertActionRegistry = alertActionRegistry; this.templateHelper = templateHelper; this.alertMap = ConcurrentCollections.newConcurrentMap(); // Not using component settings, to let AlertsStore and AlertActionManager share the same settings this.scrollSize = settings.getAsInt("alerts.scroll.size", 100); this.scrollTimeout = settings.getAsTime("alerts.scroll.timeout", TimeValue.timeValueSeconds(30)); this.triggerManager = triggerManager; } /** * Returns the alert with the specified name otherwise <code>null</code> is returned. */ public Alert getAlert(String name) { return alertMap.get(name); } /** * Creates an alert with the specified name and source. If an alert with the specified name already exists it will * get overwritten. */ public Tuple<Alert, IndexResponse> addAlert(String name, BytesReference alertSource) { Alert alert = parseAlert(name, alertSource); IndexResponse response = persistAlert(name, alertSource, IndexRequest.OpType.CREATE); alert.version(response.getVersion()); alertMap.put(name, alert); return new Tuple<>(alert, response); } /** * Updates the specified alert by making sure that the made changes are persisted. */ public IndexResponse updateAlert(Alert alert) throws IOException { IndexResponse response = client.prepareIndex(ALERT_INDEX, ALERT_TYPE, alert.alertName()) .setSource(jsonBuilder().value(alert)) // TODO: the content type should be based on the provided content type when the alert was initially added. .setVersion(alert.version()) .setOpType(IndexRequest.OpType.INDEX) .get(); alert.version(response.getVersion()); // Don'<></> need to update the alertMap, since we are working on an instance from it. assert alertMap.get(alert.alertName()) == alert; return response; } /** * Deletes the alert with the specified name if exists */ public DeleteResponse deleteAlert(String name) { Alert alert = alertMap.remove(name); if (alert == null) { return new DeleteResponse(ALERT_INDEX, ALERT_TYPE, name, Versions.MATCH_ANY, false); } DeleteResponse deleteResponse = client.prepareDelete(ALERT_INDEX, ALERT_TYPE, name) .setVersion(alert.version()) .get(); assert deleteResponse.isFound(); return deleteResponse; } /** * Clears the in-memory representation of the alerts */ public void clear() { alertMap.clear(); } public ConcurrentMap<String, Alert> getAlerts() { return alertMap; } public boolean start(ClusterState state) { if (started.get()) { return true; } IndexMetaData alertIndexMetaData = state.getMetaData().index(ALERT_INDEX); if (alertIndexMetaData != null) { logger.debug("Previous alerting index"); if (state.routingTable().index(ALERT_INDEX).allPrimaryShardsActive()) { logger.debug("Previous alerting index with active primary shards"); try { loadAlerts(); } catch (Exception e) { logger.warn("Failed to load alerts", e); } templateHelper.checkAndUploadIndexTemplate(state, "alerts"); started.set(true); return true; } else { logger.info("Not all primary shards of the .alerts index are started"); return false; } } else { logger.info("No previous .alert index, skip loading of alerts"); templateHelper.checkAndUploadIndexTemplate(state, "alerts"); started.set(true); return true; } } public boolean started() { return started.get(); } public void stop() { if (started.compareAndSet(true, false)) { clear(); logger.info("Stopped alert store"); } } private IndexResponse persistAlert(String alertName, BytesReference alertSource, IndexRequest.OpType opType) { IndexRequest indexRequest = new IndexRequest(ALERT_INDEX, ALERT_TYPE, alertName); indexRequest.listenerThreaded(false); indexRequest.source(alertSource, false); indexRequest.opType(opType); return client.index(indexRequest).actionGet(); } private void loadAlerts() { client.admin().indices().refresh(new RefreshRequest(ALERT_INDEX)).actionGet(); SearchResponse response = client.prepareSearch(ALERT_INDEX) .setTypes(ALERT_TYPE) .setSearchType(SearchType.SCAN) .setScroll(scrollTimeout) .setSize(scrollSize) .setVersion(true) .get(); try { if (response.getHits().getTotalHits() > 0) { response = client.prepareSearchScroll(response.getScrollId()).setScroll(scrollTimeout).get(); while (response.getHits().hits().length != 0) { for (SearchHit sh : response.getHits()) { String alertId = sh.getId(); Alert alert = parseAlert(alertId, sh); alertMap.put(alertId, alert); } response = client.prepareSearchScroll(response.getScrollId()).setScroll(scrollTimeout).get(); } } } finally { client.prepareClearScroll().addScrollId(response.getScrollId()).get(); } logger.info("Loaded [{}] alerts from the alert index.", alertMap.size()); } private Alert parseAlert(String alertId, SearchHit sh) { Alert alert = parseAlert(alertId, sh.getSourceRef()); alert.version(sh.version()); return alert; } protected Alert parseAlert(String alertName, BytesReference source) { Alert alert = new Alert(); alert.alertName(alertName); try (XContentParser parser = XContentHelper.createParser(source)) { String currentFieldName = null; XContentParser.Token token = parser.nextToken(); assert token == XContentParser.Token.START_OBJECT; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (token == XContentParser.Token.START_OBJECT) { if (TRIGGER_FIELD.match(currentFieldName)) { alert.trigger(triggerManager.instantiateAlertTrigger(parser)); } else if (ACTION_FIELD.match(currentFieldName)) { List<AlertAction> actions = alertActionRegistry.instantiateAlertActions(parser); alert.actions(actions); } else if (REQUEST_FIELD.match(currentFieldName)) { alert.setSearchRequest(AlertUtils.readSearchRequest(parser)); } else { throw new ElasticsearchIllegalArgumentException("Unexpected field [" + currentFieldName + "]"); } } else if (token.isValue()) { if (SCHEDULE_FIELD.match(currentFieldName)) { alert.schedule(parser.textOrNull()); } else if (ENABLE.match(currentFieldName)) { alert.enabled(parser.booleanValue()); } else if (LAST_ACTION_FIRE.match(currentFieldName)) { alert.lastActionFire(DateTime.parse(parser.textOrNull())); } else if (LAST_ACTION_EXECUTED_FIELD.match(currentFieldName)) { alert.setTimeLastActionExecuted(DateTime.parse(parser.textOrNull())); } else if (THROTTLE_PERIOD_FIELD.match(currentFieldName)) { alert.setThrottlePeriod(TimeValue.parseTimeValue(parser.textOrNull(), new TimeValue(0))); } else if (ACK_STATE_FIELD.match(currentFieldName)) { alert.setAckState(AlertAckState.fromString(parser.textOrNull())); } else { throw new ElasticsearchIllegalArgumentException("Unexpected field [" + currentFieldName + "]"); } } else { throw new ElasticsearchIllegalArgumentException("Unexpected token [" + token + "]"); } } } catch (IOException e) { throw new ElasticsearchException("Error during parsing alert", e); } if (alert.lastActionFire() == null) { alert.lastActionFire(new DateTime(0)); } if (alert.schedule() == null) { throw new ElasticsearchIllegalArgumentException("Schedule is a required field"); } if (alert.trigger() == null) { throw new ElasticsearchIllegalArgumentException("Trigger is a required field"); } return alert; } }
improve assert Original commit: elastic/x-pack-elasticsearch@cfedeb5da8030c4c4f2c418bc5f6a1a35a73ccde
src/main/java/org/elasticsearch/alerts/AlertsStore.java
improve assert
Java
apache-2.0
2ea439bb876b20ee35e97212feb9525a982f3021
0
obsidian-toaster/generator-backend,obsidian-toaster/generator-backend
/** * Copyright 2005-2015 Red Hat, Inc. * <p> * Red Hat 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.obsidian.generator.rest; import static javax.json.Json.createObjectBuilder; import java.nio.file.Paths; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.inject.Inject; import javax.json.JsonObject; import javax.json.JsonObjectBuilder; import javax.json.JsonString; import javax.validation.constraints.Pattern; import javax.ws.rs.Consumes; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Form; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.jboss.forge.addon.resource.Resource; import org.jboss.forge.addon.resource.ResourceFactory; import org.jboss.forge.addon.ui.command.CommandFactory; import org.jboss.forge.addon.ui.command.UICommand; import org.jboss.forge.addon.ui.context.UIContext; import org.jboss.forge.addon.ui.context.UISelection; import org.jboss.forge.addon.ui.controller.CommandController; import org.jboss.forge.addon.ui.controller.CommandControllerFactory; import org.jboss.forge.addon.ui.controller.WizardCommandController; import org.jboss.forge.addon.ui.result.Failed; import org.jboss.forge.addon.ui.result.Result; import org.jboss.forge.furnace.versions.Versions; import org.jboss.forge.service.ui.RestUIContext; import org.jboss.forge.service.ui.RestUIRuntime; import org.jboss.forge.service.util.UICommandHelper; import io.obsidian.generator.ForgeInitializer; import io.obsidian.generator.util.JsonBuilder; @Path("/forge") public class ObsidianResource { private static final String ALLOWED_CMDS_VALIDATION_MESSAGE = "Supported commmands are 'obsidian-new-quickstart' or 'obsidian-new-project'"; private static final String ALLOWED_CMDS_PATTERN = "(obsidian-new-quickstart)|(obsidian-new-project)"; private static final String DEFAULT_COMMAND_NAME = "obsidian-new-quickstart"; private Map<String, String> commandMap = new HashMap<>(); public ObsidianResource() { commandMap.put("obsidian-new-quickstart", "Obsidian: New Quickstart"); commandMap.put("obsidian-new-project", "Obsidian: New Project"); } @Inject private CommandFactory commandFactory; @Inject private CommandControllerFactory controllerFactory; @Inject private ResourceFactory resourceFactory; @Inject private UICommandHelper helper; @GET @Path("/version") @Produces(MediaType.APPLICATION_JSON) public JsonObject getInfo() { return createObjectBuilder() .add("version", Versions.getImplementationVersionFor(UIContext.class).toString()) .build(); } @GET @Path("/commands/{commandName}") @Produces(MediaType.APPLICATION_JSON) public JsonObject getCommandInfo( @PathParam("commandName") @Pattern(regexp = ALLOWED_CMDS_PATTERN, message = ALLOWED_CMDS_VALIDATION_MESSAGE) @DefaultValue(DEFAULT_COMMAND_NAME) String commandName) throws Exception { JsonObjectBuilder builder = createObjectBuilder(); try (CommandController controller = getCommand(commandName)) { helper.describeController(builder, controller); } return builder.build(); } @POST @Path("/commands/{commandName}/validate") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public JsonObject validateCommand(JsonObject content, @PathParam("commandName") @Pattern(regexp = ALLOWED_CMDS_PATTERN, message = ALLOWED_CMDS_VALIDATION_MESSAGE) @DefaultValue(DEFAULT_COMMAND_NAME) String commandName) throws Exception { JsonObjectBuilder builder = createObjectBuilder(); try (CommandController controller = getCommand(commandName)) { helper.populateControllerAllInputs(content, controller); helper.describeCurrentState(builder, controller); helper.describeValidation(builder, controller); helper.describeInputs(builder, controller); } return builder.build(); } @POST @Path("/commands/{commandName}/next") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public JsonObject nextStep(JsonObject content, @PathParam("commandName") @Pattern(regexp = ALLOWED_CMDS_PATTERN, message = ALLOWED_CMDS_VALIDATION_MESSAGE) @DefaultValue(DEFAULT_COMMAND_NAME) String commandName) throws Exception { int stepIndex = content.getInt("stepIndex", 1); JsonObjectBuilder builder = createObjectBuilder(); try (CommandController controller = getCommand(commandName)) { if (!(controller instanceof WizardCommandController)) { throw new WebApplicationException("Controller is not a wizard", Status.BAD_REQUEST); } WizardCommandController wizardController = (WizardCommandController) controller; for (int i = 0; i < stepIndex; i++) { if (wizardController.canMoveToNextStep()) { helper.populateController(content, wizardController); helper.describeValidation(builder, controller); wizardController.next().initialize(); } } helper.describeMetadata(builder, controller); helper.describeCurrentState(builder, controller); helper.describeInputs(builder, controller); } return builder.build(); } @POST @Path("/commands/{commandName}/execute") @Consumes(MediaType.APPLICATION_JSON) public Response executeCommand(JsonObject content, @PathParam("commandName") @Pattern(regexp = ALLOWED_CMDS_PATTERN, message = ALLOWED_CMDS_VALIDATION_MESSAGE) @DefaultValue(DEFAULT_COMMAND_NAME) String commandName) throws Exception { try (CommandController controller = getCommand(commandName)) { helper.populateControllerAllInputs(content, controller); if (controller.isValid()) { Result result = controller.execute(); if (result instanceof Failed) { return Response.status(Status.INTERNAL_SERVER_ERROR).entity(result.getMessage()).build(); } else { UISelection<?> selection = controller.getContext().getSelection(); java.nio.file.Path path = Paths.get(selection.get().toString()); String artifactId = findArtifactId(content); byte[] zipContents = io.obsidian.generator.util.Paths.zip(artifactId, path); io.obsidian.generator.util.Paths.deleteDirectory(path); return Response .ok(zipContents) .type("application/zip") .header("Content-Disposition", "attachment; filename=\"" + artifactId + ".zip\"") .build(); } } else { JsonObjectBuilder builder = createObjectBuilder(); helper.describeValidation(builder, controller); return Response.status(Status.PRECONDITION_FAILED).entity(builder.build()).build(); } } } /** * @param content the {@link JsonObject} content from the request * @return the value for the input "named" */ private String findArtifactId(JsonObject content) { return content.getJsonArray("inputs").stream() .filter(input -> "named".equals(((JsonObject) input).getString("name"))) .map(input -> ((JsonString) ((JsonObject) input).get("value")).getString()) .findFirst().orElse("demo"); } @POST @Path("/commands/{commandName}/execute") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) public Response executeCommand(Form form, @PathParam("commandName") @Pattern(regexp = ALLOWED_CMDS_PATTERN, message = ALLOWED_CMDS_VALIDATION_MESSAGE) @DefaultValue(DEFAULT_COMMAND_NAME) String commandName) throws Exception { String stepIndex = form.asMap().remove("stepIndex").get(0); final JsonBuilder jsonBuilder = new JsonBuilder().createJson(Integer.valueOf(stepIndex)); for (Map.Entry<String, List<String>> entry : form.asMap().entrySet()) { jsonBuilder.addInput(entry.getKey(), entry.getValue()); } final Response response = executeCommand(jsonBuilder.build(), commandName); if (response.getEntity() instanceof JsonObject) { JsonObject responseEntity = (JsonObject) response.getEntity(); String error = ((JsonObject) responseEntity.getJsonArray("messages").get(0)).getString("description"); return Response.status(Status.PRECONDITION_FAILED).entity(error).build(); } return response; } private CommandController getCommand(String name) throws Exception { RestUIContext context = createUIContext(); UICommand command = commandFactory.getCommandByName(context, commandMap.get(name)); CommandController controller = controllerFactory.createController(context, new RestUIRuntime(Collections.emptyList()), command); controller.initialize(); return controller; } private RestUIContext createUIContext() { java.nio.file.Path rootPath = ForgeInitializer.getRoot(); Resource<?> selection = resourceFactory.create(rootPath.toFile()); return new RestUIContext(selection, Collections.emptyList()); } }
src/main/java/io/obsidian/generator/rest/ObsidianResource.java
/** * Copyright 2005-2015 Red Hat, Inc. * <p> * Red Hat 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.obsidian.generator.rest; import static javax.json.Json.createObjectBuilder; import java.nio.file.Paths; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.json.JsonObject; import javax.json.JsonObjectBuilder; import javax.json.JsonString; import javax.validation.constraints.Pattern; import javax.ws.rs.Consumes; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Form; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.jboss.forge.addon.resource.Resource; import org.jboss.forge.addon.resource.ResourceFactory; import org.jboss.forge.addon.ui.command.CommandFactory; import org.jboss.forge.addon.ui.command.UICommand; import org.jboss.forge.addon.ui.context.UIContext; import org.jboss.forge.addon.ui.context.UISelection; import org.jboss.forge.addon.ui.controller.CommandController; import org.jboss.forge.addon.ui.controller.CommandControllerFactory; import org.jboss.forge.addon.ui.controller.WizardCommandController; import org.jboss.forge.addon.ui.result.Failed; import org.jboss.forge.addon.ui.result.Result; import org.jboss.forge.furnace.versions.Versions; import org.jboss.forge.service.ui.RestUIContext; import org.jboss.forge.service.ui.RestUIRuntime; import org.jboss.forge.service.util.UICommandHelper; import io.obsidian.generator.ForgeInitializer; import io.obsidian.generator.util.JsonBuilder; @Path("/forge") @ApplicationScoped public class ObsidianResource { private static final String ALLOWED_CMDS_VALIDATION_MESSAGE = "Supported commmands are 'obsidian-new-quickstart' or 'obsidian-new-project'"; private static final String ALLOWED_CMDS_PATTERN = "(obsidian-new-quickstart)|(obsidian-new-project)"; private static final String DEFAULT_COMMAND_NAME = "obsidian-new-quickstart"; private Map<String, String> commandMap = new HashMap<>(); public ObsidianResource() { commandMap.put("obsidian-new-quickstart", "Obsidian: New Quickstart"); commandMap.put("obsidian-new-project", "Obsidian: New Project"); } @Inject private CommandFactory commandFactory; @Inject private CommandControllerFactory controllerFactory; @Inject private ResourceFactory resourceFactory; @Inject private UICommandHelper helper; @GET @Path("/version") @Produces(MediaType.APPLICATION_JSON) public JsonObject getInfo() { return createObjectBuilder() .add("version", Versions.getImplementationVersionFor(UIContext.class).toString()) .build(); } @GET @Path("/commands/{commandName}") @Produces(MediaType.APPLICATION_JSON) public JsonObject getCommandInfo( @PathParam("commandName") @Pattern(regexp = ALLOWED_CMDS_PATTERN, message = ALLOWED_CMDS_VALIDATION_MESSAGE) @DefaultValue(DEFAULT_COMMAND_NAME) String commandName) throws Exception { JsonObjectBuilder builder = createObjectBuilder(); try (CommandController controller = getCommand(commandName)) { helper.describeController(builder, controller); } return builder.build(); } @POST @Path("/commands/{commandName}/validate") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public JsonObject validateCommand(JsonObject content, @PathParam("commandName") @Pattern(regexp = ALLOWED_CMDS_PATTERN, message = ALLOWED_CMDS_VALIDATION_MESSAGE) @DefaultValue(DEFAULT_COMMAND_NAME) String commandName) throws Exception { JsonObjectBuilder builder = createObjectBuilder(); try (CommandController controller = getCommand(commandName)) { helper.populateControllerAllInputs(content, controller); helper.describeCurrentState(builder, controller); helper.describeValidation(builder, controller); helper.describeInputs(builder, controller); } return builder.build(); } @POST @Path("/commands/{commandName}/next") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public JsonObject nextStep(JsonObject content, @PathParam("commandName") @Pattern(regexp = ALLOWED_CMDS_PATTERN, message = ALLOWED_CMDS_VALIDATION_MESSAGE) @DefaultValue(DEFAULT_COMMAND_NAME) String commandName) throws Exception { int stepIndex = content.getInt("stepIndex", 1); JsonObjectBuilder builder = createObjectBuilder(); try (CommandController controller = getCommand(commandName)) { if (!(controller instanceof WizardCommandController)) { throw new WebApplicationException("Controller is not a wizard", Status.BAD_REQUEST); } WizardCommandController wizardController = (WizardCommandController) controller; for (int i = 0; i < stepIndex; i++) { if (wizardController.canMoveToNextStep()) { helper.populateController(content, wizardController); helper.describeValidation(builder, controller); wizardController.next().initialize(); } } helper.describeMetadata(builder, controller); helper.describeCurrentState(builder, controller); helper.describeInputs(builder, controller); } return builder.build(); } @POST @Path("/commands/{commandName}/execute") @Consumes(MediaType.APPLICATION_JSON) public Response executeCommand(JsonObject content, @PathParam("commandName") @Pattern(regexp = ALLOWED_CMDS_PATTERN, message = ALLOWED_CMDS_VALIDATION_MESSAGE) @DefaultValue(DEFAULT_COMMAND_NAME) String commandName) throws Exception { try (CommandController controller = getCommand(commandName)) { helper.populateControllerAllInputs(content, controller); if (controller.isValid()) { Result result = controller.execute(); if (result instanceof Failed) { return Response.status(Status.INTERNAL_SERVER_ERROR).entity(result.getMessage()).build(); } else { UISelection<?> selection = controller.getContext().getSelection(); java.nio.file.Path path = Paths.get(selection.get().toString()); String artifactId = findArtifactId(content); byte[] zipContents = io.obsidian.generator.util.Paths.zip(artifactId, path); io.obsidian.generator.util.Paths.deleteDirectory(path); return Response .ok(zipContents) .type("application/zip") .header("Content-Disposition", "attachment; filename=\"" + artifactId + ".zip\"") .build(); } } else { JsonObjectBuilder builder = createObjectBuilder(); helper.describeValidation(builder, controller); return Response.status(Status.PRECONDITION_FAILED).entity(builder.build()).build(); } } } /** * @param content the {@link JsonObject} content from the request * @return the value for the input "named" */ private String findArtifactId(JsonObject content) { return content.getJsonArray("inputs").stream() .filter(input -> "named".equals(((JsonObject) input).getString("name"))) .map(input -> ((JsonString) ((JsonObject) input).get("value")).getString()) .findFirst().orElse("demo"); } @POST @Path("/commands/{commandName}/execute") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) public Response executeCommand(Form form, @PathParam("commandName") @Pattern(regexp = ALLOWED_CMDS_PATTERN, message = ALLOWED_CMDS_VALIDATION_MESSAGE) @DefaultValue(DEFAULT_COMMAND_NAME) String commandName) throws Exception { String stepIndex = form.asMap().remove("stepIndex").get(0); final JsonBuilder jsonBuilder = new JsonBuilder().createJson(Integer.valueOf(stepIndex)); for (Map.Entry<String, List<String>> entry : form.asMap().entrySet()) { jsonBuilder.addInput(entry.getKey(), entry.getValue()); } final Response response = executeCommand(jsonBuilder.build(), commandName); if (response.getEntity() instanceof JsonObject) { JsonObject responseEntity = (JsonObject) response.getEntity(); String error = ((JsonObject) responseEntity.getJsonArray("messages").get(0)).getString("description"); return Response.status(Status.PRECONDITION_FAILED).entity(error).build(); } return response; } private CommandController getCommand(String name) throws Exception { RestUIContext context = createUIContext(); UICommand command = commandFactory.getCommandByName(context, commandMap.get(name)); CommandController controller = controllerFactory.createController(context, new RestUIRuntime(Collections.emptyList()), command); controller.initialize(); return controller; } private RestUIContext createUIContext() { java.nio.file.Path rootPath = ForgeInitializer.getRoot(); Resource<?> selection = resourceFactory.create(rootPath.toFile()); return new RestUIContext(selection, Collections.emptyList()); } }
Removed @ApplicationScoped from JAX-RS resource
src/main/java/io/obsidian/generator/rest/ObsidianResource.java
Removed @ApplicationScoped from JAX-RS resource
Java
apache-2.0
6563e5283dd4ea16d8201ee2e22b6dd6d24c6deb
0
MatejTymes/JavaFixes
package mtymes.javafixes.beta.decimal; import org.junit.Test; import java.math.BigInteger; import static java.math.BigInteger.ONE; import static java.math.BigInteger.ZERO; import static mtymes.javafixes.test.Conditions.negative; import static mtymes.javafixes.test.Conditions.positive; import static mtymes.javafixes.test.Random.randomInt; import static mtymes.javafixes.test.Random.randomLong; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class PowerMathTest { @Test public void shouldFindMaxPowerOf10ForLong() { assertThat(PowerMath.maxLongPowerOf10(), equalTo(18)); } @Test public void shouldFindPowerOf10ForLongs() { assertThat(PowerMath.powerOf10Long(0), equalTo(1L)); long expectedValue = 1L; for (int i = 1; i <= 18; i++) { expectedValue *= 10L; assertThat(PowerMath.powerOf10Long(i), equalTo(expectedValue)); } } @Test public void shouldFindPowerOf10ForBigIntegers() { assertThat(PowerMath.powerOf10Big(0), equalTo(BigInteger.ONE)); BigInteger expectedValue = BigInteger.ONE; for (int i = 1; i <= 500; i++) { expectedValue = expectedValue.multiply(BigInteger.TEN); assertThat(PowerMath.powerOf10Big(i), equalTo(expectedValue)); } } @Test public void shouldFindIfLongValueCanBeUpscaledByPowerOf10() { assertThat(PowerMath.canUpscaleLongByPowerOf10(Long.MAX_VALUE, 0), is(true)); assertThat(PowerMath.canUpscaleLongByPowerOf10(Long.MIN_VALUE, 0), is(true)); assertThat(PowerMath.canUpscaleLongByPowerOf10(randomLong(Long.MIN_VALUE, Long.MAX_VALUE), 0), is(true)); for (int n = 1; n <= 18; n++) { long nPow10 = PowerMath.powerOf10Long(n); assertThat(PowerMath.canUpscaleLongByPowerOf10(Long.MAX_VALUE / nPow10, n), is(true)); assertThat(PowerMath.canUpscaleLongByPowerOf10(Long.MIN_VALUE / nPow10, n), is(true)); assertThat(PowerMath.canUpscaleLongByPowerOf10(randomLong(Long.MIN_VALUE / nPow10, Long.MAX_VALUE / nPow10), n), is(true)); assertThat(PowerMath.canUpscaleLongByPowerOf10(Long.MAX_VALUE / nPow10 + 1, n), is(false)); assertThat(PowerMath.canUpscaleLongByPowerOf10(Long.MIN_VALUE / nPow10 - 1, n), is(false)); assertThat(PowerMath.canUpscaleLongByPowerOf10(randomLong(Long.MIN_VALUE, Long.MIN_VALUE / nPow10 - 1), n), is(false)); assertThat(PowerMath.canUpscaleLongByPowerOf10(randomLong(Long.MAX_VALUE / nPow10 + 1, Long.MAX_VALUE), n), is(false)); } for (int n = 0; n <= 100; n++) { assertThat(PowerMath.canUpscaleLongByPowerOf10(0L, n), is(true)); } assertThat(PowerMath.canUpscaleLongByPowerOf10(randomLong(positive()), 19), is(false)); assertThat(PowerMath.canUpscaleLongByPowerOf10(randomLong(negative()), 19), is(false)); assertThat(PowerMath.canUpscaleLongByPowerOf10(randomLong(positive()), randomInt(20, Integer.MAX_VALUE)), is(false)); assertThat(PowerMath.canUpscaleLongByPowerOf10(randomLong(negative()), randomInt(20, Integer.MAX_VALUE)), is(false)); } @Test public void shouldFindNumberOfLongDigits() { assertThat("wrong number of digits for " + 0L, PowerMath.numberOfDigits(0L), equalTo(1)); assertThat("wrong number of digits for " + 1L, PowerMath.numberOfDigits(1L), equalTo(1)); assertThat("wrong number of digits for " + -1L, PowerMath.numberOfDigits(-1L), equalTo(1)); for (int n = 1; n < PowerMath.maxLongPowerOf10(); n++) { long powerOf10 = PowerMath.powerOf10Long(n); assertThat("wrong number of digits for " + powerOf10, PowerMath.numberOfDigits(powerOf10), equalTo(n + 1)); assertThat("wrong number of digits for " + -powerOf10, PowerMath.numberOfDigits(-powerOf10), equalTo(n + 1)); assertThat("wrong number of digits for " + (powerOf10 - 1), PowerMath.numberOfDigits(powerOf10 - 1), equalTo(n)); assertThat("wrong number of digits for " + (-powerOf10 + 1), PowerMath.numberOfDigits(-powerOf10 + 1), equalTo(n)); assertThat("wrong number of digits for " + (powerOf10 + 1), PowerMath.numberOfDigits(powerOf10 + 1), equalTo(n + 1)); assertThat("wrong number of digits for " + (-powerOf10 - 1), PowerMath.numberOfDigits(-powerOf10 - 1), equalTo(n + 1)); } } @Test public void shouldFindNumberOfBigIntegerDigits() { assertThat("wrong number of digits for " + ZERO, PowerMath.numberOfDigits(ZERO), equalTo(1)); assertThat("wrong number of digits for " + ONE, PowerMath.numberOfDigits(ONE), equalTo(1)); assertThat("wrong number of digits for " + ONE.negate(), PowerMath.numberOfDigits(ONE.negate()), equalTo(1)); BigInteger powerOf10 = PowerMath.powerOf10Big(0); // tested for (n) up to 125_000 digits for (int n = 1; n < 1_000; n++) { powerOf10 = powerOf10.multiply(BigInteger.TEN); assertThat("wrong number of digits for " + powerOf10, PowerMath.numberOfDigits(powerOf10), equalTo(n + 1)); BigInteger negativePowerOf10 = powerOf10.negate(); assertThat("wrong number of digits for " + negativePowerOf10, PowerMath.numberOfDigits(negativePowerOf10), equalTo(n + 1)); assertThat("wrong number of digits for " + powerOf10.subtract(ONE), PowerMath.numberOfDigits(powerOf10.subtract(ONE)), equalTo(n)); assertThat("wrong number of digits for " + negativePowerOf10.add(ONE), PowerMath.numberOfDigits(negativePowerOf10.add(ONE)), equalTo(n)); assertThat("wrong number of digits for " + powerOf10.add(ONE), PowerMath.numberOfDigits(powerOf10.add(ONE)), equalTo(n + 1)); assertThat("wrong number of digits for " + negativePowerOf10.subtract(ONE), PowerMath.numberOfDigits(negativePowerOf10.subtract(ONE)), equalTo(n + 1)); } } }
src/test/java/mtymes/javafixes/beta/decimal/PowerMathTest.java
package mtymes.javafixes.beta.decimal; import org.junit.Test; import java.math.BigInteger; import static java.math.BigInteger.ONE; import static mtymes.javafixes.test.Conditions.negative; import static mtymes.javafixes.test.Conditions.positive; import static mtymes.javafixes.test.Random.randomInt; import static mtymes.javafixes.test.Random.randomLong; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class PowerMathTest { @Test public void shouldFindMaxPowerOf10ForLong() { assertThat(PowerMath.maxLongPowerOf10(), equalTo(18)); } @Test public void shouldFindPowerOf10ForLongs() { assertThat(PowerMath.powerOf10Long(0), equalTo(1L)); long expectedValue = 1L; for (int i = 1; i <= 18; i++) { expectedValue *= 10L; assertThat(PowerMath.powerOf10Long(i), equalTo(expectedValue)); } } @Test public void shouldFindPowerOf10ForBigIntegers() { assertThat(PowerMath.powerOf10Big(0), equalTo(BigInteger.ONE)); BigInteger expectedValue = BigInteger.ONE; for (int i = 1; i <= 500; i++) { expectedValue = expectedValue.multiply(BigInteger.TEN); assertThat(PowerMath.powerOf10Big(i), equalTo(expectedValue)); } } @Test public void shouldFindIfLongValueCanBeUpscaledByPowerOf10() { assertThat(PowerMath.canUpscaleLongByPowerOf10(Long.MAX_VALUE, 0), is(true)); assertThat(PowerMath.canUpscaleLongByPowerOf10(Long.MIN_VALUE, 0), is(true)); assertThat(PowerMath.canUpscaleLongByPowerOf10(randomLong(Long.MIN_VALUE, Long.MAX_VALUE), 0), is(true)); for (int n = 1; n <= 18; n++) { long nPow10 = PowerMath.powerOf10Long(n); assertThat(PowerMath.canUpscaleLongByPowerOf10(Long.MAX_VALUE / nPow10, n), is(true)); assertThat(PowerMath.canUpscaleLongByPowerOf10(Long.MIN_VALUE / nPow10, n), is(true)); assertThat(PowerMath.canUpscaleLongByPowerOf10(randomLong(Long.MIN_VALUE / nPow10, Long.MAX_VALUE / nPow10), n), is(true)); assertThat(PowerMath.canUpscaleLongByPowerOf10(Long.MAX_VALUE / nPow10 + 1, n), is(false)); assertThat(PowerMath.canUpscaleLongByPowerOf10(Long.MIN_VALUE / nPow10 - 1, n), is(false)); assertThat(PowerMath.canUpscaleLongByPowerOf10(randomLong(Long.MIN_VALUE, Long.MIN_VALUE / nPow10 - 1), n), is(false)); assertThat(PowerMath.canUpscaleLongByPowerOf10(randomLong(Long.MAX_VALUE / nPow10 + 1, Long.MAX_VALUE), n), is(false)); } for (int n = 0; n <= 100; n++) { assertThat(PowerMath.canUpscaleLongByPowerOf10(0L, n), is(true)); } assertThat(PowerMath.canUpscaleLongByPowerOf10(randomLong(positive()), 19), is(false)); assertThat(PowerMath.canUpscaleLongByPowerOf10(randomLong(negative()), 19), is(false)); assertThat(PowerMath.canUpscaleLongByPowerOf10(randomLong(positive()), randomInt(20, Integer.MAX_VALUE)), is(false)); assertThat(PowerMath.canUpscaleLongByPowerOf10(randomLong(negative()), randomInt(20, Integer.MAX_VALUE)), is(false)); } @Test public void shouldFindNumberOfLongDigits() { assertThat(PowerMath.numberOfDigits(0L), equalTo(1)); assertThat(PowerMath.numberOfDigits(1L), equalTo(1)); assertThat(PowerMath.numberOfDigits(-1L), equalTo(1)); for (int n = 1; n < PowerMath.maxLongPowerOf10(); n++) { long powerOf10 = PowerMath.powerOf10Long(n); assertThat("wrong number of digits for " + powerOf10, PowerMath.numberOfDigits(powerOf10), equalTo(n + 1)); assertThat("wrong number of digits for " + -powerOf10, PowerMath.numberOfDigits(-powerOf10), equalTo(n + 1)); assertThat("wrong number of digits for " + (powerOf10 - 1), PowerMath.numberOfDigits(powerOf10 - 1), equalTo(n)); assertThat("wrong number of digits for " + (-powerOf10 + 1), PowerMath.numberOfDigits(-powerOf10 + 1), equalTo(n)); assertThat("wrong number of digits for " + (powerOf10 + 1), PowerMath.numberOfDigits(powerOf10 + 1), equalTo(n + 1)); assertThat("wrong number of digits for " + (-powerOf10 - 1), PowerMath.numberOfDigits(-powerOf10 - 1), equalTo(n + 1)); } } @Test public void shouldFindNumberOfBigIntegerDigits() { assertThat(PowerMath.numberOfDigits(BigInteger.ZERO), equalTo(1)); assertThat(PowerMath.numberOfDigits(ONE), equalTo(1)); assertThat(PowerMath.numberOfDigits(ONE.negate()), equalTo(1)); BigInteger powerOf10 = PowerMath.powerOf10Big(0); // tested for (n) up to 125_000 digits for (int n = 1; n < 1_000; n++) { powerOf10 = powerOf10.multiply(BigInteger.TEN); assertThat("wrong number of digits for " + powerOf10, PowerMath.numberOfDigits(powerOf10), equalTo(n + 1)); BigInteger negativePowerOf10 = powerOf10.negate(); assertThat("wrong number of digits for " + negativePowerOf10, PowerMath.numberOfDigits(negativePowerOf10), equalTo(n + 1)); assertThat("wrong number of digits for " + powerOf10.subtract(ONE), PowerMath.numberOfDigits(powerOf10.subtract(ONE)), equalTo(n)); assertThat("wrong number of digits for " + negativePowerOf10.add(ONE), PowerMath.numberOfDigits(negativePowerOf10.add(ONE)), equalTo(n)); assertThat("wrong number of digits for " + powerOf10.add(ONE), PowerMath.numberOfDigits(powerOf10.add(ONE)), equalTo(n + 1)); assertThat("wrong number of digits for " + negativePowerOf10.subtract(ONE), PowerMath.numberOfDigits(negativePowerOf10.subtract(ONE)), equalTo(n + 1)); } } }
mtymes: updated PowerMathTest
src/test/java/mtymes/javafixes/beta/decimal/PowerMathTest.java
mtymes: updated PowerMathTest
Java
apache-2.0
3d643132bd595a0516b0e79962c957ba4ca58c60
0
venicegeo/pz-jobcommon
/** * Copyright 2016, RadiantBlue Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ package messaging.job; import java.io.IOException; import model.data.DataResource; import model.job.Job; import model.job.type.IngestJob; import model.request.PiazzaJobRequest; import model.status.StatusUpdate; import org.apache.kafka.clients.producer.ProducerRecord; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; /** * Factory class to abstract the production of Job-related Kafka messages using * this projects defined POJO Models. * * @author Patrick.Doody * */ public class JobMessageFactory { public static final String REQUEST_JOB_TOPIC_NAME = "Request-Job"; public static final String CREATE_JOB_TOPIC_NAME = "Create-Job"; public static final String ABORT_JOB_TOPIC_NAME = "Abort-Job"; public static final String UPDATE_JOB_TOPIC_NAME = "Update-Job"; /** * Creates a Kafka message for a Piazza Job to be created. This Topic is * listened to solely by the Dispatcher and acts as a simple pass-through * from the outer world to the internal Piazza components. * * @param piazzaRequest * The Job to be created. * @param jobId * The ID of the Job * @return Kafka message * @throws JsonProcessingException * The PiazzaJob cannot be serialized to JSON. */ public static ProducerRecord<String, String> getRequestJobMessage(PiazzaJobRequest piazzaRequest, String jobId, String space) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); return new ProducerRecord<String, String>(String.format("%s-%s", REQUEST_JOB_TOPIC_NAME, space), jobId, mapper.writeValueAsString(piazzaRequest)); } /** * Creates a Kafka message for a Piazza Job to be cancelled; referenced by * Job ID. This message is consumed by the Job Manager, which will update * the Job Tables, and any other components that are required to act on the * Job being cancelled. * * @param abortJob * The Job, describing the Job to abort and potential reason for * requesting the cancellation. * @return Kafka Message * @throws JsonProcessingException */ public static ProducerRecord<String, String> getAbortJobMessage(PiazzaJobRequest piazzaRequest, String jobId, String space) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); return new ProducerRecord<String, String>(String.format("%s-%s", ABORT_JOB_TOPIC_NAME, space), jobId, mapper.writeValueAsString(piazzaRequest)); } /** * Creates a Kafka message that wraps up a Status Update for a Job. This is * intended to be produced by the Worker component that owns this Job. * * This can also be used to post the result to the Job. If you're setting * the status of the job to complete, you can also set the * StatusUpdate.setResult() method to attach some resulting object or ID * that the job has created. * * @param jobId * The ID of the Job being updated * @param statusUpdate * Status Update information * @return * @throws JsonProcessingException */ public static ProducerRecord<String, String> getUpdateStatusMessage(String jobId, StatusUpdate statusUpdate, String space) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); return new ProducerRecord<String, String>(String.format("%s-%s", UPDATE_JOB_TOPIC_NAME, space), jobId, mapper.writeValueAsString(statusUpdate)); } /** * Creates a Kafka message for a Piazza Job to be created. This Topic is * designed to be consumed by the Job Manager component. The JobManager will * track this message and use it to commit the job transaction record into * the Job Tables. * * @param job * The Job to be indexed by the Job Manager * @return Kafka message * @throws JsonProcessingException * The PiazzaJob cannot be serialized to JSON. */ public static ProducerRecord<String, String> getJobManagerCreateJobMessage(Job job, String space) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); return new ProducerRecord<String, String>(String.format("%s-%s", CREATE_JOB_TOPIC_NAME, space), job.getJobId(), mapper.writeValueAsString(job)); } /** * Creates a Job Request method for an Ingest Job to ingest the specified * Data Resource, and assigns the specified Job ID to this Ingest job. The * DataResource passed into this first argument MUST have its DataId * specified. * * This method is only to be used by internal Piazza components who * *understand how the Job Process works*. This method is an abstraction * around creating an IngestJob to the system, where a DataResource is meant * to be ingested. * * Instead of having the developer create a PiazzaJobRequest, followed up by * an IngestJob, and then finally specifying the DataResource, this method * aims to abstract out those first two steps and require only the * DataResource to be ingested. This method will handle the rest of the * creation and return the Kafka message that can be sent in order to create * the Ingst Job. * * @param dataResource * The Data Resource to be ingested * @param jobId * The Job ID of the Ingest Job that will be created * @param userName * The authenticated UserName * @return The Kafka message for creating the Ingest Job, that can be Send * via a producer. */ public static ProducerRecord<String, String> getIngestJobForDataResource(DataResource dataResource, String jobId, String userName, String space) throws Exception { // Data Resource must have an ID at this point if (dataResource.getDataId() == null) { throw new Exception("The DataResource object must have a populated ID."); } // Create the IngestJob IngestJob ingestJob = new IngestJob(); ingestJob.data = dataResource; ingestJob.host = true; // This method is only for internal components, // so we will always host // Create the Job Request and attach the IngestJob PiazzaJobRequest jobRequest = new PiazzaJobRequest(); jobRequest.userName = userName; jobRequest.jobType = ingestJob; ProducerRecord<String, String> ingestJobMessage = JobMessageFactory.getRequestJobMessage(jobRequest, jobId, space); // This message will now be handled by the Dispatcher the same as any // other Job request return ingestJobMessage; } /** * Creates a Kafka message for a Piazza Job to be created and consumed by * the internal Piazza worker. This topic is different from the above * method, getJobManagerCreateJobMessage, in that it is meant to be consumed * not by the Job Manager, but the internal component that will be * performing the actual work on the job. Thus, the topic for this message * is dynamic based on the JobType's type field. * * @param job * The Job to be processed by the internal worker component. * @returnKafka message * @throws JsonProcessingException * The PiazzaJob cannot be serialized to JSON. */ public static ProducerRecord<String, String> getWorkerJobCreateMessage(Job job, String space) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); System.out.println(job.jobType.getType()); return new ProducerRecord<String, String>(job.jobType.getType(), job.getJobId(), mapper.writeValueAsString(job)); } /** * Parses the raw JSON Payload into the PiazzaRest backing models. No value * validation done here, only syntax. * * @param json * JSON Payload from POST RequestBody * @return PiazzaRequest object for the JSON Payload. * @throws Exception */ public static PiazzaJobRequest parseRequestJson(String json) throws IOException, JsonParseException, JsonMappingException { PiazzaJobRequest request = new ObjectMapper().readValue(json, PiazzaJobRequest.class); return request; } }
src/main/java/messaging/job/JobMessageFactory.java
/** * Copyright 2016, RadiantBlue Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ package messaging.job; import java.io.IOException; import model.data.DataResource; import model.job.Job; import model.job.type.AbortJob; import model.job.type.IngestJob; import model.request.PiazzaJobRequest; import model.status.StatusUpdate; import org.apache.kafka.clients.producer.ProducerRecord; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; /** * Factory class to abstract the production of Job-related Kafka messages using * this projects defined POJO Models. * * @author Patrick.Doody * */ public class JobMessageFactory { public static final String REQUEST_JOB_TOPIC_NAME = "Request-Job"; public static final String CREATE_JOB_TOPIC_NAME = "Create-Job"; public static final String ABORT_JOB_TOPIC_NAME = "Abort-Job"; public static final String UPDATE_JOB_TOPIC_NAME = "Update-Job"; /** * Creates a Kafka message for a Piazza Job to be created. This Topic is * listened to solely by the Dispatcher and acts as a simple pass-through * from the outer world to the internal Piazza components. * * @param piazzaRequest * The Job to be created. * @param jobId * The ID of the Job * @return Kafka message * @throws JsonProcessingException * The PiazzaJob cannot be serialized to JSON. */ public static ProducerRecord<String, String> getRequestJobMessage(PiazzaJobRequest piazzaRequest, String jobId) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); return new ProducerRecord<String, String>(REQUEST_JOB_TOPIC_NAME, jobId, mapper.writeValueAsString(piazzaRequest)); } /** * Creates a Kafka message for a Piazza Job to be cancelled; referenced by * Job ID. This message is consumed by the Job Manager, which will update * the Job Tables, and any other components that are required to act on the * Job being cancelled. * * @param abortJob * The Job, describing the Job to abort and potential reason for * requesting the cancellation. * @return Kafka Message * @throws JsonProcessingException */ public static ProducerRecord<String, String> getAbortJobMessage(PiazzaJobRequest piazzaRequest, String jobId) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); return new ProducerRecord<String, String>(ABORT_JOB_TOPIC_NAME, jobId, mapper.writeValueAsString(piazzaRequest)); } /** * Creates a Kafka message that wraps up a Status Update for a Job. This is * intended to be produced by the Worker component that owns this Job. * * This can also be used to post the result to the Job. If you're setting * the status of the job to complete, you can also set the * StatusUpdate.setResult() method to attach some resulting object or ID * that the job has created. * * @param jobId * The ID of the Job being updated * @param statusUpdate * Status Update information * @return * @throws JsonProcessingException */ public static ProducerRecord<String, String> getUpdateStatusMessage(String jobId, StatusUpdate statusUpdate) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); return new ProducerRecord<String, String>(UPDATE_JOB_TOPIC_NAME, jobId, mapper.writeValueAsString(statusUpdate)); } /** * Creates a Kafka message for a Piazza Job to be created. This Topic is * designed to be consumed by the Job Manager component. The JobManager will * track this message and use it to commit the job transaction record into * the Job Tables. * * @param job * The Job to be indexed by the Job Manager * @return Kafka message * @throws JsonProcessingException * The PiazzaJob cannot be serialized to JSON. */ public static ProducerRecord<String, String> getJobManagerCreateJobMessage(Job job) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); return new ProducerRecord<String, String>(CREATE_JOB_TOPIC_NAME, job.getJobId(), mapper.writeValueAsString(job)); } /** * Creates a Job Request method for an Ingest Job to ingest the specified * Data Resource, and assigns the specified Job ID to this Ingest job. The * DataResource passed into this first argument MUST have its DataId * specified. * * This method is only to be used by internal Piazza components who * *understand how the Job Process works*. This method is an abstraction * around creating an IngestJob to the system, where a DataResource is meant * to be ingested. * * Instead of having the developer create a PiazzaJobRequest, followed up by * an IngestJob, and then finally specifying the DataResource, this method * aims to abstract out those first two steps and require only the * DataResource to be ingested. This method will handle the rest of the * creation and return the Kafka message that can be sent in order to create * the Ingst Job. * * @param dataResource * The Data Resource to be ingested * @param jobId * The Job ID of the Ingest Job that will be created * @param userName * The authenticated UserName * @return The Kafka message for creating the Ingest Job, that can be Send * via a producer. */ public static ProducerRecord<String, String> getIngestJobForDataResource(DataResource dataResource, String jobId, String userName) throws Exception { // Data Resource must have an ID at this point if (dataResource.getDataId() == null) { throw new Exception("The DataResource object must have a populated ID."); } // Create the IngestJob IngestJob ingestJob = new IngestJob(); ingestJob.data = dataResource; ingestJob.host = true; // This method is only for internal components, // so we will always host // Create the Job Request and attach the IngestJob PiazzaJobRequest jobRequest = new PiazzaJobRequest(); jobRequest.userName = userName; jobRequest.jobType = ingestJob; ProducerRecord<String, String> ingestJobMessage = JobMessageFactory.getRequestJobMessage(jobRequest, jobId); // This message will now be handled by the Dispatcher the same as any // other Job request return ingestJobMessage; } /** * Creates a Kafka message for a Piazza Job to be created and consumed by * the internal Piazza worker. This topic is different from the above * method, getJobManagerCreateJobMessage, in that it is meant to be consumed * not by the Job Manager, but the internal component that will be * performing the actual work on the job. Thus, the topic for this message * is dynamic based on the JobType's type field. * * @param job * The Job to be processed by the internal worker component. * @returnKafka message * @throws JsonProcessingException * The PiazzaJob cannot be serialized to JSON. */ public static ProducerRecord<String, String> getWorkerJobCreateMessage(Job job) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); System.out.println(job.jobType.getType()); return new ProducerRecord<String, String>(job.jobType.getType(), job.getJobId(), mapper.writeValueAsString(job)); } /** * Creates a Kafka message for the Piazza Job Status. This Topic is designed * to be consumed by the Piazza Gateway that will return the status to the * end-user. * * @param topic * The topic to place the message on. * @param key * A field representing a name for the JobId. * @param value * A field representing the JobId value. * * @return Kafka message */ public static ProducerRecord<String, String> getJobReturnMessage(String topic, String key, String value) { return new ProducerRecord<String, String>(topic, key, value); } /** * Parses the raw JSON Payload into the PiazzaRest backing models. No value * validation done here, only syntax. * * @param json * JSON Payload from POST RequestBody * @return PiazzaRequest object for the JSON Payload. * @throws Exception */ public static PiazzaJobRequest parseRequestJson(String json) throws IOException, JsonParseException, JsonMappingException { PiazzaJobRequest request = new ObjectMapper().readValue(json, PiazzaJobRequest.class); return request; } }
environment space in topic names
src/main/java/messaging/job/JobMessageFactory.java
environment space in topic names
Java
apache-2.0
ac95fe895c1aabebf50e9c8f6e0208b615174ac8
0
google/flogger,google/flogger
/* * Copyright (C) 2012 The Flogger 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.google.common.flogger; import static com.google.common.flogger.util.CallerFinder.getStackForCallerOf; import static com.google.common.flogger.util.Checks.checkNotNull; import static java.util.concurrent.TimeUnit.NANOSECONDS; import com.google.common.flogger.LogSiteStats.RateLimitPeriod; import com.google.common.flogger.backend.LogData; import com.google.common.flogger.backend.Metadata; import com.google.common.flogger.backend.Platform; import com.google.common.flogger.backend.Tags; import com.google.common.flogger.backend.TemplateContext; import com.google.common.flogger.parser.MessageParser; import com.google.errorprone.annotations.CheckReturnValue; import java.util.Arrays; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import javax.annotation.Nullable; /** * The base context for a logging statement, which implements the base logging API. * <p> * This class is an implementation of the base {@link LoggingApi} interface and acts as a holder for * any state applied to the log statement during the fluent call sequence. The lifecycle of a * logging context is very short; it is created by a logger, usually in response to a call to the * {@link AbstractLogger#at(Level)} method, and normally lasts only as long as the log statement. * <p> * This class should not be visible to normal users of the logging API and it is only needed when * extending the API to add more functionality. In order to extend the logging API and add methods * to the fluent call chain, the {@code LoggingApi} interface should be extended to add any new * methods, and this class should be extended to implement them. A new logger class will then be * needed to return the extended context. * <p> * Logging contexts are not thread safe. */ @CheckReturnValue public abstract class LogContext< LOGGER extends AbstractLogger<API>, API extends LoggingApi<API>> implements LoggingApi<API>, LogData { /** * The predefined metadata keys used by the default logging API. Backend implementations can use * these to identify metadata added by the core logging API. */ // TODO: Reevaluate this whole strategy before open-sourcing. public static final class Key { private Key() {} /** * The key associated with a {@link Throwable} cause to be associated with the log message. This * value is set by {@link LoggingApi#withCause(Throwable)}. */ public static final MetadataKey<Throwable> LOG_CAUSE = MetadataKey.single("cause", Throwable.class); /** * The key associated with a rate limiting counter for "1-in-N" rate limiting. The value is set * by {@link LoggingApi#every(int)}. */ public static final MetadataKey<Integer> LOG_EVERY_N = MetadataKey.single("ratelimit_count", Integer.class); /** * The key associated with a rate limiting period for "at most once every N" rate limiting. The * value is set by {@link LoggingApi#atMostEvery(int, TimeUnit)}. */ public static final MetadataKey<RateLimitPeriod> LOG_AT_MOST_EVERY = MetadataKey.single("ratelimit_period", RateLimitPeriod.class); /** * The key associated with a {@code Boolean} value used to specify that the log statement must * be emitted. * <p> * Forcing a log statement ensures that the {@code LoggerBackend} is passed the {@code LogData} * for this log statement regardless of the backend's log level or any other filtering or rate * limiting which might normally occur. If a log statement is forced, this key will be set * immediately on creation of the logging context and will be visible to both fluent methods * and post-processing. * <p> * Filtering and rate-limiting methods must check for this value and should treat forced log * statements as not having had any filtering or rate limiting applied. For example, if the * following log statement was forced: * <pre>{@code * logger.atInfo().withCause(e).atMostEvery(1, MINUTES).log("Message..."); * }</pre> * it should behave as if the rate-limiting methods were never called, such as: * <pre>{@code * logger.atInfo().withCause(e).log("Message..."); * }</pre> * As well as no longer including any rate-limiting metadata for the forced log statement, this * also has the effect of never interfering with the rate-limiting of this log statement for * other callers. * <p> * The decision of whether to force a log statement is expected to be made based upon debug * values provded by the logger which come from a scope greater than the log statement itself. * Thus it makes no sense to provide a public method to set this value programmatically for a * log statement. */ public static final MetadataKey<Boolean> WAS_FORCED = MetadataKey.single("forced", Boolean.class); /** * The key associated with any injected metadata (in the form of a {@code Tags} instance. * <p> * If tags are injected, they are added after post-processing if the log site is enabled. Thus * they are no available to the {@code postProcess()} method itself. The rationale is that a * log statement's behavior should only be affected by code at the log site (other than * "forcing" log statements, which is slightly a special case). */ public static final MetadataKey<Tags> TAGS = MetadataKey.single("tags", Tags.class); /** * Key associated with the metadata for specifying additional stack information with a log * statement. */ public static final MetadataKey<StackSize> CONTEXT_STACK_SIZE = MetadataKey.single("stack_size", StackSize.class); } static final class MutableMetadata extends Metadata { /** * The default number of key/value pairs we initially allocate space for when someone adds * metadata to this context. * <p> * Note: As of 10/12 the VM allocates small object arrays very linearly with respect to the * number of elements (an array has a 12 byte header with 4 bytes/element for object * references). The allocation size is always rounded up to the next 8 bytes which means we * can just pick a small value for the initial size and grow from there without too much waste. * <p> * For 4 key/value pairs, we will need 8 elements in the array, which will take up 48 bytes * {@code (12 + (8 * 4) = 44}, which when rounded up is 48. */ private static final int INITIAL_KEY_VALUE_CAPACITY = 4; /** * The array of key/value pairs to hold any metadata the might be added by the logger or any of * the fluent methods on our API. This is an array so it is as space efficient as possible. */ private Object[] keyValuePairs = new Object[2 * INITIAL_KEY_VALUE_CAPACITY]; /** The number of key/value pairs currently stored in the array. */ private int keyValueCount = 0; @Override public int size() { return keyValueCount; } @Override public MetadataKey<?> getKey(int n) { if (n >= keyValueCount) { throw new IndexOutOfBoundsException(); } return (MetadataKey<?>) keyValuePairs[2 * n]; } @Override public Object getValue(int n) { if (n >= keyValueCount) { throw new IndexOutOfBoundsException(); } return keyValuePairs[(2 * n) + 1]; } private int indexOf(MetadataKey<?> key) { for (int index = 0; index < keyValueCount; index++) { if (keyValuePairs[2 * index].equals(key)) { return index; } } return -1; } @Override @Nullable public <T> T findValue(MetadataKey<T> key) { int index = indexOf(key); return index != -1 ? key.cast(keyValuePairs[(2 * index) + 1]) : null; } /** * Adds the key/value pair to the metadata (growing the internal array as necessary). If the * key cannot be repeated, and there is already a value for the key in the metadata, then the * existing value is replaced, otherwise the value is added at the end of the metadata. */ <T> void addValue(MetadataKey<T> key, T value) { if (!key.canRepeat()) { int index = indexOf(key); if (index != -1) { keyValuePairs[(2 * index) + 1] = checkNotNull(value, "metadata value"); return; } } // Check that the array is big enough for one more element. if (2 * (keyValueCount + 1) > keyValuePairs.length) { // Use doubling here (this code should almost never be hit in normal usage and the total // number of items should always stay relatively small. If this resizing algorithm is ever // modified it is vital that the new value is always an even number. keyValuePairs = Arrays.copyOf(keyValuePairs, 2 * keyValuePairs.length); } keyValuePairs[2 * keyValueCount] = checkNotNull(key, "metadata key"); keyValuePairs[(2 * keyValueCount) + 1] = checkNotNull(value, "metadata value"); keyValueCount += 1; } /** Removes all key/value pairs for a given key. */ void removeAllValues(MetadataKey<?> key) { int index = indexOf(key); if (index >= 0) { int dest = 2 * index; int src = dest + 2; while (src < (2 * keyValueCount)) { Object nextKey = keyValuePairs[src]; if (!nextKey.equals(key)) { keyValuePairs[dest] = nextKey; keyValuePairs[dest + 1] = keyValuePairs[src + 1]; dest += 2; } src += 2; } // We know src & dest are +ve and (src > dest), so shifting is safe here. keyValueCount -= (src - dest) >> 1; while (dest < src) { keyValuePairs[dest++] = null; } } } /** Strictly for debugging. */ @Override public String toString() { StringBuilder out = new StringBuilder("Metadata{"); for (int n = 0; n < size(); n++) { out.append(" '").append(getKey(n)).append("': ").append(getValue(n)); } return out.append(" }").toString(); } } /** * A simple token used to identify cases where a single literal value is logged. Note that this * instance must be unique and it is important not to replace this with {@code ""} or any other * value than might be interned and be accessible to code outside this class. */ private static final String LITERAL_VALUE_MESSAGE = new String(); // TODO: Aggressively attempt to reduce the number of fields in this instance. /** The log level of the log statement that this context was created for. */ private final Level level; /** The timestamp of the log statement that this context is associated with. */ private final long timestampNanos; /** Additional metadata for this log statement (added via fluent API methods). */ private MutableMetadata metadata = null; /** The log site information for this log statement (set immediately prior to post-processing). */ private LogSite logSite = null; /** The template context if formatting is required (set only after post-processing). */ private TemplateContext templateContext = null; /** The log arguments (set only after post-processing). */ private Object[] args = null; /** * Creates a logging context with the specified level, and with a timestamp obtained from the * configured logging {@link Platform}. * * @param level the log level for this log statement. * @param isForced whether to force this log statement (see {@link #wasForced()} for details). */ protected LogContext(Level level, boolean isForced) { this(level, isForced, Platform.getCurrentTimeNanos()); } /** * Creates a logging context with the specified level and timestamp. This constructor is provided * only for testing when timestamps need to be injected. In general, subclasses would only need * to call this constructor when testing additional API methods which require timestamps (e.g. * additional rate limiting functionality). Most unit tests for logger subclasses should not * test the value of the timestamp at all, since this is already well tested elsewhere. * * @param level the log level for this log statement. * @param isForced whether to force this log statement (see {@link #wasForced()} for details). * @param timestampNanos the nanosecond timestamp for this log statement. */ protected LogContext(Level level, boolean isForced, long timestampNanos) { this.level = checkNotNull(level, "level"); this.timestampNanos = timestampNanos; if (isForced) { addMetadata(Key.WAS_FORCED, Boolean.TRUE); } } /** * Returns the current API (which is just the concrete sub-type of this instance). This is * returned by fluent methods to continue the fluent call chain. */ protected abstract API api(); // ---- Logging Context Constants ---- /** * Returns the logger which created this context. This is implemented as an abstract method to * save a field in every context. */ protected abstract LOGGER getLogger(); /** * Returns the constant no-op logging API, which can be returned by fluent methods in extended * logging contexts to efficiently disable logging. This is implemented as an abstract method to * save a field in every context. */ protected abstract API noOp(); /** * Returns the message parser used for all log statements made through this logger. */ protected abstract MessageParser getMessageParser(); // ---- LogData API ---- @Override public final Level getLevel() { return level; } @Deprecated @Override public final long getTimestampMicros() { return NANOSECONDS.toMicros(timestampNanos); } @Override public final long getTimestampNanos() { return timestampNanos; } @Override public final String getLoggerName() { return getLogger().getBackend().getLoggerName(); } @Override public final LogSite getLogSite() { if (logSite == null) { throw new IllegalStateException("cannot request log site information prior to postProcess()"); } return logSite; } @Override public final TemplateContext getTemplateContext() { return templateContext; } @Override public final Object[] getArguments() { if (templateContext == null) { throw new IllegalStateException("cannot get arguments unless a template context exists"); } return args; } @Override public final Object getLiteralArgument() { if (templateContext != null) { throw new IllegalStateException("cannot get literal argument if a template context exists"); } return args[0]; } @Override public final boolean wasForced() { // Check explicit TRUE here because findValue() can return null (which would fail unboxing). return metadata != null && Boolean.TRUE.equals(metadata.findValue(Key.WAS_FORCED)); } /** * Returns any additional metadata for this log statement. * <p> * When called outside of the logging backend, this method may return different values * at different times (ie, it may initially return a shared static "empty" metadata object and * later return a different implementation). As such it is not safe to cache the instance * returned by this method or to attempt to cast it to any particular implementation. */ @Override public final Metadata getMetadata() { return metadata != null ? metadata : Metadata.empty(); } // ---- Mutable Metadata ---- /** * Adds the given key/value pair to this logging context. If the key cannot be repeated, and * there is already a value for the key in the metadata, then the existing value is replaced, * otherwise the value is added at the end of the metadata. * * @param key the metadata key (see {@link LogData}). * @param value the metadata value. */ protected final <T> void addMetadata(MetadataKey<T> key, T value) { if (metadata == null) { metadata = new MutableMetadata(); } metadata.addValue(key, value); } /** * Removes all key/value pairs with the specified key. Note that this method does not resize any * underlying backing arrays or other storage as logging contexts are expected to be short lived. * * @param key the metadata key (see {@link LogData}). */ protected final void removeMetadata(MetadataKey<?> key) { if (metadata != null) { metadata.removeAllValues(key); } } // ---- Post processing ---- /** * A callback that can be overridden to implement post processing of logging context prior to * invoking the backend. * * <p>If a fluent method invoked during the log statement requires access to persistent state * during post-processing, {@code logSiteKey} can be used to look it up. If this log statement * cannot be identified uniquely, then {@code logSiteKey} will be {@code null}, and this method * must behave exactly as if the corresponding fluent method had not been invoked. * * <p>Thus on a system in which log site information is unavailable: * * <pre>{@code logger.atInfo().every(100).withCause(e).log("Some message"); }</pre> * * should behave exactly the same as: * * <pre>{@code logger.atInfo().withCause(e).log("Some message"); }</pre> * * <p>Implementations of this method must always call {@code super.postProcess()} first with the * given log site key, such as: * * <pre>{@code protected boolean postProcess(@Nullable LogSiteKey logSiteKey) { * if (!super.postProcess(logSiteKey)) { * return false; * } * ... * return shouldLog; * }}</pre> * * <p>If a method in the logging chain can determine that logging should definitely be disabled * then it is generally better to return the NoOp API implementation at that point rather than * waiting until here to cancel the operation, although care must be taken to check whether the * log statement has been "forced" or not. * * * <p>The default implementation of this method enforces the rate limits as set by {@link * #every(int)} or {@link #atMostEvery(int, TimeUnit)}. * * @param logSiteKey used to lookup persistent, per log statement, state. * @return true if the logging backend should be invoked to output the current log statement. */ protected boolean postProcess(@Nullable LogSiteKey logSiteKey) { if (metadata != null && logSiteKey != null) { // This code still gets reached if a "cause" was set, but as that's far more likely than any // other metadata that might suppress logging, it's not worth any more "early out" checks. // If we have a cause, we're almost certainly logging it, and that's expensive anyway. Integer rateLimitCount = metadata.findValue(Key.LOG_EVERY_N); RateLimitPeriod rateLimitPeriod = metadata.findValue(Key.LOG_AT_MOST_EVERY); LogSiteStats stats = LogSiteStats.getStatsForKey(logSiteKey); if (rateLimitCount != null && !stats.incrementAndCheckInvocationCount(rateLimitCount)) { return false; } if (rateLimitPeriod != null && !stats.checkLastTimestamp(getTimestampNanos(), rateLimitPeriod)) { return false; } } // This does not affect whether logging will occur, only what additional data it contains. StackSize stackSize = getMetadata().findValue(Key.CONTEXT_STACK_SIZE); if (stackSize != null) { // we add this information to the stack trace exception so it doesn't need to go here. removeMetadata(Key.CONTEXT_STACK_SIZE); LogSiteStackTrace context = new LogSiteStackTrace( getMetadata().findValue(LogContext.Key.LOG_CAUSE), stackSize, getStackForCallerOf(LogContext.class, new Throwable(), stackSize.getMaxDepth())); // The "cause" is a unique metadata key, we must replace any existing value. addMetadata(LogContext.Key.LOG_CAUSE, context); } // By default, no restrictions apply so we should log. return true; } /** * Pre-processes log metadata and determines whether we should make the pending logging call. * <p> * Note that this call is made inside each of the individual log methods (rather than in * {@code logImpl()}) because it is better to decide whether we are actually going to do the * logging before we pay the price of creating a varargs array and doing things like auto-boxing * of arguments. */ private boolean shouldLog() { // The log site may have already been injected via "withInjectedLogSite()". if (logSite == null) { // From the point at which we call inferLogSite() we can skip 1 additional method (the // shouldLog() method itself) when looking up the stack to find the log() method. logSite = checkNotNull(Platform.getCallerFinder().findLogSite(LogContext.class, 1), "logger backend must not return a null LogSite"); } LogSiteKey logSiteKey = null; if (logSite != LogSite.INVALID) { logSiteKey = logSite; } if (!postProcess(logSiteKey)) { return false; } // Right at the end of post processing add any tags injected by the platform. Alternately this // could be done in logImpl(), but it would have the same effect. This should be the last piece // of metadata added to a LogData instance (but users are not allowed to rely on that). Tags tags = Platform.getInjectedTags(); if (!tags.isEmpty()) { addMetadata(Key.TAGS, tags); } return true; } /** * Make the backend logging call. This is the point at which we have paid the price of creating a * varargs array and doing any necessary auto-boxing. */ @SuppressWarnings("ReferenceEquality") private void logImpl(String message, Object... args) { this.args = args; // Evaluate any (rare) LazyArg instances early. This may throw exceptions from user code, but // it seems reasonable to propagate them in this case (they would have been thrown if the // argument was evaluated at the call site anyway). for (int n = 0; n < args.length; n++) { if (args[n] instanceof LazyArg) { args[n] = ((LazyArg<?>) args[n]).evaluate(); } } // Using "!=" is fast and sufficient here because the only real case this should be skipping // is when we called log(String) or log(), which should not result in a template being created. // DO NOT replace this with a string instance which can be interned, or use equals() here, // since that could mistakenly treat other calls to log(String, Object...) incorrectly. if (message != LITERAL_VALUE_MESSAGE) { this.templateContext = new TemplateContext(getMessageParser(), message); } getLogger().write(this); } // ---- Log site injection (used by pre-processors and special cases) ---- @Override public final API withInjectedLogSite(LogSite logSite) { // First call wins (since auto-injection will typically target the log() method at the end of // the chain and might not check for previous explicit injection). if (this.logSite == null) { this.logSite = checkNotNull(logSite, "log site"); } return api(); } @SuppressWarnings("deprecation") @Override public final API withInjectedLogSite( String internalClassName, String methodName, int encodedLineNumber, @Nullable String sourceFileName) { return withInjectedLogSite( LogSite.injectedLogSite(internalClassName, methodName, encodedLineNumber, sourceFileName)); } // ---- Public logging API ---- @Override public final boolean isEnabled() { // We can't guarantee that all logger implementations will return instances of this class // _only_ when logging is enabled, so if would be potentially unsafe to just return true here. // It's not worth caching this result in the instance because calls to this method should be // rare and they are only going to be made once per instance anyway. return wasForced() || getLogger().isLoggable(level); } @Override public final API withCause(Throwable cause) { if (cause != null) { addMetadata(Key.LOG_CAUSE, cause); } return api(); } @Override public API withStackTrace(StackSize size) { if (checkNotNull(size, "stack size") != StackSize.NONE) { addMetadata(Key.CONTEXT_STACK_SIZE, size); } return api(); } @Override public final API every(int n) { // See wasForced() for discussion as to why this occurs before argument checking. if (wasForced()) { return api(); } if (n <= 0) { throw new IllegalArgumentException("rate limit count must be positive"); } // 1-in-1 rate limiting is a no-op. if (n > 1) { addMetadata(Key.LOG_EVERY_N, n); } return api(); } @Override public final API atMostEvery(int n, TimeUnit unit) { // See wasForced() for discussion as to why this occurs before argument checking. if (wasForced()) { return api(); } if (n < 0) { throw new IllegalArgumentException("rate limit period cannot be negative"); } // Rate limiting with a zero length period is a no-op, but if the time unit is nanoseconds then // the value is rounded up inside the rate limit object. if (n > 0) { addMetadata(Key.LOG_AT_MOST_EVERY, LogSiteStats.newRateLimitPeriod(n, unit)); } return api(); } /* * Note that while all log statements look almost identical to each other, it is vital that we * keep the 'shouldLog()' call outside of the call to 'logImpl()' so we can decide whether or not * to abort logging before we do any varargs creation. */ @Override public final void log() { if (shouldLog()) logImpl(LITERAL_VALUE_MESSAGE, ""); } @Override public final void log(String msg) { if (shouldLog()) logImpl(LITERAL_VALUE_MESSAGE, msg); } @Override public final void log(String message, @Nullable Object p1) { if (shouldLog()) logImpl(message, p1); } @Override public final void log(String message, @Nullable Object p1, @Nullable Object p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log( String message, @Nullable Object p1, @Nullable Object p2, @Nullable Object p3) { if (shouldLog()) logImpl(message, p1, p2, p3); } @Override public final void log( String message, @Nullable Object p1, @Nullable Object p2, @Nullable Object p3, @Nullable Object p4) { if (shouldLog()) logImpl(message, p1, p2, p3, p4); } @Override public final void log( String msg, @Nullable Object p1, @Nullable Object p2, @Nullable Object p3, @Nullable Object p4, @Nullable Object p5) { if (shouldLog()) logImpl(msg, p1, p2, p3, p4, p5); } @Override public final void log( String msg, @Nullable Object p1, @Nullable Object p2, @Nullable Object p3, @Nullable Object p4, @Nullable Object p5, @Nullable Object p6) { if (shouldLog()) logImpl(msg, p1, p2, p3, p4, p5, p6); } @Override public final void log( String msg, @Nullable Object p1, @Nullable Object p2, @Nullable Object p3, @Nullable Object p4, @Nullable Object p5, @Nullable Object p6, @Nullable Object p7) { if (shouldLog()) logImpl(msg, p1, p2, p3, p4, p5, p6, p7); } @Override public final void log( String msg, @Nullable Object p1, @Nullable Object p2, @Nullable Object p3, @Nullable Object p4, @Nullable Object p5, @Nullable Object p6, @Nullable Object p7, @Nullable Object p8) { if (shouldLog()) logImpl(msg, p1, p2, p3, p4, p5, p6, p7, p8); } @Override public final void log( String msg, @Nullable Object p1, @Nullable Object p2, @Nullable Object p3, @Nullable Object p4, @Nullable Object p5, @Nullable Object p6, @Nullable Object p7, @Nullable Object p8, @Nullable Object p9) { if (shouldLog()) logImpl(msg, p1, p2, p3, p4, p5, p6, p7, p8, p9); } @Override public final void log( String msg, @Nullable Object p1, @Nullable Object p2, @Nullable Object p3, @Nullable Object p4, @Nullable Object p5, @Nullable Object p6, @Nullable Object p7, @Nullable Object p8, @Nullable Object p9, @Nullable Object p10) { if (shouldLog()) logImpl(msg, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10); } @Override public final void log( String msg, @Nullable Object p1, @Nullable Object p2, @Nullable Object p3, @Nullable Object p4, @Nullable Object p5, @Nullable Object p6, @Nullable Object p7, @Nullable Object p8, @Nullable Object p9, @Nullable Object p10, Object... rest) { if (shouldLog()) { // Manually create a new varargs array and copy the parameters in. Object[] params = new Object[rest.length + 10]; params[0] = p1; params[1] = p2; params[2] = p3; params[3] = p4; params[4] = p5; params[5] = p6; params[6] = p7; params[7] = p8; params[8] = p9; params[9] = p10; System.arraycopy(rest, 0, params, 10, rest.length); logImpl(msg, params); } } @Override public final void log(String message, char p1) { if (shouldLog()) logImpl(message, p1); } @Override public final void log(String message, byte p1) { if (shouldLog()) logImpl(message, p1); } @Override public final void log(String message, short p1) { if (shouldLog()) logImpl(message, p1); } @Override public final void log(String message, int p1) { if (shouldLog()) logImpl(message, p1); } @Override public final void log(String message, long p1) { if (shouldLog()) logImpl(message, p1); } @Override public final void log(String message, @Nullable Object p1, boolean p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, @Nullable Object p1, char p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, @Nullable Object p1, byte p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, @Nullable Object p1, short p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, @Nullable Object p1, int p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, @Nullable Object p1, long p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, @Nullable Object p1, float p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, @Nullable Object p1, double p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, boolean p1, @Nullable Object p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, char p1, @Nullable Object p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, byte p1, @Nullable Object p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, short p1, @Nullable Object p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, int p1, @Nullable Object p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, long p1, @Nullable Object p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, float p1, @Nullable Object p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, double p1, @Nullable Object p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, boolean p1, boolean p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, char p1, boolean p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, byte p1, boolean p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, short p1, boolean p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, int p1, boolean p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, long p1, boolean p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, float p1, boolean p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, double p1, boolean p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, boolean p1, char p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, char p1, char p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, byte p1, char p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, short p1, char p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, int p1, char p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, long p1, char p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, float p1, char p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, double p1, char p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, boolean p1, byte p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, char p1, byte p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, byte p1, byte p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, short p1, byte p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, int p1, byte p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, long p1, byte p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, float p1, byte p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, double p1, byte p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, boolean p1, short p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, char p1, short p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, byte p1, short p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, short p1, short p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, int p1, short p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, long p1, short p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, float p1, short p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, double p1, short p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, boolean p1, int p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, char p1, int p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, byte p1, int p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, short p1, int p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, int p1, int p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, long p1, int p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, float p1, int p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, double p1, int p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, boolean p1, long p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, char p1, long p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, byte p1, long p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, short p1, long p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, int p1, long p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, long p1, long p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, float p1, long p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, double p1, long p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, boolean p1, float p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, char p1, float p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, byte p1, float p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, short p1, float p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, int p1, float p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, long p1, float p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, float p1, float p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, double p1, float p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, boolean p1, double p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, char p1, double p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, byte p1, double p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, short p1, double p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, int p1, double p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, long p1, double p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, float p1, double p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, double p1, double p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void logVarargs(String message, Object[] params) { if (shouldLog()) { // Copy the varargs array (because we didn't create it and this is quite a rare case). logImpl(message, Arrays.copyOf(params, params.length)); } } }
api/src/main/java/com/google/common/flogger/LogContext.java
/* * Copyright (C) 2012 The Flogger 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.google.common.flogger; import static com.google.common.flogger.util.CallerFinder.getStackForCallerOf; import static com.google.common.flogger.util.Checks.checkNotNull; import static java.util.concurrent.TimeUnit.NANOSECONDS; import com.google.common.flogger.LogSiteStats.RateLimitPeriod; import com.google.common.flogger.backend.LogData; import com.google.common.flogger.backend.Metadata; import com.google.common.flogger.backend.Platform; import com.google.common.flogger.backend.Tags; import com.google.common.flogger.backend.TemplateContext; import com.google.common.flogger.parser.MessageParser; import com.google.errorprone.annotations.CheckReturnValue; import java.util.Arrays; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import javax.annotation.Nullable; /** * The base context for a logging statement, which implements the base logging API. * <p> * This class is an implementation of the base {@link LoggingApi} interface and acts as a holder for * any state applied to the log statement during the fluent call sequence. The lifecycle of a * logging context is very short; it is created by a logger, usually in response to a call to the * {@link AbstractLogger#at(Level)} method, and normally lasts only as long as the log statement. * <p> * This class should not be visible to normal users of the logging API and it is only needed when * extending the API to add more functionality. In order to extend the logging API and add methods * to the fluent call chain, the {@code LoggingApi} interface should be extended to add any new * methods, and this class should be extended to implement them. A new logger class will then be * needed to return the extended context. * <p> * Logging contexts are not thread safe. */ @CheckReturnValue public abstract class LogContext< LOGGER extends AbstractLogger<API>, API extends LoggingApi<API>> implements LoggingApi<API>, LogData { /** * The predefined metadata keys used by the default logging API. Backend implementations can use * these to identify metadata added by the core logging API. */ // TODO: Reevaluate this whole strategy before open-sourcing. public static final class Key { private Key() {} /** * The key associated with a {@link Throwable} cause to be associated with the log message. This * value is set by {@link LoggingApi#withCause(Throwable)}. */ public static final MetadataKey<Throwable> LOG_CAUSE = MetadataKey.single("cause", Throwable.class); /** * The key associated with a rate limiting counter for "1-in-N" rate limiting. The value is set * by {@link LoggingApi#every(int)}. */ public static final MetadataKey<Integer> LOG_EVERY_N = MetadataKey.single("ratelimit_count", Integer.class); /** * The key associated with a rate limiting period for "at most once every N" rate limiting. The * value is set by {@link LoggingApi#atMostEvery(int, TimeUnit)}. */ public static final MetadataKey<RateLimitPeriod> LOG_AT_MOST_EVERY = MetadataKey.single("ratelimit_period", RateLimitPeriod.class); /** * The key associated with a {@code Boolean} value used to specify that the log statement must * be emitted. * <p> * Forcing a log statement ensures that the {@code LoggerBackend} is passed the {@code LogData} * for this log statement regardless of the backend's log level or any other filtering or rate * limiting which might normally occur. If a log statement is forced, this key will be set * immediately on creation of the logging context and will be visible to both fluent methods * and post-processing. * <p> * Filtering and rate-limiting methods must check for this value and should treat forced log * statements as not having had any filtering or rate limiting applied. For example, if the * following log statement was forced: * <pre>{@code * logger.atInfo().withCause(e).atMostEvery(1, MINUTES).log("Message..."); * }</pre> * it should behave as if the rate-limiting methods were never called, such as: * <pre>{@code * logger.atInfo().withCause(e).log("Message..."); * }</pre> * As well as no longer including any rate-limiting metadata for the forced log statement, this * also has the effect of never interfering with the rate-limiting of this log statement for * other callers. * <p> * The decision of whether to force a log statement is expected to be made based upon debug * values provded by the logger which come from a scope greater than the log statement itself. * Thus it makes no sense to provide a public method to set this value programmatically for a * log statement. */ public static final MetadataKey<Boolean> WAS_FORCED = MetadataKey.single("forced", Boolean.class); /** * The key associated with any injected metadata (in the form of a {@code Tags} instance. * <p> * If tags are injected, they are added after post-processing if the log site is enabled. Thus * they are no available to the {@code postProcess()} method itself. The rationale is that a * log statement's behavior should only be affected by code at the log site (other than * "forcing" log statements, which is slightly a special case). */ public static final MetadataKey<Tags> TAGS = MetadataKey.single("tags", Tags.class); /** * Key associated with the metadata for specifying additional stack information with a log * statement. */ public static final MetadataKey<StackSize> CONTEXT_STACK_SIZE = MetadataKey.single("stack_size", StackSize.class); } static final class MutableMetadata extends Metadata { /** * The default number of key/value pairs we initially allocate space for when someone adds * metadata to this context. * <p> * Note: As of 10/12 the VM allocates small object arrays very linearly with respect to the * number of elements (an array has a 12 byte header with 4 bytes/element for object * references). The allocation size is always rounded up to the next 8 bytes which means we * can just pick a small value for the initial size and grow from there without too much waste. * <p> * For 4 key/value pairs, we will need 8 elements in the array, which will take up 48 bytes * {@code (12 + (8 * 4) = 44}, which when rounded up is 48. */ private static final int INITIAL_KEY_VALUE_CAPACITY = 4; /** * The array of key/value pairs to hold any metadata the might be added by the logger or any of * the fluent methods on our API. This is an array so it is as space efficient as possible. */ private Object[] keyValuePairs = new Object[2 * INITIAL_KEY_VALUE_CAPACITY]; /** The number of key/value pairs currently stored in the array. */ private int keyValueCount = 0; @Override public int size() { return keyValueCount; } @Override public MetadataKey<?> getKey(int n) { if (n >= keyValueCount) { throw new IndexOutOfBoundsException(); } return (MetadataKey<?>) keyValuePairs[2 * n]; } @Override public Object getValue(int n) { if (n >= keyValueCount) { throw new IndexOutOfBoundsException(); } return keyValuePairs[(2 * n) + 1]; } private int indexOf(MetadataKey<?> key) { for (int index = 0; index < keyValueCount; index++) { if (keyValuePairs[2 * index].equals(key)) { return index; } } return -1; } @Override @Nullable public <T> T findValue(MetadataKey<T> key) { int index = indexOf(key); return index != -1 ? key.cast(keyValuePairs[(2 * index) + 1]) : null; } /** * Adds the key/value pair to the metadata (growing the internal array as necessary). If the * key cannot be repeated, and there is already a value for the key in the metadata, then the * existing value is replaced, otherwise the value is added at the end of the metadata. */ <T> void addValue(MetadataKey<T> key, T value) { if (!key.canRepeat()) { int index = indexOf(key); if (index != -1) { keyValuePairs[(2 * index) + 1] = checkNotNull(value, "metadata value"); return; } } // Check that the array is big enough for one more element. if (2 * (keyValueCount + 1) > keyValuePairs.length) { // Use doubling here (this code should almost never be hit in normal usage and the total // number of items should always stay relatively small. If this resizing algorithm is ever // modified it is vital that the new value is always an even number. keyValuePairs = Arrays.copyOf(keyValuePairs, 2 * keyValuePairs.length); } keyValuePairs[2 * keyValueCount] = checkNotNull(key, "metadata key"); keyValuePairs[(2 * keyValueCount) + 1] = checkNotNull(value, "metadata value"); keyValueCount += 1; } /** Removes all key/value pairs for a given key. */ void removeAllValues(MetadataKey<?> key) { int index = indexOf(key); if (index >= 0) { int dest = 2 * index; int src = dest + 2; while (src < (2 * keyValueCount)) { Object nextKey = keyValuePairs[src]; if (!nextKey.equals(key)) { keyValuePairs[dest] = nextKey; keyValuePairs[dest + 1] = keyValuePairs[src + 1]; dest += 2; } src += 2; } // We know src & dest are +ve and (src > dest), so shifting is safe here. keyValueCount -= (src - dest) >> 1; while (dest < src) { keyValuePairs[dest++] = null; } } } /** Strictly for debugging. */ @Override public String toString() { StringBuilder out = new StringBuilder("Metadata{"); for (int n = 0; n < size(); n++) { out.append(" '").append(getKey(n)).append("': ").append(getValue(n)); } return out.append(" }").toString(); } } /** * A simple token used to identify cases where a single literal value is logged. Note that this * instance must be unique and it is important not to replace this with {@code ""} or any other * value than might be interned and be accessible to code outside this class. */ private static final String LITERAL_VALUE_MESSAGE = new String(); // TODO: Aggressively attempt to reduce the number of fields in this instance. /** The log level of the log statement that this context was created for. */ private final Level level; /** The timestamp of the log statement that this context is associated with. */ private final long timestampNanos; /** Additional metadata for this log statement (added via fluent API methods). */ private MutableMetadata metadata = null; /** The log site information for this log statement (set immediately prior to post-processing). */ private LogSite logSite = null; /** The template context if formatting is required (set only after post-processing). */ private TemplateContext templateContext = null; /** The log arguments (set only after post-processing). */ private Object[] args = null; /** * Creates a logging context with the specified level, and with a timestamp obtained from the * configured logging {@link Platform}. * * @param level the log level for this log statement. * @param isForced whether to force this log statement (see {@link #wasForced()} for details). */ protected LogContext(Level level, boolean isForced) { this(level, isForced, Platform.getCurrentTimeNanos()); } /** * Creates a logging context with the specified level and timestamp. This constructor is provided * only for testing when timestamps need to be injected. In general, subclasses would only need * to call this constructor when testing additional API methods which require timestamps (e.g. * additional rate limiting functionality). Most unit tests for logger subclasses should not * test the value of the timestamp at all, since this is already well tested elsewhere. * * @param level the log level for this log statement. * @param isForced whether to force this log statement (see {@link #wasForced()} for details). * @param timestampNanos the nanosecond timestamp for this log statement. */ protected LogContext(Level level, boolean isForced, long timestampNanos) { this.level = checkNotNull(level, "level"); this.timestampNanos = timestampNanos; if (isForced) { addMetadata(Key.WAS_FORCED, Boolean.TRUE); } } /** * Returns the current API (which is just the concrete sub-type of this instance). This is * returned by fluent methods to continue the fluent call chain. */ protected abstract API api(); // ---- Logging Context Constants ---- /** * Returns the logger which created this context. This is implemented as an abstract method to * save a field in every context. */ protected abstract LOGGER getLogger(); /** * Returns the constant no-op logging API, which can be returned by fluent methods in extended * logging contexts to efficiently disable logging. This is implemented as an abstract method to * save a field in every context. */ protected abstract API noOp(); /** * Returns the message parser used for all log statements made through this logger. */ protected abstract MessageParser getMessageParser(); // ---- LogData API ---- @Override public final Level getLevel() { return level; } @Deprecated @Override public final long getTimestampMicros() { return NANOSECONDS.toMicros(timestampNanos); } @Override public final long getTimestampNanos() { return timestampNanos; } @Override public final String getLoggerName() { return getLogger().getBackend().getLoggerName(); } @Override public final LogSite getLogSite() { if (logSite == null) { throw new IllegalStateException("cannot request log site information prior to postProcess()"); } return logSite; } @Override public final TemplateContext getTemplateContext() { return templateContext; } @Override public final Object[] getArguments() { if (templateContext == null) { throw new IllegalStateException("cannot get arguments unless a template context exists"); } return args; } @Override public final Object getLiteralArgument() { if (templateContext != null) { throw new IllegalStateException("cannot get literal argument if a template context exists"); } return args[0]; } @Override public final boolean wasForced() { // Check explicit TRUE here because findValue() can return null (which would fail unboxing). return metadata != null && Boolean.TRUE.equals(metadata.findValue(Key.WAS_FORCED)); } /** * Returns any additional metadata for this log statement. * <p> * When called outside of the logging backend, this method may return different values * at different times (ie, it may initially return a shared static "empty" metadata object and * later return a different implementation). As such it is not safe to cache the instance * returned by this method or to attempt to cast it to any particular implementation. */ @Override public final Metadata getMetadata() { return metadata != null ? metadata : Metadata.empty(); } // ---- Mutable Metadata ---- /** * Adds the given key/value pair to this logging context. If the key cannot be repeated, and * there is already a value for the key in the metadata, then the existing value is replaced, * otherwise the value is added at the end of the metadata. * * @param key the metadata key (see {@link LogData}). * @param value the metadata value. */ protected final <T> void addMetadata(MetadataKey<T> key, T value) { if (metadata == null) { metadata = new MutableMetadata(); } metadata.addValue(key, value); } /** * Removes all key/value pairs with the specified key. Note that this method does not resize any * underlying backing arrays or other storage as logging contexts are expected to be short lived. * * @param key the metadata key (see {@link LogData}). */ protected final void removeMetadata(MetadataKey<?> key) { if (metadata != null) { metadata.removeAllValues(key); } } // ---- Post processing ---- /** * A callback that can be overridden to implement post processing of logging context prior to * invoking the backend. * * <p>If a fluent method invoked during the log statement requires access to persistent state * during post-processing, {@code logSiteKey} can be used to look it up. If this log statement * cannot be identified uniquely, then {@code logSiteKey} will be {@code null}, and this method * must behave exactly as if the corresponding fluent method had not been invoked. * * <p>Thus on a system in which log site information is unavailable: * * <pre>{@code logger.atInfo().every(100).withCause(e).log("Some message"); }</pre> * * should behave exactly the same as: * * <pre>{@code logger.atInfo().withCause(e).log("Some message"); }</pre> * * <p>Implementations of this method must always call {@code super.postProcess()} first with the * given log site key, such as: * * <pre>{@code protected boolean postProcess(@Nullable LogSiteKey logSiteKey) { * if (!super.postProcess(logSiteKey)) { * return false; * } * ... * return shouldLog; * }}</pre> * * <p>If a method in the logging chain can determine that logging should definitely be disabled * then it is generally better to return the NoOp API implementation at that point rather than * waiting until here to cancel the operation, although care must be taken to check whether the * log statement has been "forced" or not. * * * <p>The default implementation of this method enforces the rate limits as set by {@link * #every(int)} or {@link #atMostEvery(int, TimeUnit)}. * * @param logSiteKey used to lookup persistent, per log statement, state. * @return true if the logging backend should be invoked to output the current log statement. */ protected boolean postProcess(@Nullable LogSiteKey logSiteKey) { if (metadata != null && logSiteKey != null) { // This code still gets reached if a "cause" was set, but as that's far more likely than any // other metadata that might suppress logging, it's not worth any more "early out" checks. // If we have a cause, we're almost certainly logging it, and that's expensive anyway. Integer rateLimitCount = metadata.findValue(Key.LOG_EVERY_N); RateLimitPeriod rateLimitPeriod = metadata.findValue(Key.LOG_AT_MOST_EVERY); LogSiteStats stats = LogSiteStats.getStatsForKey(logSiteKey); if (rateLimitCount != null && !stats.incrementAndCheckInvocationCount(rateLimitCount)) { return false; } if (rateLimitPeriod != null && !stats.checkLastTimestamp(getTimestampNanos(), rateLimitPeriod)) { return false; } } // This does not affect whether logging will occur, only what additional data it contains. StackSize stackSize = getMetadata().findValue(Key.CONTEXT_STACK_SIZE); if (stackSize != null) { // we add this information to the stack trace exception so it doesn't need to go here. removeMetadata(Key.CONTEXT_STACK_SIZE); LogSiteStackTrace context = new LogSiteStackTrace( getMetadata().findValue(LogContext.Key.LOG_CAUSE), stackSize, getStackForCallerOf(LogContext.class, new Throwable(), stackSize.getMaxDepth())); // The "cause" is a unique metadata key, we must replace any existing value. addMetadata(LogContext.Key.LOG_CAUSE, context); } // By default, no restrictions apply so we should log. return true; } /** * Pre-processes log metadata and determines whether we should make the pending logging call. * <p> * Note that this call is made inside each of the individual log methods (rather than in * {@code logImpl()}) because it is better to decide whether we are actually going to do the * logging before we pay the price of creating a varargs array and doing things like auto-boxing * of arguments. */ private boolean shouldLog() { // The log site may have already been injected via "withInjectedLogSite()". if (logSite == null) { // From the point at which we call inferLogSite() we can skip 1 additional method (the // shouldLog() method itself) when looking up the stack to find the log() method. logSite = checkNotNull(Platform.getCallerFinder().findLogSite(LogContext.class, 1), "logger backend must not return a null LogSite"); } LogSiteKey logSiteKey = null; if (logSite != LogSite.INVALID) { logSiteKey = logSite; } if (!postProcess(logSiteKey)) { return false; } // Right at the end of post processing add any tags injected by the platform. Alternately this // could be done in logImpl(), but it would have the same effect. This should be the last piece // of metadata added to a LogData instance (but users are not allowed to rely on that). Tags tags = Platform.getInjectedTags(); if (!tags.isEmpty()) { addMetadata(Key.TAGS, tags); } return true; } /** * Make the backend logging call. This is the point at which we have paid the price of creating a * varargs array and doing any necessary auto-boxing. */ @SuppressWarnings("ReferenceEquality") private void logImpl(String message, Object... args) { this.args = args; // Evaluate any (rare) LazyArg instances early. This may throw exceptions from user code, but // it seems reasonable to propagate them in this case (they would have been thrown if the // argument was evaluated at the call site anyway). for (int n = 0; n < args.length; n++) { if (args[n] instanceof LazyArg) { args[n] = ((LazyArg<?>) args[n]).evaluate(); } } // Using "!=" is fast and sufficient here because the only real case this should be skipping // is when we called log(String) or log() which got converted to "log("%s", String) using this // constant. if (message != LITERAL_VALUE_MESSAGE) { this.templateContext = new TemplateContext(getMessageParser(), message); } getLogger().write(this); } // ---- Log site injection (used by pre-processors and special cases) ---- @Override public final API withInjectedLogSite(LogSite logSite) { // First call wins (since auto-injection will typically target the log() method at the end of // the chain and might not check for previous explicit injection). if (this.logSite == null) { this.logSite = checkNotNull(logSite, "log site"); } return api(); } @SuppressWarnings("deprecation") @Override public final API withInjectedLogSite( String internalClassName, String methodName, int encodedLineNumber, @Nullable String sourceFileName) { return withInjectedLogSite( LogSite.injectedLogSite(internalClassName, methodName, encodedLineNumber, sourceFileName)); } // ---- Public logging API ---- @Override public final boolean isEnabled() { // We can't guarantee that all logger implementations will return instances of this class // _only_ when logging is enabled, so if would be potentially unsafe to just return true here. // It's not worth caching this result in the instance because calls to this method should be // rare and they are only going to be made once per instance anyway. return wasForced() || getLogger().isLoggable(level); } @Override public final API withCause(Throwable cause) { if (cause != null) { addMetadata(Key.LOG_CAUSE, cause); } return api(); } @Override public API withStackTrace(StackSize size) { if (checkNotNull(size, "stack size") != StackSize.NONE) { addMetadata(Key.CONTEXT_STACK_SIZE, size); } return api(); } @Override public final API every(int n) { // See wasForced() for discussion as to why this occurs before argument checking. if (wasForced()) { return api(); } if (n <= 0) { throw new IllegalArgumentException("rate limit count must be positive"); } // 1-in-1 rate limiting is a no-op. if (n > 1) { addMetadata(Key.LOG_EVERY_N, n); } return api(); } @Override public final API atMostEvery(int n, TimeUnit unit) { // See wasForced() for discussion as to why this occurs before argument checking. if (wasForced()) { return api(); } if (n < 0) { throw new IllegalArgumentException("rate limit period cannot be negative"); } // Rate limiting with a zero length period is a no-op, but if the time unit is nanoseconds then // the value is rounded up inside the rate limit object. if (n > 0) { addMetadata(Key.LOG_AT_MOST_EVERY, LogSiteStats.newRateLimitPeriod(n, unit)); } return api(); } /* * Note that while all log statements look almost identical to each other, it is vital that we * keep the 'shouldLog()' call outside of the call to 'logImpl()' so we can decide whether or not * to abort logging before we do any varargs creation. */ @Override public final void log() { if (shouldLog()) logImpl(LITERAL_VALUE_MESSAGE, ""); } @Override public final void log(String msg) { if (shouldLog()) logImpl(LITERAL_VALUE_MESSAGE, msg); } @Override public final void log(String message, @Nullable Object p1) { if (shouldLog()) logImpl(message, p1); } @Override public final void log(String message, @Nullable Object p1, @Nullable Object p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log( String message, @Nullable Object p1, @Nullable Object p2, @Nullable Object p3) { if (shouldLog()) logImpl(message, p1, p2, p3); } @Override public final void log( String message, @Nullable Object p1, @Nullable Object p2, @Nullable Object p3, @Nullable Object p4) { if (shouldLog()) logImpl(message, p1, p2, p3, p4); } @Override public final void log( String msg, @Nullable Object p1, @Nullable Object p2, @Nullable Object p3, @Nullable Object p4, @Nullable Object p5) { if (shouldLog()) logImpl(msg, p1, p2, p3, p4, p5); } @Override public final void log( String msg, @Nullable Object p1, @Nullable Object p2, @Nullable Object p3, @Nullable Object p4, @Nullable Object p5, @Nullable Object p6) { if (shouldLog()) logImpl(msg, p1, p2, p3, p4, p5, p6); } @Override public final void log( String msg, @Nullable Object p1, @Nullable Object p2, @Nullable Object p3, @Nullable Object p4, @Nullable Object p5, @Nullable Object p6, @Nullable Object p7) { if (shouldLog()) logImpl(msg, p1, p2, p3, p4, p5, p6, p7); } @Override public final void log( String msg, @Nullable Object p1, @Nullable Object p2, @Nullable Object p3, @Nullable Object p4, @Nullable Object p5, @Nullable Object p6, @Nullable Object p7, @Nullable Object p8) { if (shouldLog()) logImpl(msg, p1, p2, p3, p4, p5, p6, p7, p8); } @Override public final void log( String msg, @Nullable Object p1, @Nullable Object p2, @Nullable Object p3, @Nullable Object p4, @Nullable Object p5, @Nullable Object p6, @Nullable Object p7, @Nullable Object p8, @Nullable Object p9) { if (shouldLog()) logImpl(msg, p1, p2, p3, p4, p5, p6, p7, p8, p9); } @Override public final void log( String msg, @Nullable Object p1, @Nullable Object p2, @Nullable Object p3, @Nullable Object p4, @Nullable Object p5, @Nullable Object p6, @Nullable Object p7, @Nullable Object p8, @Nullable Object p9, @Nullable Object p10) { if (shouldLog()) logImpl(msg, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10); } @Override public final void log( String msg, @Nullable Object p1, @Nullable Object p2, @Nullable Object p3, @Nullable Object p4, @Nullable Object p5, @Nullable Object p6, @Nullable Object p7, @Nullable Object p8, @Nullable Object p9, @Nullable Object p10, Object... rest) { if (shouldLog()) { // Manually create a new varargs array and copy the parameters in. Object[] params = new Object[rest.length + 10]; params[0] = p1; params[1] = p2; params[2] = p3; params[3] = p4; params[4] = p5; params[5] = p6; params[6] = p7; params[7] = p8; params[8] = p9; params[9] = p10; System.arraycopy(rest, 0, params, 10, rest.length); logImpl(msg, params); } } @Override public final void log(String message, char p1) { if (shouldLog()) logImpl(message, p1); } @Override public final void log(String message, byte p1) { if (shouldLog()) logImpl(message, p1); } @Override public final void log(String message, short p1) { if (shouldLog()) logImpl(message, p1); } @Override public final void log(String message, int p1) { if (shouldLog()) logImpl(message, p1); } @Override public final void log(String message, long p1) { if (shouldLog()) logImpl(message, p1); } @Override public final void log(String message, @Nullable Object p1, boolean p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, @Nullable Object p1, char p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, @Nullable Object p1, byte p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, @Nullable Object p1, short p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, @Nullable Object p1, int p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, @Nullable Object p1, long p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, @Nullable Object p1, float p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, @Nullable Object p1, double p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, boolean p1, @Nullable Object p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, char p1, @Nullable Object p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, byte p1, @Nullable Object p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, short p1, @Nullable Object p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, int p1, @Nullable Object p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, long p1, @Nullable Object p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, float p1, @Nullable Object p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, double p1, @Nullable Object p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, boolean p1, boolean p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, char p1, boolean p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, byte p1, boolean p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, short p1, boolean p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, int p1, boolean p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, long p1, boolean p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, float p1, boolean p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, double p1, boolean p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, boolean p1, char p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, char p1, char p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, byte p1, char p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, short p1, char p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, int p1, char p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, long p1, char p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, float p1, char p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, double p1, char p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, boolean p1, byte p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, char p1, byte p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, byte p1, byte p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, short p1, byte p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, int p1, byte p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, long p1, byte p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, float p1, byte p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, double p1, byte p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, boolean p1, short p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, char p1, short p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, byte p1, short p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, short p1, short p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, int p1, short p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, long p1, short p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, float p1, short p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, double p1, short p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, boolean p1, int p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, char p1, int p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, byte p1, int p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, short p1, int p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, int p1, int p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, long p1, int p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, float p1, int p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, double p1, int p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, boolean p1, long p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, char p1, long p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, byte p1, long p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, short p1, long p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, int p1, long p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, long p1, long p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, float p1, long p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, double p1, long p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, boolean p1, float p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, char p1, float p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, byte p1, float p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, short p1, float p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, int p1, float p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, long p1, float p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, float p1, float p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, double p1, float p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, boolean p1, double p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, char p1, double p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, byte p1, double p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, short p1, double p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, int p1, double p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, long p1, double p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, float p1, double p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void log(String message, double p1, double p2) { if (shouldLog()) logImpl(message, p1, p2); } @Override public final void logVarargs(String message, Object[] params) { if (shouldLog()) { // Copy the varargs array (because we didn't create it and this is quite a rare case). logImpl(message, Arrays.copyOf(params, params.length)); } } }
Attempting to clarify docs around how the special "literal message" string marker is used. RELNOTES=N/A ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=237815318
api/src/main/java/com/google/common/flogger/LogContext.java
Attempting to clarify docs around how the special "literal message" string marker is used.
Java
apache-2.0
77abda4ec0d082f94f0c92bac028baba7d181fc3
0
libris/librisxl,libris/librisxl,libris/librisxl
package whelk.export.servlet; import org.codehaus.jackson.map.ObjectMapper; import whelk.Document; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import java.io.IOException; import java.sql.*; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.*; public class ListRecordTrees { // This class is used as a crutch to simulate "pass by reference"-mechanics. The point of this is that (a pointer to) // an instance of ModificationTimes is passed around in the tree building process, being _updated_ (which a ZonedDateTime // cannot be) with each documents created-timestamp. private static class ModificationTimes { public ZonedDateTime earliestModification; public ZonedDateTime latestModification; } public static void respond(HttpServletRequest request, HttpServletResponse response, ZonedDateTime fromDateTime, ZonedDateTime untilDateTime, SetSpec setSpec, String requestedFormat) throws IOException, XMLStreamException, SQLException { String tableName = OaiPmh.configuration.getProperty("sqlMaintable"); // First connection, used for iterating over the requested root (holding) nodes. ID only try (Connection firstConn = DataBase.getConnection()) { // Construct the query String selectSQL = "SELECT id, modified FROM " + tableName + " WHERE TRUE "; if (setSpec.getRootSet() != null) selectSQL += " AND manifest->>'collection' = ?"; if (setSpec.getSubset() != null) selectSQL += " AND data @> '{\"@graph\":[{\"heldBy\": {\"@type\": \"Organization\", \"notation\": \"" + Helpers.scrubSQL(setSpec.getSubset()) + "\"}}]}' "; PreparedStatement preparedStatement = firstConn.prepareStatement(selectSQL); // Assign parameters if (setSpec.getRootSet() != null) preparedStatement.setString(1, setSpec.getRootSet()); ResultSet resultSet = preparedStatement.executeQuery(); // Build the xml response feed XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance(); xmlOutputFactory.setProperty("escapeCharacters", false); // Inline xml must be left untouched. XMLStreamWriter writer = null; boolean xmlIntroWritten = false; while (resultSet.next()) { List<String> nodeDatas = new LinkedList<String>(); HashSet<String> visitedIDs = new HashSet<String>(); String id = resultSet.getString("id"); ZonedDateTime modified = ZonedDateTime.ofInstant(resultSet.getTimestamp("modified").toInstant(), ZoneOffset.UTC); ModificationTimes modificationTimes = new ModificationTimes(); modificationTimes.earliestModification = modified; modificationTimes.latestModification = modified; // Use a second db connection for the embedding process try (Connection secondConn = DataBase.getConnection()) { addNodeAndSubnodesToTree(id, visitedIDs, secondConn, nodeDatas, modificationTimes); } if (fromDateTime != null && fromDateTime.compareTo(modificationTimes.latestModification) > 0) continue; if (untilDateTime != null && untilDateTime.compareTo(modificationTimes.earliestModification) < 0) continue; // Do not begin writing to the response until at least one record has passed all checks. We might still need to // send a "noRecordsMatch". if (!xmlIntroWritten) { xmlIntroWritten = true; writer = xmlOutputFactory.createXMLStreamWriter(response.getOutputStream()); ResponseCommon.writeOaiPmhHeader(writer, request, true); writer.writeStartElement("ListRecordTrees"); writer.writeStartElement("records"); } Document mergedDocument = mergeDocument(id, nodeDatas); writer.writeStartElement("record"); writer.writeStartElement("metadata"); ResponseCommon.writeConvertedDocument(writer, requestedFormat, mergedDocument); writer.writeEndElement(); // metadata writer.writeEndElement(); // record } if (xmlIntroWritten) { writer.writeEndElement(); // records writer.writeEndElement(); // ListRecordTrees ResponseCommon.writeOaiPmhClose(writer, request); } else { ResponseCommon.sendOaiPmhError(OaiPmh.OAIPMH_ERROR_NO_RECORDS_MATCH, "", request, response); } } } private static void addNodeAndSubnodesToTree(String id, Set<String> visitedIDs, Connection connection, List<String> nodeDatas, ModificationTimes modificationTimes) throws SQLException, IOException { if (visitedIDs.contains(id)) return; String tableName = OaiPmh.configuration.getProperty("sqlMaintable"); String selectSQL = "SELECT id, data, modified FROM " + tableName + " WHERE id = ?"; PreparedStatement preparedStatement = connection.prepareStatement(selectSQL); preparedStatement.setString(1, id); ResultSet resultSet = preparedStatement.executeQuery(); if (!resultSet.next()) return; ObjectMapper mapper = new ObjectMapper(); String jsonBlob = resultSet.getString("data"); nodeDatas.add(jsonBlob); visitedIDs.add(id); ZonedDateTime modified = ZonedDateTime.ofInstant(resultSet.getTimestamp("modified").toInstant(), ZoneOffset.UTC); if (modified.compareTo(modificationTimes.earliestModification) < 0) modificationTimes.earliestModification = modified; if (modified.compareTo(modificationTimes.latestModification) > 0) modificationTimes.latestModification = modified; Map map = mapper.readValue(jsonBlob, HashMap.class); parseMap(map, visitedIDs, connection, nodeDatas, modificationTimes); } private static void parseMap(Map map, Set<String> visitedIDs, Connection connection, List<String> nodeDatas, ModificationTimes modificationTimes) throws SQLException, IOException { for (Object key : map.keySet()) { Object value = map.get(key); if (value instanceof Map) parseMap( (Map) value, visitedIDs, connection, nodeDatas, modificationTimes ); else if (value instanceof List) parseList( (List) value, visitedIDs, connection, nodeDatas, modificationTimes ); else parsePotentialId( key, value, visitedIDs, connection, nodeDatas, modificationTimes ); } } private static void parseList(List list, Set<String> visitedIDs, Connection connection, List<String> nodeDatas, ModificationTimes modificationTimes) throws SQLException, IOException { for (Object item : list) { if (item instanceof Map) parseMap( (Map) item, visitedIDs, connection, nodeDatas, modificationTimes ); else if (item instanceof List) parseList( (List) item, visitedIDs, connection, nodeDatas, modificationTimes ); } } private static void parsePotentialId(Object key, Object value, Set<String> visitedIDs, Connection connection, List<String> nodeDatas, ModificationTimes modificationTimes) throws SQLException, IOException { if ( !(key instanceof String) || !(value instanceof String)) return; if ( ! "@id".equals(key) ) return; String potentialID = (String) value; if ( !potentialID.startsWith("http") ) return; potentialID = potentialID.replace("resource/", ""); String sql = "SELECT id FROM lddb__identifiers WHERE identifier = ?"; PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, potentialID); ResultSet resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { String id = resultSet.getString("id"); addNodeAndSubnodesToTree( id, visitedIDs, connection, nodeDatas, modificationTimes ); } } private static Document mergeDocument(String id, List<String> nodeDatas) throws IOException { ObjectMapper mapper = new ObjectMapper(); // One element in the list is guaranteed. String rootData = nodeDatas.get(0); Map rootMap = mapper.readValue(rootData, HashMap.class); List mergedGraph = (List) rootMap.get("@graph"); for (int i = 1; i < nodeDatas.size(); ++i) { String nodeData = nodeDatas.get(i); Map nodeRootMap = mapper.readValue(nodeData, HashMap.class); List nodeGraph = (List) nodeRootMap.get("@graph"); mergedGraph.addAll(nodeGraph); } rootMap.replace("@graph", mergedGraph); return new Document(id, rootMap); } }
oaipmh/src/main/java/whelk/export/servlet/ListRecordTrees.java
package whelk.export.servlet; import org.codehaus.jackson.map.ObjectMapper; import whelk.Document; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import java.io.IOException; import java.sql.*; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.*; public class ListRecordTrees { // This class is used as a crutch to simulate "pass by reference"-mechanics. The point of this is that (a pointer to) // an instance of ModificationTimes is passed around in the tree building process, being _updated_ (which a ZonedDateTime // cannot be) with each documents created-timestamp. private static class ModificationTimes { public ZonedDateTime earliestModification; public ZonedDateTime latestModification; } public static void respond(HttpServletRequest request, HttpServletResponse response, ZonedDateTime fromDateTime, ZonedDateTime untilDateTime, SetSpec setSpec, String requestedFormat) throws IOException, XMLStreamException, SQLException { String tableName = OaiPmh.configuration.getProperty("sqlMaintable"); // First connection, used for iterating over the requested root (holding) nodes. ID only try (Connection firstConn = DataBase.getConnection()) { // Construct the query String selectSQL = "SELECT id, modified FROM " + tableName + " WHERE TRUE "; if (setSpec.getRootSet() != null) selectSQL += " AND manifest->>'collection' = ?"; if (setSpec.getSubset() != null) selectSQL += " AND data @> '{\"@graph\":[{\"heldBy\": {\"@type\": \"Organization\", \"notation\": \"" + Helpers.scrubSQL(setSpec.getSubset()) + "\"}}]}' "; PreparedStatement preparedStatement = firstConn.prepareStatement(selectSQL); // Assign parameters if (setSpec.getRootSet() != null) preparedStatement.setString(1, setSpec.getRootSet()); ResultSet resultSet = preparedStatement.executeQuery(); // Build the xml response feed XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance(); xmlOutputFactory.setProperty("escapeCharacters", false); // Inline xml must be left untouched. XMLStreamWriter writer = xmlOutputFactory.createXMLStreamWriter(response.getOutputStream()); ResponseCommon.writeOaiPmhHeader(writer, request, true); writer.writeStartElement("ListRecordTrees"); writer.writeStartElement("records"); while (resultSet.next()) { List<String> nodeDatas = new LinkedList<String>(); HashSet<String> visitedIDs = new HashSet<String>(); String id = resultSet.getString("id"); ZonedDateTime modified = ZonedDateTime.ofInstant(resultSet.getTimestamp("modified").toInstant(), ZoneOffset.UTC); ModificationTimes modificationTimes = new ModificationTimes(); modificationTimes.earliestModification = modified; modificationTimes.latestModification = modified; // Use a second db connection for the embedding process try (Connection secondConn = DataBase.getConnection()) { addNodeAndSubnodesToTree(id, visitedIDs, secondConn, nodeDatas, modificationTimes); } //System.out.println("Id: " + id + " has modification window: " + modificationTimes.earliestModification + " -> " + modificationTimes.latestModification); if (fromDateTime != null && fromDateTime.compareTo(modificationTimes.latestModification) > 0) continue; if (untilDateTime != null && untilDateTime.compareTo(modificationTimes.earliestModification) < 0) continue; Document mergedDocument = mergeDocument(id, nodeDatas); writer.writeStartElement("record"); writer.writeStartElement("metadata"); ResponseCommon.writeConvertedDocument(writer, requestedFormat, mergedDocument); writer.writeEndElement(); // metadata writer.writeEndElement(); // record } writer.writeEndElement(); // records writer.writeEndElement(); // ListRecordTrees ResponseCommon.writeOaiPmhClose(writer, request); } } private static void addNodeAndSubnodesToTree(String id, Set<String> visitedIDs, Connection connection, List<String> nodeDatas, ModificationTimes modificationTimes) throws SQLException, IOException { if (visitedIDs.contains(id)) return; String tableName = OaiPmh.configuration.getProperty("sqlMaintable"); String selectSQL = "SELECT id, data, modified FROM " + tableName + " WHERE id = ?"; PreparedStatement preparedStatement = connection.prepareStatement(selectSQL); preparedStatement.setString(1, id); ResultSet resultSet = preparedStatement.executeQuery(); if (!resultSet.next()) return; ObjectMapper mapper = new ObjectMapper(); String jsonBlob = resultSet.getString("data"); nodeDatas.add(jsonBlob); visitedIDs.add(id); ZonedDateTime modified = ZonedDateTime.ofInstant(resultSet.getTimestamp("modified").toInstant(), ZoneOffset.UTC); if (modified.compareTo(modificationTimes.earliestModification) < 0) modificationTimes.earliestModification = modified; if (modified.compareTo(modificationTimes.latestModification) > 0) modificationTimes.latestModification = modified; Map map = mapper.readValue(jsonBlob, HashMap.class); parseMap(map, visitedIDs, connection, nodeDatas, modificationTimes); } private static void parseMap(Map map, Set<String> visitedIDs, Connection connection, List<String> nodeDatas, ModificationTimes modificationTimes) throws SQLException, IOException { for (Object key : map.keySet()) { Object value = map.get(key); if (value instanceof Map) parseMap( (Map) value, visitedIDs, connection, nodeDatas, modificationTimes ); else if (value instanceof List) parseList( (List) value, visitedIDs, connection, nodeDatas, modificationTimes ); else parsePotentialId( key, value, visitedIDs, connection, nodeDatas, modificationTimes ); } } private static void parseList(List list, Set<String> visitedIDs, Connection connection, List<String> nodeDatas, ModificationTimes modificationTimes) throws SQLException, IOException { for (Object item : list) { if (item instanceof Map) parseMap( (Map) item, visitedIDs, connection, nodeDatas, modificationTimes ); else if (item instanceof List) parseList( (List) item, visitedIDs, connection, nodeDatas, modificationTimes ); } } private static void parsePotentialId(Object key, Object value, Set<String> visitedIDs, Connection connection, List<String> nodeDatas, ModificationTimes modificationTimes) throws SQLException, IOException { if ( !(key instanceof String) || !(value instanceof String)) return; if ( ! "@id".equals(key) ) return; String potentialID = (String) value; if ( !potentialID.startsWith("http") ) return; potentialID = potentialID.replace("resource/", ""); String sql = "SELECT id FROM lddb__identifiers WHERE identifier = ?"; PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, potentialID); ResultSet resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { String id = resultSet.getString("id"); addNodeAndSubnodesToTree( id, visitedIDs, connection, nodeDatas, modificationTimes ); } } private static Document mergeDocument(String id, List<String> nodeDatas) throws IOException { ObjectMapper mapper = new ObjectMapper(); // One element in the list is guaranteed. String rootData = nodeDatas.get(0); Map rootMap = mapper.readValue(rootData, HashMap.class); List mergedGraph = (List) rootMap.get("@graph"); for (int i = 1; i < nodeDatas.size(); ++i) { String nodeData = nodeDatas.get(i); Map nodeRootMap = mapper.readValue(nodeData, HashMap.class); List nodeGraph = (List) nodeRootMap.get("@graph"); mergedGraph.addAll(nodeGraph); } rootMap.replace("@graph", mergedGraph); return new Document(id, rootMap); } }
Correctly error out on noRecordsMatch instead of returning an empty list, when requesting expanded records.
oaipmh/src/main/java/whelk/export/servlet/ListRecordTrees.java
Correctly error out on noRecordsMatch instead of returning an empty list, when requesting expanded records.
Java
apache-2.0
7df44e41bcfcf0554dd1789e4979d07e537662ad
0
kickstarter/android-oss,kickstarter/android-oss,kickstarter/android-oss,kickstarter/android-oss
package com.kickstarter.presenters; import android.content.Context; import android.os.Bundle; import android.util.Pair; import com.kickstarter.KSApplication; import com.kickstarter.libs.CurrentUser; import com.kickstarter.libs.Presenter; import com.kickstarter.libs.RxUtils; import com.kickstarter.models.Project; import com.kickstarter.models.User; import com.kickstarter.services.ApiClient; import com.kickstarter.ui.activities.ProjectActivity; import com.kickstarter.ui.adapters.ProjectAdapter; import javax.inject.Inject; import rx.Observable; import rx.android.schedulers.AndroidSchedulers; import rx.subjects.PublishSubject; public class ProjectPresenter extends Presenter<ProjectActivity> implements ProjectAdapter.Delegate { @Inject ApiClient client; @Inject CurrentUser currentUser; private final PublishSubject<Void> backProjectClick = PublishSubject.create(); private final PublishSubject<Void> blurbClick = PublishSubject.create(); private final PublishSubject<Void> commentsClick = PublishSubject.create(); private final PublishSubject<Void> creatorNameClick = PublishSubject.create(); private final PublishSubject<Void> shareClick = PublishSubject.create(); private final PublishSubject<Void> updatesClick = PublishSubject.create(); private final PublishSubject<Void> loginSuccess = PublishSubject.create(); private final PublishSubject<Void> starClick = PublishSubject.create(); @Override protected void onCreate(final Context context, final Bundle savedInstanceState) { super.onCreate(context, savedInstanceState); ((KSApplication) context.getApplicationContext()).component().inject(this); } public void takeProject(final Project initialProject) { final Observable<User> loggedInUserOnStarClick = RxUtils.takeWhen(currentUser.observable(), starClick) .filter(u -> u != null); final Observable<User> loggedOutUserOnStarClick = RxUtils.takeWhen(currentUser.observable(), starClick) .filter(u -> u == null); final Observable<Project> projectOnUserChangeStar = loggedInUserOnStarClick .switchMap(__ -> toggleProjectStar(initialProject)) .share(); final Observable<Project> starredProjectOnLoginSuccess = loginSuccess .take(1) .switchMap(__ -> starProject(initialProject)) .share(); final Observable<Project> project = client.fetchProject(initialProject) .mergeWith(projectOnUserChangeStar) .mergeWith(starredProjectOnLoginSuccess) .filter(Project::isDisplayable) .share(); final Observable<Pair<ProjectActivity, Project>> viewAndProject = RxUtils.combineLatestPair(viewSubject, project); addSubscription( viewAndProject .observeOn(AndroidSchedulers.mainThread()) .subscribe(vp -> vp.first.show(vp.second)) ); addSubscription( RxUtils.takePairWhen( viewSubject, projectOnUserChangeStar.mergeWith(starredProjectOnLoginSuccess) ) .filter(vp -> vp.second.isStarred()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(vp -> vp.first.showStarPrompt()) ); addSubscription( RxUtils.takeWhen(viewSubject, loggedOutUserOnStarClick) .observeOn(AndroidSchedulers.mainThread()) .subscribe(ProjectActivity::startLoginToutActivity) ); addSubscription(RxUtils.takeWhen(viewAndProject, backProjectClick) .observeOn(AndroidSchedulers.mainThread()) .subscribe(vp -> vp.first.startCheckoutActivity(vp.second))); addSubscription(RxUtils.takeWhen(viewAndProject, shareClick) .observeOn(AndroidSchedulers.mainThread()) .subscribe(vp -> vp.first.startShareIntent(vp.second))); addSubscription(RxUtils.takeWhen(viewAndProject, blurbClick) .observeOn(AndroidSchedulers.mainThread()) .subscribe(vp -> vp.first.showProjectDescription(vp.second))); addSubscription(RxUtils.takeWhen(viewAndProject, commentsClick) .observeOn(AndroidSchedulers.mainThread()) .subscribe(vp -> vp.first.startCommentsActivity(vp.second))); addSubscription(RxUtils.takeWhen(viewAndProject, creatorNameClick) .observeOn(AndroidSchedulers.mainThread()) .subscribe(vp -> vp.first.showCreatorBio(vp.second))); addSubscription(RxUtils.takeWhen(viewAndProject, updatesClick) .observeOn(AndroidSchedulers.mainThread()) .subscribe(vp -> vp.first.showUpdates(vp.second))); } public void takeBackProjectClick() { backProjectClick.onNext(null); } public void takeBlurbClick() { blurbClick.onNext(null); } public void takeCommentsClick() { commentsClick.onNext(null); } public void takeCreatorNameClick(){ creatorNameClick.onNext(null); } public void takeShareClick() { shareClick.onNext(null); } public void takeUpdatesClick() { updatesClick.onNext(null); } public void takeLoginSuccess() { loginSuccess.onNext(null); } public void takeStarClick() { starClick.onNext(null); } public Observable<Project> starProject(final Project project) { return client.starProject(project) .onErrorResumeNext(Observable.empty()); } public Observable<Project> toggleProjectStar(final Project project) { return client.toggleProjectStar(project) .onErrorResumeNext(Observable.empty()); } }
app/src/main/java/com/kickstarter/presenters/ProjectPresenter.java
package com.kickstarter.presenters; import android.content.Context; import android.os.Bundle; import android.util.Pair; import com.kickstarter.KSApplication; import com.kickstarter.libs.CurrentUser; import com.kickstarter.libs.Presenter; import com.kickstarter.libs.RxUtils; import com.kickstarter.models.Project; import com.kickstarter.models.User; import com.kickstarter.services.ApiClient; import com.kickstarter.ui.activities.ProjectActivity; import com.kickstarter.ui.adapters.ProjectAdapter; import com.kickstarter.ui.viewholders.ProjectViewHolder; import javax.inject.Inject; import rx.Observable; import rx.android.schedulers.AndroidSchedulers; import rx.subjects.PublishSubject; public class ProjectPresenter extends Presenter<ProjectActivity> implements ProjectAdapter.Delegate { @Inject ApiClient client; @Inject CurrentUser currentUser; private final PublishSubject<Void> backProjectClick = PublishSubject.create(); private final PublishSubject<Void> blurbClick = PublishSubject.create(); private final PublishSubject<Void> commentsClick = PublishSubject.create(); private final PublishSubject<Void> creatorNameClick = PublishSubject.create(); private final PublishSubject<Void> shareClick = PublishSubject.create(); private final PublishSubject<Void> updatesClick = PublishSubject.create(); private final PublishSubject<Void> loginSuccess = PublishSubject.create(); private final PublishSubject<Void> starClick = PublishSubject.create(); @Override protected void onCreate(final Context context, final Bundle savedInstanceState) { super.onCreate(context, savedInstanceState); ((KSApplication) context.getApplicationContext()).component().inject(this); } public void takeProject(final Project initialProject) { final Observable<User> loggedInUserOnStarClick = RxUtils.takeWhen(currentUser.observable(), starClick) .filter(u -> u != null); final Observable<User> loggedOutUserOnStarClick = RxUtils.takeWhen(currentUser.observable(), starClick) .filter(u -> u == null); final Observable<Project> projectOnUserChangeStar = loggedInUserOnStarClick .switchMap(__ -> toggleProjectStar(initialProject)) .share(); final Observable<Project> starredProjectOnLoginSuccess = loginSuccess .take(1) .switchMap(__ -> starProject(initialProject)) .share(); final Observable<Project> project = client.fetchProject(initialProject) .mergeWith(projectOnUserChangeStar) .mergeWith(starredProjectOnLoginSuccess) .filter(Project::isDisplayable) .share(); final Observable<Pair<ProjectActivity, Project>> viewAndProject = RxUtils.combineLatestPair(viewSubject, project); addSubscription( viewAndProject .observeOn(AndroidSchedulers.mainThread()) .subscribe(vp -> vp.first.show(vp.second)) ); addSubscription( RxUtils.takePairWhen( viewSubject, projectOnUserChangeStar.mergeWith(starredProjectOnLoginSuccess) ) .filter(vp -> vp.second.isStarred()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(vp -> vp.first.showStarPrompt()) ); addSubscription( RxUtils.takeWhen(viewSubject, loggedOutUserOnStarClick) .observeOn(AndroidSchedulers.mainThread()) .subscribe(ProjectActivity::startLoginToutActivity) ); addSubscription(RxUtils.takeWhen(viewAndProject, backProjectClick) .observeOn(AndroidSchedulers.mainThread()) .subscribe(vp -> vp.first.startCheckoutActivity(vp.second))); addSubscription(RxUtils.takeWhen(viewAndProject, shareClick) .observeOn(AndroidSchedulers.mainThread()) .subscribe(vp -> vp.first.startShareIntent(vp.second))); addSubscription(RxUtils.takeWhen(viewAndProject, blurbClick) .observeOn(AndroidSchedulers.mainThread()) .subscribe(vp -> vp.first.showProjectDescription(vp.second))); addSubscription(RxUtils.takeWhen(viewAndProject, commentsClick) .observeOn(AndroidSchedulers.mainThread()) .subscribe(vp -> vp.first.startCommentsActivity(vp.second))); addSubscription(RxUtils.takeWhen(viewAndProject, creatorNameClick) .observeOn(AndroidSchedulers.mainThread()) .subscribe(vp -> vp.first.showCreatorBio(vp.second))); addSubscription(RxUtils.takeWhen(viewAndProject, updatesClick) .observeOn(AndroidSchedulers.mainThread()) .subscribe(vp -> vp.first.showUpdates(vp.second))); } public void takeBackProjectClick() { backProjectClick.onNext(null); } public void takeBlurbClick() { blurbClick.onNext(null); } public void takeCommentsClick() { commentsClick.onNext(null); } public void takeCreatorNameClick(){ creatorNameClick.onNext(null); } public void takeShareClick() { shareClick.onNext(null); } public void takeUpdatesClick() { updatesClick.onNext(null); } public void takeLoginSuccess() { loginSuccess.onNext(null); } public void takeStarClick() { starClick.onNext(null); } public Observable<Project> starProject(final Project project) { return client.starProject(project) .onErrorResumeNext(Observable.empty()); } public Observable<Project> toggleProjectStar(final Project project) { return client.toggleProjectStar(project) .onErrorResumeNext(Observable.empty()); } }
remove unused import
app/src/main/java/com/kickstarter/presenters/ProjectPresenter.java
remove unused import
Java
apache-2.0
e54ebed8ce9eab57139c4084f9c2ac84fd0a88d3
0
px3/SilverWare,RadekKoubsky/SilverWare,RadekKoubsky/SilverWare,SilverThings/SilverWare,SilverThings/SilverWare,px3/SilverWare,SilverThings/SilverWare,RadekKoubsky/SilverWare
/* * -----------------------------------------------------------------------\ * SilverWare *   * Copyright (C) 2010 - 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 io.silverware.microservices.providers.cdi; import io.silverware.microservices.annotations.Microservice; import io.silverware.microservices.annotations.MicroserviceReference; import io.silverware.microservices.util.BootUtil; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.testng.Assert; import org.testng.annotations.Test; import javax.enterprise.event.Observes; import javax.enterprise.inject.Default; import javax.enterprise.inject.spi.BeanManager; import javax.inject.Inject; import javax.inject.Qualifier; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; /** * @author <a href="mailto:[email protected]">Martin Večeřa</a> */ public class CdiMicroserviceProviderQualifiersTest { private static final Logger log = LogManager.getLogger(CdiMicroserviceProviderQualifiersTest.class); private static final Semaphore semaphore = new Semaphore(0); private static String result = ""; @Test public void testQualifiers() throws Exception { final BootUtil bootUtil = new BootUtil(); final Thread platform = bootUtil.getMicroservicePlatform(this.getClass().getPackage().getName()); platform.start(); CdiMicroserviceProviderTestUtil.waitForBeanManager(bootUtil); Assert.assertTrue(semaphore.tryAcquire(1, TimeUnit.MINUTES), "Timed-out while waiting for platform startup."); Assert.assertEquals(result, "normalmockbez"); platform.interrupt(); platform.join(); } @Microservice public static class TestQualifierMicroservice { @Inject @MicroserviceReference @Sharp private QualifierMicro micro1; @Inject @MicroserviceReference @Mock private QualifierMicro micro2; @Inject @MicroserviceReference @Default private QualifierMicro micro3; public void eventObserver(@Observes MicroservicesStartedEvent event) { result += micro1.hello(); result += micro2.hello(); result += micro3.hello(); semaphore.release(); } } public interface QualifierMicro { String hello(); } @Sharp @Microservice public static class QualifierMicroBean implements QualifierMicro { @Override public String hello() { return "normal"; } } @Mock @Microservice public static class MockQualifierMicroBean implements QualifierMicro { @Override public String hello() { return "mock"; } } @Microservice public static class BezMockQualifierMicroBean implements QualifierMicro { @Override public String hello() { return "bez"; } } @Qualifier @Target({ ElementType.TYPE, ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER }) @Retention(RetentionPolicy.RUNTIME) public @interface Mock { } @Qualifier @Target({ ElementType.TYPE, ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER }) @Retention(RetentionPolicy.RUNTIME) public @interface Sharp { } }
cdi-microservice-provider/src/test/java/io/silverware/microservices/providers/cdi/CdiMicroserviceProviderQualifiersTest.java
/* * -----------------------------------------------------------------------\ * SilverWare *   * Copyright (C) 2010 - 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 io.silverware.microservices.providers.cdi; import io.silverware.microservices.annotations.Microservice; import io.silverware.microservices.annotations.MicroserviceReference; import io.silverware.microservices.util.BootUtil; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.testng.Assert; import org.testng.annotations.Test; import javax.enterprise.event.Observes; import javax.enterprise.inject.spi.BeanManager; import javax.inject.Inject; import javax.inject.Qualifier; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; /** * @author <a href="mailto:[email protected]">Martin Večeřa</a> */ public class CdiMicroserviceProviderQualifiersTest { private static final Logger log = LogManager.getLogger(CdiMicroserviceProviderQualifiersTest.class); private static final Semaphore semaphore = new Semaphore(0); private static String result = ""; @Test public void testQualifiers() throws Exception { final BootUtil bootUtil = new BootUtil(); final Thread platform = bootUtil.getMicroservicePlatform(this.getClass().getPackage().getName()); platform.start(); CdiMicroserviceProviderTestUtil.waitForBeanManager(bootUtil); Assert.assertTrue(semaphore.tryAcquire(1, TimeUnit.MINUTES), "Timed-out while waiting for platform startup."); Assert.assertEquals(result, "normalmock"); platform.interrupt(); platform.join(); } @Microservice public static class TestQualifierMicroservice { @Inject @MicroserviceReference @Sharp private QualifierMicro micro1; @Inject @MicroserviceReference @Mock private QualifierMicro micro2; public void eventObserver(@Observes MicroservicesStartedEvent event) { result += micro1.hello(); result += micro2.hello(); semaphore.release(); } } public interface QualifierMicro { String hello(); } @Sharp @Microservice public static class QualifierMicroBean implements QualifierMicro { @Override public String hello() { return "normal"; } } @Mock @Microservice public static class MockQualifierMicroBean implements QualifierMicro { @Override public String hello() { return "mock"; } } @Qualifier @Target({ ElementType.TYPE, ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER }) @Retention(RetentionPolicy.RUNTIME) public @interface Mock { } @Qualifier @Target({ ElementType.TYPE, ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER }) @Retention(RetentionPolicy.RUNTIME) public @interface Sharp { } }
extended cdi qualifiers test
cdi-microservice-provider/src/test/java/io/silverware/microservices/providers/cdi/CdiMicroserviceProviderQualifiersTest.java
extended cdi qualifiers test
Java
apache-2.0
c0d32edf2a49d119b6be9fb1a8b27b14bc143681
0
xiaob/ASimpleCache,qingsong-xu/ASimpleCache,zcwfeng/ASimpleCache,WiiliamChik/ASimpleCache,BraveAction/ASimpleCache,msdgwzhy6/ASimpleCache,GeorgeMe/ASimpleCache,luinnx/ASimpleCache,yangfuhai/ASimpleCache,mingtang1079/ASimpleCache,sdjtu502/ASimpleCache,lypdemo/ASimpleCache,caoyang521/ASimpleCache,liuguangli/ASimpleCache
/** * Copyright (c) 2012-2013, Michael Yang 杨福海 (www.yangfuhai.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.afinal.simplecache; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.RandomAccessFile; import java.io.Serializable; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import org.json.JSONObject; import android.content.Context; /** * @author Michael Yang(www.yangfuhai.com) * update at 2013.08.07 */ public class ACache { public static final int TIME_HOUR = 60 * 60; public static final int TIME_DAY = TIME_HOUR * 24; private static final int MAX_SIZE = 1000 * 1000 * 50; // 50 mb private static final int MAX_COUNT = Integer.MAX_VALUE; //不限制存放数据的数量 private static Map<String, ACache> mInstanceMap = new HashMap<String, ACache>(); private ACacheManager mCache; public static ACache get(Context ctx) { return get(ctx, "ACache"); } public static ACache get(Context ctx,String cacheName) { File f = new File(ctx.getCacheDir(), cacheName); return get(f,MAX_SIZE,MAX_COUNT); } public static ACache get(File cacheDir) { return get(cacheDir,MAX_SIZE,MAX_COUNT); } public static ACache get(Context ctx,long max_zise,int max_count) { File f = new File(ctx.getCacheDir(), "ACache"); return get(f,max_zise,max_count); } public static ACache get(File cacheDir,long max_zise,int max_count) { ACache manager = mInstanceMap.get(cacheDir.getAbsoluteFile() + myPid()); if (manager == null) { manager = new ACache(cacheDir,max_zise,max_count); mInstanceMap.put(cacheDir.getAbsolutePath() + myPid(), manager); } return manager; } private static String myPid() { return "_" + android.os.Process.myPid(); } private ACache(File cacheDir,long max_size,int max_count) { if (!cacheDir.exists() && !cacheDir.mkdirs()) { throw new RuntimeException("can't make dirs in "+cacheDir.getAbsolutePath()); } mCache = new ACacheManager(cacheDir, max_size, max_count); } // ======================================= // ============ String数据 读写 ============== // ======================================= /** * 保存 String数据 到 缓存中 * @param key 保存的key * @param value 保存的String数据 */ public void put(String key, String value) { File file = mCache.newFile(key); BufferedWriter out = null; try { out = new BufferedWriter(new FileWriter(file), 1024); out.write(value); } catch (IOException e) { e.printStackTrace(); } finally { if (out != null) { try { out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } mCache.put(file); } } /** * 保存 String数据 到 缓存中 * @param key 保存的key * @param value 保存的String数据 * @param saveTime 保存的时间,单位:秒 */ public void put(String key, String value, int saveTime) { put(key, Utils.newStringWithDateInfo(saveTime, value)); } /** * 读取 String数据 * @param key * @return String 数据 */ public String getAsString(String key) { File file = mCache.get(key); if (!file.exists()) return null; boolean removeFile = false; BufferedReader in = null; try { in = new BufferedReader(new FileReader(file)); String readString = ""; String currentLine; while ((currentLine = in.readLine()) != null) { readString += currentLine; } if (!Utils.isDue(readString)) { return Utils.clearDateInfo(readString); } else { removeFile = true; return null; } } catch (IOException e) { e.printStackTrace(); return null; } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } if (removeFile) remove(key); } } // ======================================= // ============= JSON 数据 读写 ============== // ======================================= /** * 保存 JSON数据 到 缓存中 * @param key 保存的key * @param value 保存的JSON数据 */ public void put(String key, JSONObject value) { put(key,value.toString()); } /** * 保存 JSON数据 到 缓存中 * @param key 保存的key * @param value 保存的JSON数据 * @param saveTime 保存的时间,单位:秒 */ public void put(String key, JSONObject value, int saveTime) { put(key,value.toString(), saveTime); } /** * 读取JSON数据 * @param key * @return JSON数据 */ public JSONObject getAsJSONObject(String key) { String JSONString = getAsString(key); try { JSONObject obj = new JSONObject(JSONString); return obj; } catch (Exception e) { e.printStackTrace(); return null; } } // ======================================= // ============== byte 数据 读写 ============= // ======================================= /** * 保存 byte数据 到 缓存中 * @param key 保存的key * @param value 保存的数据 */ public void put(String key, byte[] value) { File file = mCache.newFile(key); FileOutputStream out = null; try { out = new FileOutputStream(file); out.write(value); } catch (Exception e) { e.printStackTrace(); } finally { if (out != null) { try { out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } mCache.put(file); } } /** * 保存 byte数据 到 缓存中 * @param key 保存的key * @param value 保存的数据 * @param saveTime 保存的时间,单位:秒 */ public void put(String key,byte[] value, int saveTime) { put(key, Utils.newByteArrayWithDateInfo(saveTime, value)); } /** * 获取 byte 数据 * @param key * @return byte 数据 */ public byte[] getAsBinary(String key) { RandomAccessFile RAFile = null; boolean removeFile = false; try { File file = mCache.get(key); if (!file.exists()) return null; RAFile = new RandomAccessFile(file, "r"); byte[] byteArray = new byte[(int) RAFile.length()]; RAFile.read(byteArray); if (!Utils.isDue(byteArray)) { return Utils.clearDateInfo(byteArray); } else { removeFile = true; return null; } } catch (Exception e) { e.printStackTrace(); return null; } finally { if (RAFile != null) { try { RAFile.close(); } catch (IOException e) { e.printStackTrace(); } } if (removeFile) remove(key); } } // ======================================= // ============= 序列化 数据 读写 =============== // ======================================= /** * 保存 Serializable数据 到 缓存中 * @param key 保存的key * @param value 保存的value */ public void put(String key, Serializable value ) { put(key, value, -1 ); } /** * 保存 Serializable数据到 缓存中 * @param key 保存的key * @param value 保存的value * @param saveTime 保存的时间,单位:秒 */ public void put(String key, Serializable value ,int saveTime) { ByteArrayOutputStream baos = null; ObjectOutputStream oos = null; try { baos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(baos); oos.writeObject(value); byte[] data = baos.toByteArray(); if(saveTime != -1){ put(key, data ,saveTime); }else{ put(key, data); } } catch (Exception e) { e.printStackTrace(); } finally { try { oos.close(); } catch (IOException e) { } } } /** * 读取 Serializable数据 * @param key * @return Serializable 数据 */ public Object getAsObject(String key) { byte[] data = getAsBinary(key); if( data!=null ){ ByteArrayInputStream bais = null; ObjectInputStream ois = null; try { bais = new ByteArrayInputStream(data); ois = new ObjectInputStream(bais); Object reObject = ois.readObject(); return reObject; } catch (Exception e) { e.printStackTrace(); return null; } finally { try { if (bais != null) bais.close(); } catch (IOException e) { e.printStackTrace(); } try { if (ois != null) ois.close(); } catch (IOException e) { e.printStackTrace(); } } } return null; } /** * 获取缓存文件 * @param key * @return value 缓存的文件 */ public File file(String key) { File f = mCache.newFile(key); if (f.exists()) return f; return null; } /** * 移除某个key * @param key * @return 是否移除成功 */ public boolean remove(String key) { return mCache.remove(key); } /** * 清除所有数据 */ public void clear() { mCache.clear(); } /** * @title 缓存管理器 * @author 杨福海(michael) www.yangfuhai.com * @version 1.0 */ public class ACacheManager { private final AtomicLong cacheSize; private final AtomicInteger cacheCount; private final long sizeLimit; private final int countLimit; private final Map<File, Long> lastUsageDates = Collections.synchronizedMap(new HashMap<File, Long>()); protected File cacheDir; private ACacheManager(File cacheDir, long sizeLimit, int countLimit) { this.cacheDir = cacheDir; this.sizeLimit = sizeLimit; this.countLimit = countLimit; cacheSize = new AtomicLong(); cacheCount = new AtomicInteger(); calculateCacheSizeAndCacheCount(); } /** * 计算 cacheSize和cacheCount */ private void calculateCacheSizeAndCacheCount() { new Thread(new Runnable() { @Override public void run() { int size = 0; int count = 0; File[] cachedFiles = cacheDir.listFiles(); if (cachedFiles != null) { for (File cachedFile : cachedFiles) { size += calculateSize(cachedFile); count += 1; lastUsageDates.put(cachedFile,cachedFile.lastModified()); } cacheSize.set(size); cacheCount.set(count); } } }).start(); } private void put(File file) { int curCacheCount = cacheCount.get(); while (curCacheCount + 1 > countLimit) { long freedSize = removeNext(); cacheSize.addAndGet(-freedSize); curCacheCount = cacheCount.addAndGet(-1); } cacheCount.addAndGet(1); long valueSize = calculateSize(file); long curCacheSize = cacheSize.get(); while (curCacheSize + valueSize > sizeLimit) { long freedSize = removeNext(); curCacheSize = cacheSize.addAndGet(-freedSize); } cacheSize.addAndGet(valueSize); Long currentTime = System.currentTimeMillis(); file.setLastModified(currentTime); lastUsageDates.put(file, currentTime); } private File get(String key) { File file = newFile(key); Long currentTime = System.currentTimeMillis(); file.setLastModified(currentTime); lastUsageDates.put(file, currentTime); return file; } private File newFile(String key) { return new File(cacheDir, key.hashCode() + ""); } private boolean remove(String key) { File image = get(key); return image.delete(); } private void clear() { lastUsageDates.clear(); cacheSize.set(0); File[] files = cacheDir.listFiles(); if (files != null) { for (File f : files) { f.delete(); } } } /** * 移除旧的文件 * @return */ private long removeNext() { if (lastUsageDates.isEmpty()) { return 0; } Long oldestUsage = null; File mostLongUsedFile = null; Set<Entry<File, Long>> entries = lastUsageDates.entrySet(); synchronized (lastUsageDates) { for (Entry<File, Long> entry : entries) { if (mostLongUsedFile == null) { mostLongUsedFile = entry.getKey(); oldestUsage = entry.getValue(); } else { Long lastValueUsage = entry.getValue(); if (lastValueUsage < oldestUsage) { oldestUsage = lastValueUsage; mostLongUsedFile = entry.getKey(); } } } } long fileSize = calculateSize(mostLongUsedFile); if (mostLongUsedFile.delete()) { lastUsageDates.remove(mostLongUsedFile); } return fileSize; } private long calculateSize(File file) { return file.length(); } } /** * @title 时间计算工具类 * @author 杨福海(michael) www.yangfuhai.com * @version 1.0 */ private static class Utils { /** * 判断缓存的String数据是否到期 * @param str * @return true:到期了 false:还没有到期 */ private static boolean isDue(String str) { return isDue(str.getBytes()); } /** * 判断缓存的byte数据是否到期 * @param data * @return true:到期了 false:还没有到期 */ private static boolean isDue(byte[] data) { String[] strs = getDateInfoFromDate(data); if (strs != null && strs.length == 2) { String saveTimeStr = strs[0]; while (saveTimeStr.startsWith("0")) { saveTimeStr = saveTimeStr.substring(1,saveTimeStr.length()); } long saveTime = Long.valueOf(saveTimeStr); long deleteAfter = Long.valueOf(strs[1]); if (System.currentTimeMillis() > saveTime + deleteAfter * 1000) { return true; } } return false; } private static String newStringWithDateInfo(int second, String strInfo) { return createDateInfo(second) + strInfo; } private static byte[] newByteArrayWithDateInfo(int second, byte[] data2) { byte[] data1 = createDateInfo(second).getBytes(); byte[] retdata = new byte[data1.length + data2.length]; System.arraycopy(data1, 0, retdata, 0, data1.length); System.arraycopy(data2, 0, retdata, data1.length, data2.length); return retdata; } private static String clearDateInfo(String strInfo) { if (strInfo != null && hasDateInfo(strInfo.getBytes())) { strInfo = strInfo.substring(strInfo.indexOf(mSeparator) + 1,strInfo.length()); } return strInfo; } private static byte[] clearDateInfo(byte[] data) { if (hasDateInfo(data)) { return copyOfRange(data, indexOf(data, mSeparator)+1, data.length); } return data; } private static boolean hasDateInfo(byte[] data) { return data != null && data.length > 15 && data[13] == '-' && indexOf(data, mSeparator) > 14; } private static String[] getDateInfoFromDate(byte[] data) { if (hasDateInfo(data)) { String saveDate = new String(copyOfRange(data, 0, 13)); String deleteAfter = new String(copyOfRange(data, 14, indexOf(data, mSeparator))); return new String[] { saveDate, deleteAfter }; } return null; } private static int indexOf(byte[] data, char c) { for (int i = 0; i < data.length; i++) { if (data[i] == c) { return i; } } return -1; } private static byte[] copyOfRange(byte[] original, int from, int to) { int newLength = to - from; if (newLength < 0) throw new IllegalArgumentException(from + " > " + to); byte[] copy = new byte[newLength]; System.arraycopy(original, from, copy, 0, Math.min(original.length - from, newLength)); return copy; } private static final char mSeparator = ' '; private static String createDateInfo(int second) { String currentTime = System.currentTimeMillis() +""; while(currentTime.length() < 13){ currentTime = "0"+currentTime; } return currentTime + "-" + second + mSeparator; } } }
AsimpleCacheDemo/ASimpleCache/org/afinal/simplecache/ACache.java
/** * Copyright (c) 2012-2013, Michael Yang 杨福海 (www.yangfuhai.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.afinal.simplecache; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.RandomAccessFile; import java.io.Serializable; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.Map.Entry; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import org.json.JSONObject; import android.content.Context; /** * @author michael yang(www.yangfuhai.com) */ public class ACache { private static final int MAX_SIZE = 1000 * 1000 * 30; // 30 mb private static final int MAX_COUNT = 1000 * 100; // 10000 private static Map<String, ACache> instanceMap = new HashMap<String, ACache>(); private ACacheManager mCache; public static ACache get(Context ctx) { File f = new File(ctx.getCacheDir(), "ACache"); return get(f,MAX_SIZE,MAX_COUNT); } public static ACache get(File cacheDir) { return get(cacheDir,MAX_SIZE,MAX_COUNT); } public static ACache get(Context ctx,int max_zise,int max_count) { File f = new File(ctx.getCacheDir(), "ACache"); return get(f,max_zise,max_count); } public static ACache get(File cacheDir,int max_zise,int max_count) { ACache manager = instanceMap.get(cacheDir.getAbsoluteFile() + getPid()); if (manager == null) { manager = new ACache(cacheDir,max_zise,max_count); instanceMap.put(cacheDir.getAbsolutePath() + getPid(), manager); } return manager; } private static String getPid() { return "_" + android.os.Process.myPid(); } private ACache(File cacheDir,int max_size,int max_count) { if (!cacheDir.exists()) { cacheDir.mkdirs(); } mCache = new ACacheManager(cacheDir, max_size, max_count); } // ======================================= // ========== String类型 读写 ========== // ======================================= public void put(String key, String value) { File file = mCache.newFile(key); BufferedWriter out = null; try { out = new BufferedWriter(new FileWriter(file), 1024); out.write(value); } catch (IOException e) { e.printStackTrace(); } finally { if (out != null) { try { out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } mCache.put(file); } } public void put(String key, String value, int saveTime) { put(key, Utils.newStringWithDateInfo(saveTime, value)); } public String getAsString(String key) { File file = mCache.get(key); if (!file.exists()) return null; boolean removeFile = false; BufferedReader in = null; try { in = new BufferedReader(new FileReader(file)); String readString = ""; String currentLine; while ((currentLine = in.readLine()) != null) { readString += currentLine; } if (!Utils.isDue(readString)) { return Utils.clearDateInfo(readString); } else { removeFile = true; return null; } } catch (IOException e) { e.printStackTrace(); return null; } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } if (removeFile) remove(key); } } // ======================================= // ========== JSON 读写 ============ // ======================================= public void put(String key, JSONObject value) { put(key,value.toString()); } public void put(String key, JSONObject value, int saveTime) { put(key,value.toString(), saveTime); } public JSONObject getAsJSONObject(String key) { String JSONString = getAsString(key); try { JSONObject obj = new JSONObject(JSONString); return obj; } catch (Exception e) { e.printStackTrace(); return null; } } // ======================================= // ========== 二进制 读写 ========== // ======================================= public void put(String key, byte[] value) { File file = mCache.newFile(key); FileOutputStream out = null; try { out = new FileOutputStream(file); out.write(value); } catch (Exception e) { e.printStackTrace(); } finally { if (out != null) { try { out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } mCache.put(file); } } public void put(byte[] toWrite, String key, int holdTime) { put(key, Utils.newByteArrayWithDateInfo(holdTime, toWrite)); } public byte[] getAsBinary(String key) { RandomAccessFile RAFile = null; boolean removeFile = false; try { File file = mCache.get(key); if (!file.exists()) return null; RAFile = new RandomAccessFile(file, "r"); byte[] byteArray = new byte[(int) RAFile.length()]; RAFile.read(byteArray); if (!Utils.isDue(byteArray)) { return Utils.clearDateInfo(byteArray); } else { removeFile = true; return null; } } catch (Exception e) { e.printStackTrace(); return null; } finally { if (RAFile != null) { try { RAFile.close(); } catch (IOException e) { e.printStackTrace(); } } if (removeFile) remove(key); } } // ======================================= // ========== 序列化 读写 ========== // ======================================= public void put(String key, Serializable value) { File file = mCache.newFile(key); if (file.exists()) { file.delete(); } FileOutputStream os = null; ObjectOutputStream oos = null; try { os = new FileOutputStream(file); oos = new ObjectOutputStream(os); oos.writeObject(value); } catch (Exception e) { e.printStackTrace(); } finally { try { oos.close(); } catch (IOException e) { } try { os.close(); } catch (IOException e) { } } } public Object getAsObject(String key) { File file = mCache.get(key); if (!file.exists()) return null; InputStream is = null; ObjectInputStream ois = null; try { is = new FileInputStream(file); ois = new ObjectInputStream(is); return ois.readObject(); } catch (Exception e) { e.printStackTrace(); return null; } finally { try { if (is != null) is.close(); } catch (IOException e) { e.printStackTrace(); } try { if (ois != null) ois.close(); } catch (IOException e) { e.printStackTrace(); } } } public File file(String key) { File f = mCache.newFile(key); if (f.exists()) return f; return null; } /** * 移除某个key * * @param key * @return */ public boolean remove(String key) { return mCache.remove(key); } /** * 清除所有数据 */ public void clear() { mCache.clear(); } /** * @title 缓存管理器 * @author 杨福海(michael) www.yangfuhai.com * @version 1.0 */ public class ACacheManager { private final AtomicLong cacheSize; private final AtomicInteger cacheCount; private final int sizeLimit; private final int countLimit; private final Map<File, Long> lastUsageDates = Collections.synchronizedMap(new HashMap<File, Long>()); protected File cacheDir; private ACacheManager(File cacheDir, int sizeLimit, int countLimit) { this.cacheDir = cacheDir; this.sizeLimit = sizeLimit; this.countLimit = countLimit; cacheSize = new AtomicLong(); cacheCount = new AtomicInteger(); calculateCacheSizeAndCacheCount(); } /** * 计算 cacheSize和cacheCount */ private void calculateCacheSizeAndCacheCount() { new Thread(new Runnable() { @Override public void run() { int size = 0; int count = 0; File[] cachedFiles = cacheDir.listFiles(); if (cachedFiles != null) { for (File cachedFile : cachedFiles) { size += calculateSize(cachedFile); count += 1; lastUsageDates.put(cachedFile,cachedFile.lastModified()); } cacheSize.set(size); cacheCount.set(count); } } }).start(); } private void put(File file) { int curCacheCount = cacheCount.get(); while (curCacheCount + 1 > countLimit) { long freedSize = removeNext(); cacheSize.addAndGet(-freedSize); curCacheCount = cacheCount.addAndGet(-1); } cacheCount.addAndGet(1); long valueSize = calculateSize(file); long curCacheSize = cacheSize.get(); while (curCacheSize + valueSize > sizeLimit) { long freedSize = removeNext(); curCacheSize = cacheSize.addAndGet(-freedSize); } cacheSize.addAndGet(valueSize); Long currentTime = System.currentTimeMillis(); file.setLastModified(currentTime); lastUsageDates.put(file, currentTime); } private File get(String key) { File file = newFile(key); Long currentTime = System.currentTimeMillis(); file.setLastModified(currentTime); lastUsageDates.put(file, currentTime); return file; } private File newFile(String key) { return new File(cacheDir, key.hashCode() + ""); } private boolean remove(String key) { File image = get(key); return image.delete(); } private void clear() { lastUsageDates.clear(); cacheSize.set(0); File[] files = cacheDir.listFiles(); if (files != null) { for (File f : files) { f.delete(); } } } /** * 存放在最旧的文件 * @return */ private long removeNext() { if (lastUsageDates.isEmpty()) { return 0; } Long oldestUsage = null; File mostLongUsedFile = null; Set<Entry<File, Long>> entries = lastUsageDates.entrySet(); synchronized (lastUsageDates) { for (Entry<File, Long> entry : entries) { if (mostLongUsedFile == null) { mostLongUsedFile = entry.getKey(); oldestUsage = entry.getValue(); } else { Long lastValueUsage = entry.getValue(); if (lastValueUsage < oldestUsage) { oldestUsage = lastValueUsage; mostLongUsedFile = entry.getKey(); } } } } long fileSize = calculateSize(mostLongUsedFile); if (mostLongUsedFile.delete()) { lastUsageDates.remove(mostLongUsedFile); } return fileSize; } private long calculateSize(File file) { return file.length(); } } /** * @title 时间计算工具类 * @author 杨福海(michael) www.yangfuhai.com * @version 1.0 */ private static class Utils { /** * 是否到期 * * @param str * @return */ private static boolean isDue(String str) { return isDue(str.getBytes()); } /** * 是否到期 * * @param str * @return */ private static boolean isDue(byte[] data) { String[] strs = getDateInfoFromDate(data); if (strs != null && strs.length == 2) { long saveTime = Long.valueOf(strs[0]); long deleteAfter = Long.valueOf(strs[1]); if (System.currentTimeMillis() > saveTime + deleteAfter * 1000) { return true; } } return false; } private static String newStringWithDateInfo(int second, String strInfo) { return createDateInfo(second) + strInfo; } private static byte[] newByteArrayWithDateInfo(int second, byte[] data2) { byte[] data1 = createDateInfo(second).getBytes(); byte[] retdata = new byte[data1.length + data2.length]; System.arraycopy(data1, 0, retdata, 0, data1.length); System.arraycopy(data2, 0, retdata, data1.length, data2.length); return retdata; } private static String clearDateInfo(String strInfo) { if (strInfo != null && hasDateInfo(strInfo.getBytes())) { strInfo = strInfo.substring(strInfo.indexOf(mSeparator) + 1,strInfo.length()); } return strInfo; } private static byte[] clearDateInfo(byte[] data) { if (hasDateInfo(data)) { return copyOfRange(data, indexOf(data, mSeparator), data.length); } return data; } private static boolean hasDateInfo(byte[] data) { return data != null && data.length > 15 && data[13] == '-' && indexOf(data, mSeparator) > 14; } private static String[] getDateInfoFromDate(byte[] data) { if (hasDateInfo(data)) { String saveDate = new String(copyOfRange(data, 0, 13)); String deleteAfter = new String(copyOfRange(data, 14, indexOf(data, mSeparator))); return new String[] { saveDate, deleteAfter }; } return null; } private static int indexOf(byte[] data, char c) { for (int i = 0; i < data.length; i++) { if (data[i] == c) { return i; } } return -1; } private static byte[] copyOfRange(byte[] original, int from, int to) { int newLength = to - from; if (newLength < 0) throw new IllegalArgumentException(from + " > " + to); byte[] copy = new byte[newLength]; System.arraycopy(original, from, copy, 0, Math.min(original.length - from, newLength)); return copy; } private static final char mSeparator = ' '; private static String createDateInfo(int second) { return System.currentTimeMillis() + "-" + second + mSeparator; } } }
修改保存的时间可能造成的一个异常,添加序列化对象保存时间
AsimpleCacheDemo/ASimpleCache/org/afinal/simplecache/ACache.java
修改保存的时间可能造成的一个异常,添加序列化对象保存时间
Java
apache-2.0
3beaa5a2bab83e4ff2e189db03b038c32e78a85c
0
adamjshook/accumulo,ctubbsii/accumulo,ctubbsii/accumulo,mjwall/accumulo,mikewalch/accumulo,milleruntime/accumulo,phrocker/accumulo-1,adamjshook/accumulo,ctubbsii/accumulo,lstav/accumulo,apache/accumulo,keith-turner/accumulo,lstav/accumulo,apache/accumulo,milleruntime/accumulo,dhutchis/accumulo,keith-turner/accumulo,lstav/accumulo,mjwall/accumulo,mjwall/accumulo,ctubbsii/accumulo,ivakegg/accumulo,phrocker/accumulo-1,mjwall/accumulo,adamjshook/accumulo,ivakegg/accumulo,mjwall/accumulo,keith-turner/accumulo,ctubbsii/accumulo,apache/accumulo,mikewalch/accumulo,ctubbsii/accumulo,adamjshook/accumulo,adamjshook/accumulo,mikewalch/accumulo,keith-turner/accumulo,ivakegg/accumulo,milleruntime/accumulo,mikewalch/accumulo,adamjshook/accumulo,phrocker/accumulo-1,adamjshook/accumulo,dhutchis/accumulo,keith-turner/accumulo,mikewalch/accumulo,ivakegg/accumulo,adamjshook/accumulo,milleruntime/accumulo,adamjshook/accumulo,dhutchis/accumulo,lstav/accumulo,lstav/accumulo,dhutchis/accumulo,ivakegg/accumulo,apache/accumulo,ctubbsii/accumulo,mikewalch/accumulo,mikewalch/accumulo,lstav/accumulo,dhutchis/accumulo,milleruntime/accumulo,apache/accumulo,keith-turner/accumulo,apache/accumulo,ivakegg/accumulo,mjwall/accumulo,dhutchis/accumulo,keith-turner/accumulo,phrocker/accumulo-1,dhutchis/accumulo,mikewalch/accumulo,phrocker/accumulo-1,mjwall/accumulo,dhutchis/accumulo,dhutchis/accumulo,milleruntime/accumulo,phrocker/accumulo-1,ivakegg/accumulo,milleruntime/accumulo,lstav/accumulo,phrocker/accumulo-1,apache/accumulo
/* * 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.master; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.apache.accumulo.core.Constants; import org.apache.accumulo.core.client.AccumuloException; import org.apache.accumulo.core.client.AccumuloSecurityException; import org.apache.accumulo.core.client.Connector; import org.apache.accumulo.core.client.Instance; import org.apache.accumulo.core.client.Scanner; import org.apache.accumulo.core.client.TableNotFoundException; import org.apache.accumulo.core.client.impl.Namespaces; import org.apache.accumulo.core.client.impl.Tables; import org.apache.accumulo.core.client.impl.ThriftTransportPool; import org.apache.accumulo.core.client.impl.thrift.TableOperation; import org.apache.accumulo.core.client.impl.thrift.TableOperationExceptionType; import org.apache.accumulo.core.client.impl.thrift.ThriftTableOperationException; import org.apache.accumulo.core.conf.AccumuloConfiguration; import org.apache.accumulo.core.conf.Property; import org.apache.accumulo.core.data.Key; import org.apache.accumulo.core.data.KeyExtent; import org.apache.accumulo.core.data.Value; import org.apache.accumulo.core.master.state.tables.TableState; import org.apache.accumulo.core.master.thrift.MasterClientService.Iface; import org.apache.accumulo.core.master.thrift.MasterClientService.Processor; import org.apache.accumulo.core.master.thrift.MasterGoalState; import org.apache.accumulo.core.master.thrift.MasterState; import org.apache.accumulo.core.master.thrift.TabletServerStatus; import org.apache.accumulo.core.metadata.MetadataTable; import org.apache.accumulo.core.metadata.RootTable; import org.apache.accumulo.core.metadata.schema.MetadataSchema.TabletsSection; import org.apache.accumulo.core.security.Authorizations; import org.apache.accumulo.core.security.Credentials; import org.apache.accumulo.core.security.NamespacePermission; import org.apache.accumulo.core.security.SecurityUtil; import org.apache.accumulo.core.security.TablePermission; import org.apache.accumulo.core.util.Daemon; import org.apache.accumulo.core.util.Pair; import org.apache.accumulo.core.util.UtilWaitThread; import org.apache.accumulo.core.zookeeper.ZooUtil; import org.apache.accumulo.fate.AgeOffStore; import org.apache.accumulo.fate.Fate; import org.apache.accumulo.fate.zookeeper.IZooReaderWriter; import org.apache.accumulo.fate.zookeeper.ZooLock.LockLossReason; import org.apache.accumulo.fate.zookeeper.ZooUtil.NodeExistsPolicy; import org.apache.accumulo.fate.zookeeper.ZooUtil.NodeMissingPolicy; import org.apache.accumulo.master.recovery.RecoveryManager; import org.apache.accumulo.master.state.TableCounts; import org.apache.accumulo.server.Accumulo; import org.apache.accumulo.server.ServerConstants; import org.apache.accumulo.server.ServerOpts; import org.apache.accumulo.server.client.HdfsZooInstance; import org.apache.accumulo.server.conf.ServerConfiguration; import org.apache.accumulo.server.fs.VolumeManager; import org.apache.accumulo.server.fs.VolumeManager.FileType; import org.apache.accumulo.server.fs.VolumeManagerImpl; import org.apache.accumulo.server.init.Initialize; import org.apache.accumulo.server.master.LiveTServerSet; import org.apache.accumulo.server.master.LiveTServerSet.TServerConnection; import org.apache.accumulo.server.master.balancer.DefaultLoadBalancer; import org.apache.accumulo.server.master.balancer.TabletBalancer; import org.apache.accumulo.server.master.state.CurrentState; import org.apache.accumulo.server.master.state.DeadServerList; import org.apache.accumulo.server.master.state.MergeInfo; import org.apache.accumulo.server.master.state.MergeState; import org.apache.accumulo.server.master.state.MetaDataStateStore; import org.apache.accumulo.server.master.state.RootTabletStateStore; import org.apache.accumulo.server.master.state.TServerInstance; import org.apache.accumulo.server.master.state.TabletLocationState; import org.apache.accumulo.server.master.state.TabletMigration; import org.apache.accumulo.server.master.state.TabletState; import org.apache.accumulo.server.master.state.ZooStore; import org.apache.accumulo.server.master.state.ZooTabletStateStore; import org.apache.accumulo.server.security.AuditedSecurityOperation; import org.apache.accumulo.server.security.SecurityOperation; import org.apache.accumulo.server.security.SystemCredentials; import org.apache.accumulo.server.security.handler.ZKPermHandler; import org.apache.accumulo.server.tables.TableManager; import org.apache.accumulo.server.tables.TableObserver; import org.apache.accumulo.server.util.DefaultMap; import org.apache.accumulo.server.util.Halt; import org.apache.accumulo.server.util.MetadataTableUtil; import org.apache.accumulo.server.util.RpcWrapper; import org.apache.accumulo.server.util.TServerUtils; import org.apache.accumulo.server.util.TServerUtils.ServerAddress; import org.apache.accumulo.server.util.time.SimpleTimer; import org.apache.accumulo.server.zookeeper.ZooLock; import org.apache.accumulo.server.zookeeper.ZooReaderWriter; import org.apache.accumulo.start.classloader.vfs.AccumuloVFSClassLoader; import org.apache.accumulo.start.classloader.vfs.ContextManager; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.DataInputBuffer; import org.apache.hadoop.io.DataOutputBuffer; import org.apache.hadoop.io.Text; import org.apache.log4j.Logger; import org.apache.thrift.TException; import org.apache.thrift.server.TServer; import org.apache.thrift.transport.TTransportException; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.data.Stat; import com.google.common.collect.Iterables; /** * The Master is responsible for assigning and balancing tablets to tablet servers. * * The master will also coordinate log recoveries and reports general status. */ public class Master implements LiveTServerSet.Listener, TableObserver, CurrentState { final static Logger log = Logger.getLogger(Master.class); final static int ONE_SECOND = 1000; final private static Text METADATA_TABLE_ID = new Text(MetadataTable.ID); final private static Text ROOT_TABLE_ID = new Text(RootTable.ID); final static long TIME_TO_WAIT_BETWEEN_SCANS = 60 * ONE_SECOND; final private static long TIME_BETWEEN_MIGRATION_CLEANUPS = 5 * 60 * ONE_SECOND; final static long WAIT_BETWEEN_ERRORS = ONE_SECOND; final private static long DEFAULT_WAIT_FOR_WATCHER = 10 * ONE_SECOND; final private static int MAX_CLEANUP_WAIT_TIME = ONE_SECOND; final private static int TIME_TO_WAIT_BETWEEN_LOCK_CHECKS = ONE_SECOND; final static int MAX_TSERVER_WORK_CHUNK = 5000; final private static int MAX_BAD_STATUS_COUNT = 3; final VolumeManager fs; final private Instance instance; final private String hostname; final LiveTServerSet tserverSet; final private List<TabletGroupWatcher> watchers = new ArrayList<TabletGroupWatcher>(); final SecurityOperation security; final Map<TServerInstance,AtomicInteger> badServers = Collections.synchronizedMap(new DefaultMap<TServerInstance,AtomicInteger>(new AtomicInteger())); final Set<TServerInstance> serversToShutdown = Collections.synchronizedSet(new HashSet<TServerInstance>()); final SortedMap<KeyExtent,TServerInstance> migrations = Collections.synchronizedSortedMap(new TreeMap<KeyExtent,TServerInstance>()); final EventCoordinator nextEvent = new EventCoordinator(); final private Object mergeLock = new Object(); RecoveryManager recoveryManager = null; ZooLock masterLock = null; private TServer clientService = null; TabletBalancer tabletBalancer; private MasterState state = MasterState.INITIAL; Fate<Master> fate; volatile SortedMap<TServerInstance,TabletServerStatus> tserverStatus = Collections.unmodifiableSortedMap(new TreeMap<TServerInstance,TabletServerStatus>()); synchronized MasterState getMasterState() { return state; } public boolean stillMaster() { return getMasterState() != MasterState.STOP; } static final boolean X = true; static final boolean _ = false; // @formatter:off static final boolean transitionOK[][] = { // INITIAL HAVE_LOCK SAFE_MODE NORMAL UNLOAD_META UNLOAD_ROOT STOP /* INITIAL */ {X, X, _, _, _, _, X}, /* HAVE_LOCK */ {_, X, X, X, _, _, X}, /* SAFE_MODE */ {_, _, X, X, X, _, X}, /* NORMAL */ {_, _, X, X, X, _, X}, /* UNLOAD_METADATA_TABLETS */ {_, _, X, X, X, X, X}, /* UNLOAD_ROOT_TABLET */ {_, _, _, X, X, X, X}, /* STOP */ {_, _, _, _, _, X, X}}; //@formatter:on synchronized void setMasterState(MasterState newState) { if (state.equals(newState)) return; if (!transitionOK[state.ordinal()][newState.ordinal()]) { log.error("Programmer error: master should not transition from " + state + " to " + newState); } MasterState oldState = state; state = newState; nextEvent.event("State changed from %s to %s", oldState, newState); if (newState == MasterState.STOP) { // Give the server a little time before shutdown so the client // thread requesting the stop can return SimpleTimer.getInstance().schedule(new Runnable() { @Override public void run() { // This frees the main thread and will cause the master to exit clientService.stop(); Master.this.nextEvent.event("stopped event loop"); } }, 100l, 1000l); } if (oldState != newState && (newState == MasterState.HAVE_LOCK)) { upgradeZookeeper(); } if (oldState != newState && (newState == MasterState.NORMAL)) { upgradeMetadata(); } } private void moveRootTabletToRootTable(IZooReaderWriter zoo) throws Exception { String dirZPath = ZooUtil.getRoot(instance) + RootTable.ZROOT_TABLET_PATH; if (!zoo.exists(dirZPath)) { Path oldPath = fs.getFullPath(FileType.TABLE, "/" + MetadataTable.ID + "/root_tablet"); if (fs.exists(oldPath)) { String newPath = fs.choose(ServerConstants.getTablesDirs()) + "/" + RootTable.ID; fs.mkdirs(new Path(newPath)); if (!fs.rename(oldPath, new Path(newPath))) { throw new IOException("Failed to move root tablet from " + oldPath + " to " + newPath); } log.info("Upgrade renamed " + oldPath + " to " + newPath); } Path location = null; for (String basePath : ServerConstants.getTablesDirs()) { Path path = new Path(basePath + "/" + RootTable.ID + RootTable.ROOT_TABLET_LOCATION); if (fs.exists(path)) { if (location != null) { throw new IllegalStateException("Root table at multiple locations " + location + " " + path); } location = path; } } if (location == null) throw new IllegalStateException("Failed to find root tablet"); log.info("Upgrade setting root table location in zookeeper " + location); zoo.putPersistentData(dirZPath, location.toString().getBytes(), NodeExistsPolicy.FAIL); } } private boolean haveUpgradedZooKeeper = false; private void upgradeZookeeper() { // 1.5.1 and 1.6.0 both do some state checking after obtaining the zoolock for the // monitor and before starting up. It's not tied to the data version at all (and would // introduce unnecessary complexity to try to make the master do it), but be aware // that the master is not the only thing that may alter zookeeper before starting. final int accumuloPersistentVersion = Accumulo.getAccumuloPersistentVersion(fs); if (accumuloPersistentVersion == ServerConstants.TWO_VERSIONS_AGO || accumuloPersistentVersion == ServerConstants.PREV_DATA_VERSION) { // This Master hasn't started Fate yet, so any outstanding transactions must be from before the upgrade. // Change to Guava's Verify once we use Guava 17. if (null != fate) { throw new IllegalStateException("Access to Fate should not have been initialized prior to the Master transitioning to active. Please save all logs and file a bug."); } Accumulo.abortIfFateTransactions(); try { log.info("Upgrading zookeeper"); IZooReaderWriter zoo = ZooReaderWriter.getInstance(); final String zooRoot = ZooUtil.getRoot(instance); if (accumuloPersistentVersion == ServerConstants.TWO_VERSIONS_AGO) { zoo.recursiveDelete(zooRoot + "/loggers", NodeMissingPolicy.SKIP); zoo.recursiveDelete(zooRoot + "/dead/loggers", NodeMissingPolicy.SKIP); final byte[] zero = new byte[] {'0'}; zoo.putPersistentData(zooRoot + Constants.ZRECOVERY, zero, NodeExistsPolicy.SKIP); for (String id : Tables.getIdToNameMap(instance).keySet()) { zoo.putPersistentData(zooRoot + Constants.ZTABLES + "/" + id + Constants.ZTABLE_COMPACT_CANCEL_ID, zero, NodeExistsPolicy.SKIP); } } // create initial namespaces String namespaces = ZooUtil.getRoot(instance) + Constants.ZNAMESPACES; zoo.putPersistentData(namespaces, new byte[0], NodeExistsPolicy.SKIP); for (Pair<String,String> namespace : Iterables.concat( Collections.singleton(new Pair<String,String>(Namespaces.ACCUMULO_NAMESPACE, Namespaces.ACCUMULO_NAMESPACE_ID)), Collections.singleton(new Pair<String,String>(Namespaces.DEFAULT_NAMESPACE, Namespaces.DEFAULT_NAMESPACE_ID)))) { String ns = namespace.getFirst(); String id = namespace.getSecond(); log.debug("Upgrade creating namespace \"" + ns + "\" (ID: " + id + ")"); if (!Namespaces.exists(instance, id)) TableManager.prepareNewNamespaceState(instance.getInstanceID(), id, ns, NodeExistsPolicy.SKIP); } // create root table log.debug("Upgrade creating table " + RootTable.NAME + " (ID: " + RootTable.ID + ")"); TableManager.prepareNewTableState(instance.getInstanceID(), RootTable.ID, Namespaces.ACCUMULO_NAMESPACE_ID, RootTable.NAME, TableState.ONLINE, NodeExistsPolicy.SKIP); Initialize.initMetadataConfig(RootTable.ID); // ensure root user can flush root table security.grantTablePermission(SystemCredentials.get().toThrift(instance), security.getRootUsername(), RootTable.ID, TablePermission.ALTER_TABLE, Namespaces.ACCUMULO_NAMESPACE_ID); // put existing tables in the correct namespaces String tables = ZooUtil.getRoot(instance) + Constants.ZTABLES; for (String tableId : zoo.getChildren(tables)) { String targetNamespace = (MetadataTable.ID.equals(tableId) || RootTable.ID.equals(tableId)) ? Namespaces.ACCUMULO_NAMESPACE_ID : Namespaces.DEFAULT_NAMESPACE_ID; log.debug("Upgrade moving table " + new String(zoo.getData(tables + "/" + tableId + Constants.ZTABLE_NAME, null), Constants.UTF8) + " (ID: " + tableId + ") into namespace with ID " + targetNamespace); zoo.putPersistentData(tables + "/" + tableId + Constants.ZTABLE_NAMESPACE, targetNamespace.getBytes(Constants.UTF8), NodeExistsPolicy.SKIP); } // rename metadata table log.debug("Upgrade renaming table " + MetadataTable.OLD_NAME + " (ID: " + MetadataTable.ID + ") to " + MetadataTable.NAME); zoo.putPersistentData(tables + "/" + MetadataTable.ID + Constants.ZTABLE_NAME, Tables.qualify(MetadataTable.NAME).getSecond().getBytes(Constants.UTF8), NodeExistsPolicy.OVERWRITE); moveRootTabletToRootTable(zoo); // add system namespace permissions to existing users ZKPermHandler perm = new ZKPermHandler(); perm.initialize(instance.getInstanceID(), true); String users = ZooUtil.getRoot(instance) + "/users"; for (String user : zoo.getChildren(users)) { zoo.putPersistentData(users + "/" + user + "/Namespaces", new byte[0], NodeExistsPolicy.SKIP); perm.grantNamespacePermission(user, Namespaces.ACCUMULO_NAMESPACE_ID, NamespacePermission.READ); } perm.grantNamespacePermission("root", Namespaces.ACCUMULO_NAMESPACE_ID, NamespacePermission.ALTER_TABLE); haveUpgradedZooKeeper = true; } catch (Exception ex) { log.fatal("Error performing upgrade", ex); System.exit(1); } } } private final AtomicBoolean upgradeMetadataRunning = new AtomicBoolean(false); private final CountDownLatch waitForMetadataUpgrade = new CountDownLatch(1); private final ServerConfiguration serverConfig; private void upgradeMetadata() { // we make sure we're only doing the rest of this method once so that we can signal to other threads that an upgrade wasn't needed. if (upgradeMetadataRunning.compareAndSet(false, true)) { final int accumuloPersistentVersion = Accumulo.getAccumuloPersistentVersion(fs); if (accumuloPersistentVersion == ServerConstants.TWO_VERSIONS_AGO || accumuloPersistentVersion == ServerConstants.PREV_DATA_VERSION) { // sanity check that we passed the Fate verification prior to ZooKeeper upgrade, and that Fate still hasn't been started. // Change both to use Guava's Verify once we use Guava 17. if (!haveUpgradedZooKeeper) { throw new IllegalStateException("We should only attempt to upgrade Accumulo's !METADATA table if we've already upgraded ZooKeeper. Please save all logs and file a bug."); } if (null != fate) { throw new IllegalStateException("Access to Fate should not have been initialized prior to the Master finishing upgrades. Please save all logs and file a bug."); } Runnable upgradeTask = new Runnable() { @Override public void run() { try { log.info("Starting to upgrade !METADATA table."); MetadataTableUtil.moveMetaDeleteMarkers(instance, SystemCredentials.get()); log.info("Updating persistent data version."); Accumulo.updateAccumuloVersion(fs, accumuloPersistentVersion); log.info("Upgrade complete"); waitForMetadataUpgrade.countDown(); } catch (Exception ex) { log.fatal("Error performing upgrade", ex); System.exit(1); } } }; // need to run this in a separate thread because a lock is held that prevents metadata tablets from being assigned and this task writes to the // metadata table new Thread(upgradeTask).start(); } else { waitForMetadataUpgrade.countDown(); } } } private int assignedOrHosted(Text tableId) { int result = 0; for (TabletGroupWatcher watcher : watchers) { TableCounts count = watcher.getStats(tableId); result += count.hosted() + count.assigned(); } return result; } private int totalAssignedOrHosted() { int result = 0; for (TabletGroupWatcher watcher : watchers) { for (TableCounts counts : watcher.getStats().values()) { result += counts.assigned() + counts.hosted(); } } return result; } private int nonMetaDataTabletsAssignedOrHosted() { return totalAssignedOrHosted() - assignedOrHosted(new Text(MetadataTable.ID)) - assignedOrHosted(new Text(RootTable.ID)); } private int notHosted() { int result = 0; for (TabletGroupWatcher watcher : watchers) { for (TableCounts counts : watcher.getStats().values()) { result += counts.assigned() + counts.assignedToDeadServers(); } } return result; } // The number of unassigned tablets that should be assigned: displayed on the monitor page int displayUnassigned() { int result = 0; switch (getMasterState()) { case NORMAL: // Count offline tablets for online tables for (TabletGroupWatcher watcher : watchers) { TableManager manager = TableManager.getInstance(); for (Entry<Text,TableCounts> entry : watcher.getStats().entrySet()) { Text tableId = entry.getKey(); TableCounts counts = entry.getValue(); TableState tableState = manager.getTableState(tableId.toString()); if (tableState != null && tableState.equals(TableState.ONLINE)) { result += counts.unassigned() + counts.assignedToDeadServers() + counts.assigned(); } } } break; case SAFE_MODE: // Count offline tablets for the metadata table for (TabletGroupWatcher watcher : watchers) { result += watcher.getStats(METADATA_TABLE_ID).unassigned(); } break; case UNLOAD_METADATA_TABLETS: case UNLOAD_ROOT_TABLET: for (TabletGroupWatcher watcher : watchers) { result += watcher.getStats(METADATA_TABLE_ID).unassigned(); } break; default: break; } return result; } public void mustBeOnline(final String tableId) throws ThriftTableOperationException { Tables.clearCache(instance); if (!Tables.getTableState(instance, tableId).equals(TableState.ONLINE)) throw new ThriftTableOperationException(tableId, null, TableOperation.MERGE, TableOperationExceptionType.OFFLINE, "table is not online"); } public Connector getConnector() throws AccumuloException, AccumuloSecurityException { return instance.getConnector(SystemCredentials.get().getPrincipal(), SystemCredentials.get().getToken()); } private Master(ServerConfiguration config, VolumeManager fs, String hostname) throws IOException { this.serverConfig = config; this.instance = config.getInstance(); this.fs = fs; this.hostname = hostname; AccumuloConfiguration aconf = serverConfig.getConfiguration(); log.info("Version " + Constants.VERSION); log.info("Instance " + instance.getInstanceID()); ThriftTransportPool.getInstance().setIdleTime(aconf.getTimeInMillis(Property.GENERAL_RPC_TIMEOUT)); security = AuditedSecurityOperation.getInstance(); tserverSet = new LiveTServerSet(instance, config.getConfiguration(), this); this.tabletBalancer = aconf.instantiateClassProperty(Property.MASTER_TABLET_BALANCER, TabletBalancer.class, new DefaultLoadBalancer()); this.tabletBalancer.init(serverConfig); try { AccumuloVFSClassLoader.getContextManager().setContextConfig(new ContextManager.DefaultContextsConfig(new Iterable<Entry<String,String>>() { @Override public Iterator<Entry<String,String>> iterator() { return getSystemConfiguration().iterator(); } })); } catch (IOException e) { throw new RuntimeException(e); } } public TServerConnection getConnection(TServerInstance server) { return tserverSet.getConnection(server); } public MergeInfo getMergeInfo(Text tableId) { synchronized (mergeLock) { try { String path = ZooUtil.getRoot(instance.getInstanceID()) + Constants.ZTABLES + "/" + tableId.toString() + "/merge"; if (!ZooReaderWriter.getInstance().exists(path)) return new MergeInfo(); byte[] data = ZooReaderWriter.getInstance().getData(path, new Stat()); DataInputBuffer in = new DataInputBuffer(); in.reset(data, data.length); MergeInfo info = new MergeInfo(); info.readFields(in); return info; } catch (KeeperException.NoNodeException ex) { log.info("Error reading merge state, it probably just finished"); return new MergeInfo(); } catch (Exception ex) { log.warn("Unexpected error reading merge state", ex); return new MergeInfo(); } } } public void setMergeState(MergeInfo info, MergeState state) throws IOException, KeeperException, InterruptedException { synchronized (mergeLock) { String path = ZooUtil.getRoot(instance.getInstanceID()) + Constants.ZTABLES + "/" + info.getExtent().getTableId().toString() + "/merge"; info.setState(state); if (state.equals(MergeState.NONE)) { ZooReaderWriter.getInstance().recursiveDelete(path, NodeMissingPolicy.SKIP); } else { DataOutputBuffer out = new DataOutputBuffer(); try { info.write(out); } catch (IOException ex) { throw new RuntimeException("Unlikely", ex); } ZooReaderWriter.getInstance().putPersistentData(path, out.getData(), state.equals(MergeState.STARTED) ? ZooUtil.NodeExistsPolicy.FAIL : ZooUtil.NodeExistsPolicy.OVERWRITE); } mergeLock.notifyAll(); } nextEvent.event("Merge state of %s set to %s", info.getExtent(), state); } public void clearMergeState(Text tableId) throws IOException, KeeperException, InterruptedException { synchronized (mergeLock) { String path = ZooUtil.getRoot(instance.getInstanceID()) + Constants.ZTABLES + "/" + tableId.toString() + "/merge"; ZooReaderWriter.getInstance().recursiveDelete(path, NodeMissingPolicy.SKIP); mergeLock.notifyAll(); } nextEvent.event("Merge state of %s cleared", tableId); } void setMasterGoalState(MasterGoalState state) { try { ZooReaderWriter.getInstance().putPersistentData(ZooUtil.getRoot(instance) + Constants.ZMASTER_GOAL_STATE, state.name().getBytes(), NodeExistsPolicy.OVERWRITE); } catch (Exception ex) { log.error("Unable to set master goal state in zookeeper"); } } MasterGoalState getMasterGoalState() { while (true) try { byte[] data = ZooReaderWriter.getInstance().getData(ZooUtil.getRoot(instance) + Constants.ZMASTER_GOAL_STATE, null); return MasterGoalState.valueOf(new String(data)); } catch (Exception e) { log.error("Problem getting real goal state: " + e); UtilWaitThread.sleep(1000); } } public boolean hasCycled(long time) { for (TabletGroupWatcher watcher : watchers) { if (watcher.stats.lastScanFinished() < time) return false; } return true; } public void clearMigrations(String tableId) { synchronized (migrations) { Iterator<KeyExtent> iterator = migrations.keySet().iterator(); while (iterator.hasNext()) { KeyExtent extent = iterator.next(); if (extent.getTableId().toString().equals(tableId)) { iterator.remove(); } } } } static enum TabletGoalState { HOSTED, UNASSIGNED, DELETED }; TabletGoalState getSystemGoalState(TabletLocationState tls) { switch (getMasterState()) { case NORMAL: return TabletGoalState.HOSTED; case HAVE_LOCK: // fall-through intended case INITIAL: // fall-through intended case SAFE_MODE: if (tls.extent.isMeta()) return TabletGoalState.HOSTED; return TabletGoalState.UNASSIGNED; case UNLOAD_METADATA_TABLETS: if (tls.extent.isRootTablet()) return TabletGoalState.HOSTED; return TabletGoalState.UNASSIGNED; case UNLOAD_ROOT_TABLET: return TabletGoalState.UNASSIGNED; case STOP: return TabletGoalState.UNASSIGNED; default: throw new IllegalStateException("Unknown Master State"); } } TabletGoalState getTableGoalState(KeyExtent extent) { TableState tableState = TableManager.getInstance().getTableState(extent.getTableId().toString()); if (tableState == null) return TabletGoalState.DELETED; switch (tableState) { case DELETING: return TabletGoalState.DELETED; case OFFLINE: case NEW: return TabletGoalState.UNASSIGNED; default: return TabletGoalState.HOSTED; } } TabletGoalState getGoalState(TabletLocationState tls, MergeInfo mergeInfo) { KeyExtent extent = tls.extent; // Shutting down? TabletGoalState state = getSystemGoalState(tls); if (state == TabletGoalState.HOSTED) { if (tls.current != null && serversToShutdown.contains(tls.current)) { return TabletGoalState.UNASSIGNED; } // Handle merge transitions if (mergeInfo.getExtent() != null) { log.debug("mergeInfo overlaps: " + extent + " " + mergeInfo.overlaps(extent)); if (mergeInfo.overlaps(extent)) { switch (mergeInfo.getState()) { case NONE: case COMPLETE: break; case STARTED: case SPLITTING: return TabletGoalState.HOSTED; case WAITING_FOR_CHOPPED: if (tls.getState(onlineTabletServers()).equals(TabletState.HOSTED)) { if (tls.chopped) return TabletGoalState.UNASSIGNED; } else { if (tls.chopped && tls.walogs.isEmpty()) return TabletGoalState.UNASSIGNED; } return TabletGoalState.HOSTED; case WAITING_FOR_OFFLINE: case MERGING: return TabletGoalState.UNASSIGNED; } } } // taking table offline? state = getTableGoalState(extent); if (state == TabletGoalState.HOSTED) { // Maybe this tablet needs to be migrated TServerInstance dest = migrations.get(extent); if (dest != null && tls.current != null && !dest.equals(tls.current)) { return TabletGoalState.UNASSIGNED; } } } return state; } private class MigrationCleanupThread extends Daemon { @Override public void run() { setName("Migration Cleanup Thread"); while (stillMaster()) { if (!migrations.isEmpty()) { try { cleanupMutations(); } catch (Exception ex) { log.error("Error cleaning up migrations", ex); } } UtilWaitThread.sleep(TIME_BETWEEN_MIGRATION_CLEANUPS); } } // If a migrating tablet splits, and the tablet dies before sending the // master a message, the migration will refer to a non-existing tablet, // so it can never complete. Periodically scan the metadata table and // remove any migrating tablets that no longer exist. private void cleanupMutations() throws AccumuloException, AccumuloSecurityException, TableNotFoundException { Connector connector = getConnector(); Scanner scanner = connector.createScanner(MetadataTable.NAME, Authorizations.EMPTY); TabletsSection.TabletColumnFamily.PREV_ROW_COLUMN.fetch(scanner); Set<KeyExtent> found = new HashSet<KeyExtent>(); for (Entry<Key,Value> entry : scanner) { KeyExtent extent = new KeyExtent(entry.getKey().getRow(), entry.getValue()); if (migrations.containsKey(extent)) { found.add(extent); } } migrations.keySet().retainAll(found); } } private class StatusThread extends Daemon { @Override public void run() { setName("Status Thread"); EventCoordinator.Listener eventListener = nextEvent.getListener(); while (stillMaster()) { long wait = DEFAULT_WAIT_FOR_WATCHER; try { switch (getMasterGoalState()) { case NORMAL: setMasterState(MasterState.NORMAL); break; case SAFE_MODE: if (getMasterState() == MasterState.NORMAL) { setMasterState(MasterState.SAFE_MODE); } if (getMasterState() == MasterState.HAVE_LOCK) { setMasterState(MasterState.SAFE_MODE); } break; case CLEAN_STOP: switch (getMasterState()) { case NORMAL: setMasterState(MasterState.SAFE_MODE); break; case SAFE_MODE: { int count = nonMetaDataTabletsAssignedOrHosted(); log.debug(String.format("There are %d non-metadata tablets assigned or hosted", count)); if (count == 0) setMasterState(MasterState.UNLOAD_METADATA_TABLETS); } break; case UNLOAD_METADATA_TABLETS: { int count = assignedOrHosted(METADATA_TABLE_ID); log.debug(String.format("There are %d metadata tablets assigned or hosted", count)); if (count == 0) setMasterState(MasterState.UNLOAD_ROOT_TABLET); } break; case UNLOAD_ROOT_TABLET: { int count = assignedOrHosted(METADATA_TABLE_ID); if (count > 0) { log.debug(String.format("%d metadata tablets online", count)); setMasterState(MasterState.UNLOAD_ROOT_TABLET); } int root_count = assignedOrHosted(ROOT_TABLE_ID); if (root_count > 0) log.debug("The root tablet is still assigned or hosted"); if (count + root_count == 0) { Set<TServerInstance> currentServers = tserverSet.getCurrentServers(); log.debug("stopping " + currentServers.size() + " tablet servers"); for (TServerInstance server : currentServers) { try { serversToShutdown.add(server); tserverSet.getConnection(server).fastHalt(masterLock); } catch (TException e) { // its probably down, and we don't care } finally { tserverSet.remove(server); } } if (currentServers.size() == 0) setMasterState(MasterState.STOP); } } break; default: break; } } wait = updateStatus(); eventListener.waitForEvents(wait); } catch (Throwable t) { log.error("Error balancing tablets", t); UtilWaitThread.sleep(WAIT_BETWEEN_ERRORS); } } } private long updateStatus() throws AccumuloException, AccumuloSecurityException, TableNotFoundException { tserverStatus = Collections.synchronizedSortedMap(gatherTableInformation()); checkForHeldServer(tserverStatus); if (!badServers.isEmpty()) { log.debug("not balancing because the balance information is out-of-date " + badServers.keySet()); } else if (notHosted() > 0) { log.debug("not balancing because there are unhosted tablets"); } else if (getMasterGoalState() == MasterGoalState.CLEAN_STOP) { log.debug("not balancing because the master is attempting to stop cleanly"); } else if (!serversToShutdown.isEmpty()) { log.debug("not balancing while shutting down servers " + serversToShutdown); } else { return balanceTablets(); } return DEFAULT_WAIT_FOR_WATCHER; } private void checkForHeldServer(SortedMap<TServerInstance,TabletServerStatus> tserverStatus) { TServerInstance instance = null; int crazyHoldTime = 0; int someHoldTime = 0; final long maxWait = getSystemConfiguration().getTimeInMillis(Property.TSERV_HOLD_TIME_SUICIDE); for (Entry<TServerInstance,TabletServerStatus> entry : tserverStatus.entrySet()) { if (entry.getValue().getHoldTime() > 0) { someHoldTime++; if (entry.getValue().getHoldTime() > maxWait) { instance = entry.getKey(); crazyHoldTime++; } } } if (crazyHoldTime == 1 && someHoldTime == 1 && tserverStatus.size() > 1) { log.warn("Tablet server " + instance + " exceeded maximum hold time: attempting to kill it"); try { TServerConnection connection = tserverSet.getConnection(instance); if (connection != null) connection.fastHalt(masterLock); } catch (TException e) { log.error(e, e); } tserverSet.remove(instance); } } private long balanceTablets() { List<TabletMigration> migrationsOut = new ArrayList<TabletMigration>(); Set<KeyExtent> migrationsCopy = new HashSet<KeyExtent>(); synchronized (migrations) { migrationsCopy.addAll(migrations.keySet()); } long wait = tabletBalancer.balance(Collections.unmodifiableSortedMap(tserverStatus), Collections.unmodifiableSet(migrationsCopy), migrationsOut); for (TabletMigration m : TabletBalancer.checkMigrationSanity(tserverStatus.keySet(), migrationsOut)) { if (migrations.containsKey(m.tablet)) { log.warn("balancer requested migration more than once, skipping " + m); continue; } migrations.put(m.tablet, m.newServer); log.debug("migration " + m); } if (migrationsOut.size() > 0) { nextEvent.event("Migrating %d more tablets, %d total", migrationsOut.size(), migrations.size()); } return wait; } } private SortedMap<TServerInstance,TabletServerStatus> gatherTableInformation() { long start = System.currentTimeMillis(); SortedMap<TServerInstance,TabletServerStatus> result = new TreeMap<TServerInstance,TabletServerStatus>(); Set<TServerInstance> currentServers = tserverSet.getCurrentServers(); for (TServerInstance server : currentServers) { try { Thread t = Thread.currentThread(); String oldName = t.getName(); try { t.setName("Getting status from " + server); TServerConnection connection = tserverSet.getConnection(server); if (connection == null) throw new IOException("No connection to " + server); TabletServerStatus status = connection.getTableMap(false); result.put(server, status); } finally { t.setName(oldName); } } catch (Exception ex) { log.error("unable to get tablet server status " + server + " " + ex.toString()); log.debug("unable to get tablet server status " + server, ex); if (badServers.get(server).incrementAndGet() > MAX_BAD_STATUS_COUNT) { log.warn("attempting to stop " + server); try { TServerConnection connection = tserverSet.getConnection(server); if (connection != null) connection.halt(masterLock); } catch (TTransportException e) { // ignore: it's probably down } catch (Exception e) { log.info("error talking to troublesome tablet server ", e); } badServers.remove(server); tserverSet.remove(server); } } } synchronized (badServers) { badServers.keySet().retainAll(currentServers); badServers.keySet().removeAll(result.keySet()); } log.debug(String.format("Finished gathering information from %d servers in %.2f seconds", result.size(), (System.currentTimeMillis() - start) / 1000.)); return result; } public void run() throws IOException, InterruptedException, KeeperException { final String zroot = ZooUtil.getRoot(instance); getMasterLock(zroot + Constants.ZMASTER_LOCK); recoveryManager = new RecoveryManager(this); TableManager.getInstance().addObserver(this); StatusThread statusThread = new StatusThread(); statusThread.start(); MigrationCleanupThread migrationCleanupThread = new MigrationCleanupThread(); migrationCleanupThread.start(); tserverSet.startListeningForTabletServerChanges(); ZooReaderWriter.getInstance().getChildren(zroot + Constants.ZRECOVERY, new Watcher() { @Override public void process(WatchedEvent event) { nextEvent.event("Noticed recovery changes", event.getType()); try { // watcher only fires once, add it back ZooReaderWriter.getInstance().getChildren(zroot + Constants.ZRECOVERY, this); } catch (Exception e) { log.error("Failed to add log recovery watcher back", e); } } }); Credentials systemCreds = SystemCredentials.get(); watchers.add(new TabletGroupWatcher(this, new MetaDataStateStore(instance, systemCreds, this), null)); watchers.add(new TabletGroupWatcher(this, new RootTabletStateStore(instance, systemCreds, this), watchers.get(0))); watchers.add(new TabletGroupWatcher(this, new ZooTabletStateStore(new ZooStore(zroot)), watchers.get(1))); for (TabletGroupWatcher watcher : watchers) { watcher.start(); } // Once we are sure the upgrade is complete, we can safely allow fate use. waitForMetadataUpgrade.await(); try { final AgeOffStore<Master> store = new AgeOffStore<Master>(new org.apache.accumulo.fate.ZooStore<Master>(ZooUtil.getRoot(instance) + Constants.ZFATE, ZooReaderWriter.getRetryingInstance()), 1000 * 60 * 60 * 8); int threads = this.getConfiguration().getConfiguration().getCount(Property.MASTER_FATE_THREADPOOL_SIZE); fate = new Fate<Master>(this, store, threads); SimpleTimer.getInstance().schedule(new Runnable() { @Override public void run() { store.ageOff(); } }, 63000, 63000); } catch (KeeperException e) { throw new IOException(e); } catch (InterruptedException e) { throw new IOException(e); } Processor<Iface> processor = new Processor<Iface>(RpcWrapper.service(new MasterClientServiceHandler(this))); ServerAddress sa = TServerUtils.startServer(getSystemConfiguration(), hostname, Property.MASTER_CLIENTPORT, processor, "Master", "Master Client Service Handler", null, Property.MASTER_MINTHREADS, Property.MASTER_THREADCHECK, Property.GENERAL_MAX_MESSAGE_SIZE); clientService = sa.server; String address = sa.address.toString(); log.info("Setting master lock data to " + address); masterLock.replaceLockData(address.getBytes()); while (!clientService.isServing()) { UtilWaitThread.sleep(100); } while (clientService.isServing()) { UtilWaitThread.sleep(500); } log.info("Shutting down fate."); fate.shutdown(); final long deadline = System.currentTimeMillis() + MAX_CLEANUP_WAIT_TIME; statusThread.join(remaining(deadline)); // quit, even if the tablet servers somehow jam up and the watchers // don't stop for (TabletGroupWatcher watcher : watchers) { watcher.join(remaining(deadline)); } log.info("exiting"); } private long remaining(long deadline) { return Math.max(1, deadline - System.currentTimeMillis()); } public ZooLock getMasterLock() { return masterLock; } private static class MasterLockWatcher implements ZooLock.AsyncLockWatcher { boolean acquiredLock = false; boolean failedToAcquireLock = false; @Override public void lostLock(LockLossReason reason) { Halt.halt("Master lock in zookeeper lost (reason = " + reason + "), exiting!", -1); } @Override public void unableToMonitorLockNode(final Throwable e) { Halt.halt(-1, new Runnable() { @Override public void run() { log.fatal("No longer able to monitor master lock node", e); } }); } @Override public synchronized void acquiredLock() { log.debug("Acquired master lock"); if (acquiredLock || failedToAcquireLock) { Halt.halt("Zoolock in unexpected state AL " + acquiredLock + " " + failedToAcquireLock, -1); } acquiredLock = true; notifyAll(); } @Override public synchronized void failedToAcquireLock(Exception e) { log.warn("Failed to get master lock " + e); if (acquiredLock) { Halt.halt("Zoolock in unexpected state FAL " + acquiredLock + " " + failedToAcquireLock, -1); } failedToAcquireLock = true; notifyAll(); } public synchronized void waitForChange() { while (!acquiredLock && !failedToAcquireLock) { try { wait(); } catch (InterruptedException e) {} } } } private void getMasterLock(final String zMasterLoc) throws KeeperException, InterruptedException { log.info("trying to get master lock"); final String masterClientAddress = hostname + ":" + getSystemConfiguration().getPort(Property.MASTER_CLIENTPORT); while (true) { MasterLockWatcher masterLockWatcher = new MasterLockWatcher(); masterLock = new ZooLock(zMasterLoc); masterLock.lockAsync(masterLockWatcher, masterClientAddress.getBytes()); masterLockWatcher.waitForChange(); if (masterLockWatcher.acquiredLock) { break; } if (!masterLockWatcher.failedToAcquireLock) { throw new IllegalStateException("master lock in unknown state"); } masterLock.tryToCancelAsyncLockOrUnlock(); UtilWaitThread.sleep(TIME_TO_WAIT_BETWEEN_LOCK_CHECKS); } setMasterState(MasterState.HAVE_LOCK); } public static void main(String[] args) throws Exception { try { SecurityUtil.serverLogin(ServerConfiguration.getSiteConfiguration()); VolumeManager fs = VolumeManagerImpl.get(); ServerOpts opts = new ServerOpts(); opts.parseArgs("master", args); String hostname = opts.getAddress(); Instance instance = HdfsZooInstance.getInstance(); ServerConfiguration conf = new ServerConfiguration(instance); Accumulo.init(fs, conf, "master"); Master master = new Master(conf, fs, hostname); Accumulo.enableTracing(hostname, "master"); master.run(); } catch (Exception ex) { log.error("Unexpected exception, exiting", ex); System.exit(1); } } @Override public void update(LiveTServerSet current, Set<TServerInstance> deleted, Set<TServerInstance> added) { DeadServerList obit = new DeadServerList(ZooUtil.getRoot(instance) + Constants.ZDEADTSERVERS); if (added.size() > 0) { log.info("New servers: " + added); for (TServerInstance up : added) obit.delete(up.hostPort()); } for (TServerInstance dead : deleted) { String cause = "unexpected failure"; if (serversToShutdown.contains(dead)) cause = "clean shutdown"; // maybe an incorrect assumption if (!getMasterGoalState().equals(MasterGoalState.CLEAN_STOP)) obit.post(dead.hostPort(), cause); } Set<TServerInstance> unexpected = new HashSet<TServerInstance>(deleted); unexpected.removeAll(this.serversToShutdown); if (unexpected.size() > 0) { if (stillMaster() && !getMasterGoalState().equals(MasterGoalState.CLEAN_STOP)) { log.warn("Lost servers " + unexpected); } } serversToShutdown.removeAll(deleted); badServers.keySet().removeAll(deleted); // clear out any bad server with the same host/port as a new server synchronized (badServers) { cleanListByHostAndPort(badServers.keySet(), deleted, added); } synchronized (serversToShutdown) { cleanListByHostAndPort(serversToShutdown, deleted, added); } synchronized (migrations) { Iterator<Entry<KeyExtent,TServerInstance>> iter = migrations.entrySet().iterator(); while (iter.hasNext()) { Entry<KeyExtent,TServerInstance> entry = iter.next(); if (deleted.contains(entry.getValue())) { log.info("Canceling migration of " + entry.getKey() + " to " + entry.getValue()); iter.remove(); } } } nextEvent.event("There are now %d tablet servers", current.size()); } private static void cleanListByHostAndPort(Collection<TServerInstance> badServers, Set<TServerInstance> deleted, Set<TServerInstance> added) { Iterator<TServerInstance> badIter = badServers.iterator(); while (badIter.hasNext()) { TServerInstance bad = badIter.next(); for (TServerInstance add : added) { if (bad.hostPort().equals(add.hostPort())) { badIter.remove(); break; } } for (TServerInstance del : deleted) { if (bad.hostPort().equals(del.hostPort())) { badIter.remove(); break; } } } } @Override public void stateChanged(String tableId, TableState state) { nextEvent.event("Table state in zookeeper changed for %s to %s", tableId, state); } @Override public void initialize(Map<String,TableState> tableIdToStateMap) {} @Override public void sessionExpired() {} @Override public Set<String> onlineTables() { Set<String> result = new HashSet<String>(); if (getMasterState() != MasterState.NORMAL) { if (getMasterState() != MasterState.UNLOAD_METADATA_TABLETS) result.add(MetadataTable.ID); if (getMasterState() != MasterState.UNLOAD_ROOT_TABLET) result.add(RootTable.ID); return result; } TableManager manager = TableManager.getInstance(); for (String tableId : Tables.getIdToNameMap(instance).keySet()) { TableState state = manager.getTableState(tableId); if (state != null) { if (state == TableState.ONLINE) result.add(tableId); } } return result; } @Override public Set<TServerInstance> onlineTabletServers() { return tserverSet.getCurrentServers(); } @Override public Collection<MergeInfo> merges() { List<MergeInfo> result = new ArrayList<MergeInfo>(); for (String tableId : Tables.getIdToNameMap(instance).keySet()) { result.add(getMergeInfo(new Text(tableId))); } return result; } // recovers state from the persistent transaction to shutdown a server public void shutdownTServer(TServerInstance server) { nextEvent.event("Tablet Server shutdown requested for %s", server); serversToShutdown.add(server); } public EventCoordinator getEventCoordinator() { return nextEvent; } public Instance getInstance() { return this.instance; } public AccumuloConfiguration getSystemConfiguration() { return serverConfig.getConfiguration(); } public ServerConfiguration getConfiguration() { return serverConfig; } public VolumeManager getFileSystem() { return this.fs; } public void assignedTablet(KeyExtent extent) { if (extent.isMeta()) { if (getMasterState().equals(MasterState.UNLOAD_ROOT_TABLET)) { setMasterState(MasterState.UNLOAD_METADATA_TABLETS); } } if (extent.isRootTablet()) { // probably too late, but try anyhow if (getMasterState().equals(MasterState.STOP)) { setMasterState(MasterState.UNLOAD_ROOT_TABLET); } } } }
server/master/src/main/java/org/apache/accumulo/master/Master.java
/* * 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.master; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.apache.accumulo.core.Constants; import org.apache.accumulo.core.client.AccumuloException; import org.apache.accumulo.core.client.AccumuloSecurityException; import org.apache.accumulo.core.client.Connector; import org.apache.accumulo.core.client.Instance; import org.apache.accumulo.core.client.Scanner; import org.apache.accumulo.core.client.TableNotFoundException; import org.apache.accumulo.core.client.impl.Namespaces; import org.apache.accumulo.core.client.impl.Tables; import org.apache.accumulo.core.client.impl.ThriftTransportPool; import org.apache.accumulo.core.client.impl.thrift.TableOperation; import org.apache.accumulo.core.client.impl.thrift.TableOperationExceptionType; import org.apache.accumulo.core.client.impl.thrift.ThriftTableOperationException; import org.apache.accumulo.core.conf.AccumuloConfiguration; import org.apache.accumulo.core.conf.Property; import org.apache.accumulo.core.data.Key; import org.apache.accumulo.core.data.KeyExtent; import org.apache.accumulo.core.data.Value; import org.apache.accumulo.core.master.state.tables.TableState; import org.apache.accumulo.core.master.thrift.MasterClientService.Iface; import org.apache.accumulo.core.master.thrift.MasterClientService.Processor; import org.apache.accumulo.core.master.thrift.MasterGoalState; import org.apache.accumulo.core.master.thrift.MasterState; import org.apache.accumulo.core.master.thrift.TabletServerStatus; import org.apache.accumulo.core.metadata.MetadataTable; import org.apache.accumulo.core.metadata.RootTable; import org.apache.accumulo.core.metadata.schema.MetadataSchema.TabletsSection; import org.apache.accumulo.core.security.Authorizations; import org.apache.accumulo.core.security.Credentials; import org.apache.accumulo.core.security.NamespacePermission; import org.apache.accumulo.core.security.SecurityUtil; import org.apache.accumulo.core.security.TablePermission; import org.apache.accumulo.core.util.Daemon; import org.apache.accumulo.core.util.Pair; import org.apache.accumulo.core.util.UtilWaitThread; import org.apache.accumulo.core.zookeeper.ZooUtil; import org.apache.accumulo.fate.AgeOffStore; import org.apache.accumulo.fate.Fate; import org.apache.accumulo.fate.zookeeper.IZooReaderWriter; import org.apache.accumulo.fate.zookeeper.ZooLock.LockLossReason; import org.apache.accumulo.fate.zookeeper.ZooUtil.NodeExistsPolicy; import org.apache.accumulo.fate.zookeeper.ZooUtil.NodeMissingPolicy; import org.apache.accumulo.master.recovery.RecoveryManager; import org.apache.accumulo.master.state.TableCounts; import org.apache.accumulo.server.Accumulo; import org.apache.accumulo.server.ServerConstants; import org.apache.accumulo.server.ServerOpts; import org.apache.accumulo.server.client.HdfsZooInstance; import org.apache.accumulo.server.conf.ServerConfiguration; import org.apache.accumulo.server.fs.VolumeManager; import org.apache.accumulo.server.fs.VolumeManager.FileType; import org.apache.accumulo.server.fs.VolumeManagerImpl; import org.apache.accumulo.server.init.Initialize; import org.apache.accumulo.server.master.LiveTServerSet; import org.apache.accumulo.server.master.LiveTServerSet.TServerConnection; import org.apache.accumulo.server.master.balancer.DefaultLoadBalancer; import org.apache.accumulo.server.master.balancer.TabletBalancer; import org.apache.accumulo.server.master.state.CurrentState; import org.apache.accumulo.server.master.state.DeadServerList; import org.apache.accumulo.server.master.state.MergeInfo; import org.apache.accumulo.server.master.state.MergeState; import org.apache.accumulo.server.master.state.MetaDataStateStore; import org.apache.accumulo.server.master.state.RootTabletStateStore; import org.apache.accumulo.server.master.state.TServerInstance; import org.apache.accumulo.server.master.state.TabletLocationState; import org.apache.accumulo.server.master.state.TabletMigration; import org.apache.accumulo.server.master.state.TabletState; import org.apache.accumulo.server.master.state.ZooStore; import org.apache.accumulo.server.master.state.ZooTabletStateStore; import org.apache.accumulo.server.security.AuditedSecurityOperation; import org.apache.accumulo.server.security.SecurityOperation; import org.apache.accumulo.server.security.SystemCredentials; import org.apache.accumulo.server.security.handler.ZKPermHandler; import org.apache.accumulo.server.tables.TableManager; import org.apache.accumulo.server.tables.TableObserver; import org.apache.accumulo.server.util.DefaultMap; import org.apache.accumulo.server.util.Halt; import org.apache.accumulo.server.util.MetadataTableUtil; import org.apache.accumulo.server.util.RpcWrapper; import org.apache.accumulo.server.util.TServerUtils; import org.apache.accumulo.server.util.TServerUtils.ServerAddress; import org.apache.accumulo.server.util.time.SimpleTimer; import org.apache.accumulo.server.zookeeper.ZooLock; import org.apache.accumulo.server.zookeeper.ZooReaderWriter; import org.apache.accumulo.start.classloader.vfs.AccumuloVFSClassLoader; import org.apache.accumulo.start.classloader.vfs.ContextManager; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.DataInputBuffer; import org.apache.hadoop.io.DataOutputBuffer; import org.apache.hadoop.io.Text; import org.apache.log4j.Logger; import org.apache.thrift.TException; import org.apache.thrift.server.TServer; import org.apache.thrift.transport.TTransportException; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.data.Stat; import com.google.common.collect.Iterables; /** * The Master is responsible for assigning and balancing tablets to tablet servers. * * The master will also coordinate log recoveries and reports general status. */ public class Master implements LiveTServerSet.Listener, TableObserver, CurrentState { final static Logger log = Logger.getLogger(Master.class); final static int ONE_SECOND = 1000; final private static Text METADATA_TABLE_ID = new Text(MetadataTable.ID); final private static Text ROOT_TABLE_ID = new Text(RootTable.ID); final static long TIME_TO_WAIT_BETWEEN_SCANS = 60 * ONE_SECOND; final private static long TIME_BETWEEN_MIGRATION_CLEANUPS = 5 * 60 * ONE_SECOND; final static long WAIT_BETWEEN_ERRORS = ONE_SECOND; final private static long DEFAULT_WAIT_FOR_WATCHER = 10 * ONE_SECOND; final private static int MAX_CLEANUP_WAIT_TIME = ONE_SECOND; final private static int TIME_TO_WAIT_BETWEEN_LOCK_CHECKS = ONE_SECOND; final static int MAX_TSERVER_WORK_CHUNK = 5000; final private static int MAX_BAD_STATUS_COUNT = 3; final VolumeManager fs; final private Instance instance; final private String hostname; final LiveTServerSet tserverSet; final private List<TabletGroupWatcher> watchers = new ArrayList<TabletGroupWatcher>(); final SecurityOperation security; final Map<TServerInstance,AtomicInteger> badServers = Collections.synchronizedMap(new DefaultMap<TServerInstance,AtomicInteger>(new AtomicInteger())); final Set<TServerInstance> serversToShutdown = Collections.synchronizedSet(new HashSet<TServerInstance>()); final SortedMap<KeyExtent,TServerInstance> migrations = Collections.synchronizedSortedMap(new TreeMap<KeyExtent,TServerInstance>()); final EventCoordinator nextEvent = new EventCoordinator(); final private Object mergeLock = new Object(); RecoveryManager recoveryManager = null; ZooLock masterLock = null; private TServer clientService = null; TabletBalancer tabletBalancer; private MasterState state = MasterState.INITIAL; Fate<Master> fate; volatile SortedMap<TServerInstance,TabletServerStatus> tserverStatus = Collections.unmodifiableSortedMap(new TreeMap<TServerInstance,TabletServerStatus>()); synchronized MasterState getMasterState() { return state; } public boolean stillMaster() { return getMasterState() != MasterState.STOP; } static final boolean X = true; static final boolean _ = false; // @formatter:off static final boolean transitionOK[][] = { // INITIAL HAVE_LOCK SAFE_MODE NORMAL UNLOAD_META UNLOAD_ROOT STOP /* INITIAL */ {X, X, _, _, _, _, X}, /* HAVE_LOCK */ {_, X, X, X, _, _, X}, /* SAFE_MODE */ {_, _, X, X, X, _, X}, /* NORMAL */ {_, _, X, X, X, _, X}, /* UNLOAD_METADATA_TABLETS */ {_, _, X, X, X, X, X}, /* UNLOAD_ROOT_TABLET */ {_, _, _, X, X, X, X}, /* STOP */ {_, _, _, _, _, X, X}}; //@formatter:on synchronized void setMasterState(MasterState newState) { if (state.equals(newState)) return; if (!transitionOK[state.ordinal()][newState.ordinal()]) { log.error("Programmer error: master should not transition from " + state + " to " + newState); } MasterState oldState = state; state = newState; nextEvent.event("State changed from %s to %s", oldState, newState); if (newState == MasterState.STOP) { // Give the server a little time before shutdown so the client // thread requesting the stop can return SimpleTimer.getInstance().schedule(new Runnable() { @Override public void run() { // This frees the main thread and will cause the master to exit clientService.stop(); Master.this.nextEvent.event("stopped event loop"); } }, 100l, 1000l); } if (oldState != newState && (newState == MasterState.HAVE_LOCK)) { upgradeZookeeper(); } if (oldState != newState && (newState == MasterState.NORMAL)) { upgradeMetadata(); } } private void moveRootTabletToRootTable(IZooReaderWriter zoo) throws Exception { String dirZPath = ZooUtil.getRoot(instance) + RootTable.ZROOT_TABLET_PATH; if (!zoo.exists(dirZPath)) { Path oldPath = fs.getFullPath(FileType.TABLE, "/" + MetadataTable.ID + "/root_tablet"); if (fs.exists(oldPath)) { String newPath = fs.choose(ServerConstants.getTablesDirs()) + "/" + RootTable.ID; fs.mkdirs(new Path(newPath)); if (!fs.rename(oldPath, new Path(newPath))) { throw new IOException("Failed to move root tablet from " + oldPath + " to " + newPath); } log.info("Upgrade renamed " + oldPath + " to " + newPath); } Path location = null; for (String basePath : ServerConstants.getTablesDirs()) { Path path = new Path(basePath + "/" + RootTable.ID + RootTable.ROOT_TABLET_LOCATION); if (fs.exists(path)) { if (location != null) { throw new IllegalStateException("Root table at multiple locations " + location + " " + path); } location = path; } } if (location == null) throw new IllegalStateException("Failed to find root tablet"); log.info("Upgrade setting root table location in zookeeper " + location); zoo.putPersistentData(dirZPath, location.toString().getBytes(), NodeExistsPolicy.FAIL); } } private boolean haveUpgradedZooKeeper = false; private void upgradeZookeeper() { // 1.5.1 and 1.6.0 both do some state checking after obtaining the zoolock for the // monitor and before starting up. It's not tied to the data version at all (and would // introduce unnecessary complexity to try to make the master do it), but be aware // that the master is not the only thing that may alter zookeeper before starting. if (Accumulo.getAccumuloPersistentVersion(fs) == ServerConstants.PREV_DATA_VERSION) { // This Master hasn't started Fate yet, so any outstanding transactions must be from before the upgrade. // Change to Guava's Verify once we use Guava 17. if (null != fate) { throw new IllegalStateException("Access to Fate should not have been initialized prior to the Master transitioning to active. Please save all logs and file a bug."); } Accumulo.abortIfFateTransactions(); try { log.info("Upgrading zookeeper"); IZooReaderWriter zoo = ZooReaderWriter.getInstance(); // create initial namespaces String namespaces = ZooUtil.getRoot(instance) + Constants.ZNAMESPACES; zoo.putPersistentData(namespaces, new byte[0], NodeExistsPolicy.SKIP); for (Pair<String,String> namespace : Iterables.concat( Collections.singleton(new Pair<String,String>(Namespaces.ACCUMULO_NAMESPACE, Namespaces.ACCUMULO_NAMESPACE_ID)), Collections.singleton(new Pair<String,String>(Namespaces.DEFAULT_NAMESPACE, Namespaces.DEFAULT_NAMESPACE_ID)))) { String ns = namespace.getFirst(); String id = namespace.getSecond(); log.debug("Upgrade creating namespace \"" + ns + "\" (ID: " + id + ")"); if (!Namespaces.exists(instance, id)) TableManager.prepareNewNamespaceState(instance.getInstanceID(), id, ns, NodeExistsPolicy.SKIP); } // create root table log.debug("Upgrade creating table " + RootTable.NAME + " (ID: " + RootTable.ID + ")"); TableManager.prepareNewTableState(instance.getInstanceID(), RootTable.ID, Namespaces.ACCUMULO_NAMESPACE_ID, RootTable.NAME, TableState.ONLINE, NodeExistsPolicy.SKIP); Initialize.initMetadataConfig(RootTable.ID); // ensure root user can flush root table security.grantTablePermission(SystemCredentials.get().toThrift(instance), security.getRootUsername(), RootTable.ID, TablePermission.ALTER_TABLE, Namespaces.ACCUMULO_NAMESPACE_ID); // put existing tables in the correct namespaces String tables = ZooUtil.getRoot(instance) + Constants.ZTABLES; for (String tableId : zoo.getChildren(tables)) { String targetNamespace = (MetadataTable.ID.equals(tableId) || RootTable.ID.equals(tableId)) ? Namespaces.ACCUMULO_NAMESPACE_ID : Namespaces.DEFAULT_NAMESPACE_ID; log.debug("Upgrade moving table " + new String(zoo.getData(tables + "/" + tableId + Constants.ZTABLE_NAME, null), Constants.UTF8) + " (ID: " + tableId + ") into namespace with ID " + targetNamespace); zoo.putPersistentData(tables + "/" + tableId + Constants.ZTABLE_NAMESPACE, targetNamespace.getBytes(Constants.UTF8), NodeExistsPolicy.SKIP); } // rename metadata table log.debug("Upgrade renaming table " + MetadataTable.OLD_NAME + " (ID: " + MetadataTable.ID + ") to " + MetadataTable.NAME); zoo.putPersistentData(tables + "/" + MetadataTable.ID + Constants.ZTABLE_NAME, Tables.qualify(MetadataTable.NAME).getSecond().getBytes(Constants.UTF8), NodeExistsPolicy.OVERWRITE); moveRootTabletToRootTable(zoo); // add system namespace permissions to existing users ZKPermHandler perm = new ZKPermHandler(); perm.initialize(instance.getInstanceID(), true); String users = ZooUtil.getRoot(instance) + "/users"; for (String user : zoo.getChildren(users)) { zoo.putPersistentData(users + "/" + user + "/Namespaces", new byte[0], NodeExistsPolicy.SKIP); perm.grantNamespacePermission(user, Namespaces.ACCUMULO_NAMESPACE_ID, NamespacePermission.READ); } perm.grantNamespacePermission("root", Namespaces.ACCUMULO_NAMESPACE_ID, NamespacePermission.ALTER_TABLE); haveUpgradedZooKeeper = true; } catch (Exception ex) { log.fatal("Error performing upgrade", ex); System.exit(1); } } } private final AtomicBoolean upgradeMetadataRunning = new AtomicBoolean(false); private final CountDownLatch waitForMetadataUpgrade = new CountDownLatch(1); private final ServerConfiguration serverConfig; private void upgradeMetadata() { // we make sure we're only doing the rest of this method once so that we can signal to other threads that an upgrade wasn't needed. if (upgradeMetadataRunning.compareAndSet(false, true)) { final int accumuloPersistentVersion = Accumulo.getAccumuloPersistentVersion(fs); if (accumuloPersistentVersion == ServerConstants.TWO_VERSIONS_AGO || accumuloPersistentVersion == ServerConstants.PREV_DATA_VERSION) { // sanity check that we passed the Fate verification prior to ZooKeeper upgrade, and that Fate still hasn't been started. // Change both to use Guava's Verify once we use Guava 17. if (!haveUpgradedZooKeeper) { throw new IllegalStateException("We should only attempt to upgrade Accumulo's !METADATA table if we've already upgraded ZooKeeper. Please save all logs and file a bug."); } if (null != fate) { throw new IllegalStateException("Access to Fate should not have been initialized prior to the Master finishing upgrades. Please save all logs and file a bug."); } Runnable upgradeTask = new Runnable() { @Override public void run() { try { log.info("Starting to upgrade !METADATA table."); MetadataTableUtil.moveMetaDeleteMarkers(instance, SystemCredentials.get()); log.info("Updating persistent data version."); Accumulo.updateAccumuloVersion(fs, accumuloPersistentVersion); log.info("Upgrade complete"); waitForMetadataUpgrade.countDown(); } catch (Exception ex) { log.fatal("Error performing upgrade", ex); System.exit(1); } } }; // need to run this in a separate thread because a lock is held that prevents metadata tablets from being assigned and this task writes to the // metadata table new Thread(upgradeTask).start(); } else { waitForMetadataUpgrade.countDown(); } } } private int assignedOrHosted(Text tableId) { int result = 0; for (TabletGroupWatcher watcher : watchers) { TableCounts count = watcher.getStats(tableId); result += count.hosted() + count.assigned(); } return result; } private int totalAssignedOrHosted() { int result = 0; for (TabletGroupWatcher watcher : watchers) { for (TableCounts counts : watcher.getStats().values()) { result += counts.assigned() + counts.hosted(); } } return result; } private int nonMetaDataTabletsAssignedOrHosted() { return totalAssignedOrHosted() - assignedOrHosted(new Text(MetadataTable.ID)) - assignedOrHosted(new Text(RootTable.ID)); } private int notHosted() { int result = 0; for (TabletGroupWatcher watcher : watchers) { for (TableCounts counts : watcher.getStats().values()) { result += counts.assigned() + counts.assignedToDeadServers(); } } return result; } // The number of unassigned tablets that should be assigned: displayed on the monitor page int displayUnassigned() { int result = 0; switch (getMasterState()) { case NORMAL: // Count offline tablets for online tables for (TabletGroupWatcher watcher : watchers) { TableManager manager = TableManager.getInstance(); for (Entry<Text,TableCounts> entry : watcher.getStats().entrySet()) { Text tableId = entry.getKey(); TableCounts counts = entry.getValue(); TableState tableState = manager.getTableState(tableId.toString()); if (tableState != null && tableState.equals(TableState.ONLINE)) { result += counts.unassigned() + counts.assignedToDeadServers() + counts.assigned(); } } } break; case SAFE_MODE: // Count offline tablets for the metadata table for (TabletGroupWatcher watcher : watchers) { result += watcher.getStats(METADATA_TABLE_ID).unassigned(); } break; case UNLOAD_METADATA_TABLETS: case UNLOAD_ROOT_TABLET: for (TabletGroupWatcher watcher : watchers) { result += watcher.getStats(METADATA_TABLE_ID).unassigned(); } break; default: break; } return result; } public void mustBeOnline(final String tableId) throws ThriftTableOperationException { Tables.clearCache(instance); if (!Tables.getTableState(instance, tableId).equals(TableState.ONLINE)) throw new ThriftTableOperationException(tableId, null, TableOperation.MERGE, TableOperationExceptionType.OFFLINE, "table is not online"); } public Connector getConnector() throws AccumuloException, AccumuloSecurityException { return instance.getConnector(SystemCredentials.get().getPrincipal(), SystemCredentials.get().getToken()); } private Master(ServerConfiguration config, VolumeManager fs, String hostname) throws IOException { this.serverConfig = config; this.instance = config.getInstance(); this.fs = fs; this.hostname = hostname; AccumuloConfiguration aconf = serverConfig.getConfiguration(); log.info("Version " + Constants.VERSION); log.info("Instance " + instance.getInstanceID()); ThriftTransportPool.getInstance().setIdleTime(aconf.getTimeInMillis(Property.GENERAL_RPC_TIMEOUT)); security = AuditedSecurityOperation.getInstance(); tserverSet = new LiveTServerSet(instance, config.getConfiguration(), this); this.tabletBalancer = aconf.instantiateClassProperty(Property.MASTER_TABLET_BALANCER, TabletBalancer.class, new DefaultLoadBalancer()); this.tabletBalancer.init(serverConfig); try { AccumuloVFSClassLoader.getContextManager().setContextConfig(new ContextManager.DefaultContextsConfig(new Iterable<Entry<String,String>>() { @Override public Iterator<Entry<String,String>> iterator() { return getSystemConfiguration().iterator(); } })); } catch (IOException e) { throw new RuntimeException(e); } } public TServerConnection getConnection(TServerInstance server) { return tserverSet.getConnection(server); } public MergeInfo getMergeInfo(Text tableId) { synchronized (mergeLock) { try { String path = ZooUtil.getRoot(instance.getInstanceID()) + Constants.ZTABLES + "/" + tableId.toString() + "/merge"; if (!ZooReaderWriter.getInstance().exists(path)) return new MergeInfo(); byte[] data = ZooReaderWriter.getInstance().getData(path, new Stat()); DataInputBuffer in = new DataInputBuffer(); in.reset(data, data.length); MergeInfo info = new MergeInfo(); info.readFields(in); return info; } catch (KeeperException.NoNodeException ex) { log.info("Error reading merge state, it probably just finished"); return new MergeInfo(); } catch (Exception ex) { log.warn("Unexpected error reading merge state", ex); return new MergeInfo(); } } } public void setMergeState(MergeInfo info, MergeState state) throws IOException, KeeperException, InterruptedException { synchronized (mergeLock) { String path = ZooUtil.getRoot(instance.getInstanceID()) + Constants.ZTABLES + "/" + info.getExtent().getTableId().toString() + "/merge"; info.setState(state); if (state.equals(MergeState.NONE)) { ZooReaderWriter.getInstance().recursiveDelete(path, NodeMissingPolicy.SKIP); } else { DataOutputBuffer out = new DataOutputBuffer(); try { info.write(out); } catch (IOException ex) { throw new RuntimeException("Unlikely", ex); } ZooReaderWriter.getInstance().putPersistentData(path, out.getData(), state.equals(MergeState.STARTED) ? ZooUtil.NodeExistsPolicy.FAIL : ZooUtil.NodeExistsPolicy.OVERWRITE); } mergeLock.notifyAll(); } nextEvent.event("Merge state of %s set to %s", info.getExtent(), state); } public void clearMergeState(Text tableId) throws IOException, KeeperException, InterruptedException { synchronized (mergeLock) { String path = ZooUtil.getRoot(instance.getInstanceID()) + Constants.ZTABLES + "/" + tableId.toString() + "/merge"; ZooReaderWriter.getInstance().recursiveDelete(path, NodeMissingPolicy.SKIP); mergeLock.notifyAll(); } nextEvent.event("Merge state of %s cleared", tableId); } void setMasterGoalState(MasterGoalState state) { try { ZooReaderWriter.getInstance().putPersistentData(ZooUtil.getRoot(instance) + Constants.ZMASTER_GOAL_STATE, state.name().getBytes(), NodeExistsPolicy.OVERWRITE); } catch (Exception ex) { log.error("Unable to set master goal state in zookeeper"); } } MasterGoalState getMasterGoalState() { while (true) try { byte[] data = ZooReaderWriter.getInstance().getData(ZooUtil.getRoot(instance) + Constants.ZMASTER_GOAL_STATE, null); return MasterGoalState.valueOf(new String(data)); } catch (Exception e) { log.error("Problem getting real goal state: " + e); UtilWaitThread.sleep(1000); } } public boolean hasCycled(long time) { for (TabletGroupWatcher watcher : watchers) { if (watcher.stats.lastScanFinished() < time) return false; } return true; } public void clearMigrations(String tableId) { synchronized (migrations) { Iterator<KeyExtent> iterator = migrations.keySet().iterator(); while (iterator.hasNext()) { KeyExtent extent = iterator.next(); if (extent.getTableId().toString().equals(tableId)) { iterator.remove(); } } } } static enum TabletGoalState { HOSTED, UNASSIGNED, DELETED }; TabletGoalState getSystemGoalState(TabletLocationState tls) { switch (getMasterState()) { case NORMAL: return TabletGoalState.HOSTED; case HAVE_LOCK: // fall-through intended case INITIAL: // fall-through intended case SAFE_MODE: if (tls.extent.isMeta()) return TabletGoalState.HOSTED; return TabletGoalState.UNASSIGNED; case UNLOAD_METADATA_TABLETS: if (tls.extent.isRootTablet()) return TabletGoalState.HOSTED; return TabletGoalState.UNASSIGNED; case UNLOAD_ROOT_TABLET: return TabletGoalState.UNASSIGNED; case STOP: return TabletGoalState.UNASSIGNED; default: throw new IllegalStateException("Unknown Master State"); } } TabletGoalState getTableGoalState(KeyExtent extent) { TableState tableState = TableManager.getInstance().getTableState(extent.getTableId().toString()); if (tableState == null) return TabletGoalState.DELETED; switch (tableState) { case DELETING: return TabletGoalState.DELETED; case OFFLINE: case NEW: return TabletGoalState.UNASSIGNED; default: return TabletGoalState.HOSTED; } } TabletGoalState getGoalState(TabletLocationState tls, MergeInfo mergeInfo) { KeyExtent extent = tls.extent; // Shutting down? TabletGoalState state = getSystemGoalState(tls); if (state == TabletGoalState.HOSTED) { if (tls.current != null && serversToShutdown.contains(tls.current)) { return TabletGoalState.UNASSIGNED; } // Handle merge transitions if (mergeInfo.getExtent() != null) { log.debug("mergeInfo overlaps: " + extent + " " + mergeInfo.overlaps(extent)); if (mergeInfo.overlaps(extent)) { switch (mergeInfo.getState()) { case NONE: case COMPLETE: break; case STARTED: case SPLITTING: return TabletGoalState.HOSTED; case WAITING_FOR_CHOPPED: if (tls.getState(onlineTabletServers()).equals(TabletState.HOSTED)) { if (tls.chopped) return TabletGoalState.UNASSIGNED; } else { if (tls.chopped && tls.walogs.isEmpty()) return TabletGoalState.UNASSIGNED; } return TabletGoalState.HOSTED; case WAITING_FOR_OFFLINE: case MERGING: return TabletGoalState.UNASSIGNED; } } } // taking table offline? state = getTableGoalState(extent); if (state == TabletGoalState.HOSTED) { // Maybe this tablet needs to be migrated TServerInstance dest = migrations.get(extent); if (dest != null && tls.current != null && !dest.equals(tls.current)) { return TabletGoalState.UNASSIGNED; } } } return state; } private class MigrationCleanupThread extends Daemon { @Override public void run() { setName("Migration Cleanup Thread"); while (stillMaster()) { if (!migrations.isEmpty()) { try { cleanupMutations(); } catch (Exception ex) { log.error("Error cleaning up migrations", ex); } } UtilWaitThread.sleep(TIME_BETWEEN_MIGRATION_CLEANUPS); } } // If a migrating tablet splits, and the tablet dies before sending the // master a message, the migration will refer to a non-existing tablet, // so it can never complete. Periodically scan the metadata table and // remove any migrating tablets that no longer exist. private void cleanupMutations() throws AccumuloException, AccumuloSecurityException, TableNotFoundException { Connector connector = getConnector(); Scanner scanner = connector.createScanner(MetadataTable.NAME, Authorizations.EMPTY); TabletsSection.TabletColumnFamily.PREV_ROW_COLUMN.fetch(scanner); Set<KeyExtent> found = new HashSet<KeyExtent>(); for (Entry<Key,Value> entry : scanner) { KeyExtent extent = new KeyExtent(entry.getKey().getRow(), entry.getValue()); if (migrations.containsKey(extent)) { found.add(extent); } } migrations.keySet().retainAll(found); } } private class StatusThread extends Daemon { @Override public void run() { setName("Status Thread"); EventCoordinator.Listener eventListener = nextEvent.getListener(); while (stillMaster()) { long wait = DEFAULT_WAIT_FOR_WATCHER; try { switch (getMasterGoalState()) { case NORMAL: setMasterState(MasterState.NORMAL); break; case SAFE_MODE: if (getMasterState() == MasterState.NORMAL) { setMasterState(MasterState.SAFE_MODE); } if (getMasterState() == MasterState.HAVE_LOCK) { setMasterState(MasterState.SAFE_MODE); } break; case CLEAN_STOP: switch (getMasterState()) { case NORMAL: setMasterState(MasterState.SAFE_MODE); break; case SAFE_MODE: { int count = nonMetaDataTabletsAssignedOrHosted(); log.debug(String.format("There are %d non-metadata tablets assigned or hosted", count)); if (count == 0) setMasterState(MasterState.UNLOAD_METADATA_TABLETS); } break; case UNLOAD_METADATA_TABLETS: { int count = assignedOrHosted(METADATA_TABLE_ID); log.debug(String.format("There are %d metadata tablets assigned or hosted", count)); if (count == 0) setMasterState(MasterState.UNLOAD_ROOT_TABLET); } break; case UNLOAD_ROOT_TABLET: { int count = assignedOrHosted(METADATA_TABLE_ID); if (count > 0) { log.debug(String.format("%d metadata tablets online", count)); setMasterState(MasterState.UNLOAD_ROOT_TABLET); } int root_count = assignedOrHosted(ROOT_TABLE_ID); if (root_count > 0) log.debug("The root tablet is still assigned or hosted"); if (count + root_count == 0) { Set<TServerInstance> currentServers = tserverSet.getCurrentServers(); log.debug("stopping " + currentServers.size() + " tablet servers"); for (TServerInstance server : currentServers) { try { serversToShutdown.add(server); tserverSet.getConnection(server).fastHalt(masterLock); } catch (TException e) { // its probably down, and we don't care } finally { tserverSet.remove(server); } } if (currentServers.size() == 0) setMasterState(MasterState.STOP); } } break; default: break; } } wait = updateStatus(); eventListener.waitForEvents(wait); } catch (Throwable t) { log.error("Error balancing tablets", t); UtilWaitThread.sleep(WAIT_BETWEEN_ERRORS); } } } private long updateStatus() throws AccumuloException, AccumuloSecurityException, TableNotFoundException { tserverStatus = Collections.synchronizedSortedMap(gatherTableInformation()); checkForHeldServer(tserverStatus); if (!badServers.isEmpty()) { log.debug("not balancing because the balance information is out-of-date " + badServers.keySet()); } else if (notHosted() > 0) { log.debug("not balancing because there are unhosted tablets"); } else if (getMasterGoalState() == MasterGoalState.CLEAN_STOP) { log.debug("not balancing because the master is attempting to stop cleanly"); } else if (!serversToShutdown.isEmpty()) { log.debug("not balancing while shutting down servers " + serversToShutdown); } else { return balanceTablets(); } return DEFAULT_WAIT_FOR_WATCHER; } private void checkForHeldServer(SortedMap<TServerInstance,TabletServerStatus> tserverStatus) { TServerInstance instance = null; int crazyHoldTime = 0; int someHoldTime = 0; final long maxWait = getSystemConfiguration().getTimeInMillis(Property.TSERV_HOLD_TIME_SUICIDE); for (Entry<TServerInstance,TabletServerStatus> entry : tserverStatus.entrySet()) { if (entry.getValue().getHoldTime() > 0) { someHoldTime++; if (entry.getValue().getHoldTime() > maxWait) { instance = entry.getKey(); crazyHoldTime++; } } } if (crazyHoldTime == 1 && someHoldTime == 1 && tserverStatus.size() > 1) { log.warn("Tablet server " + instance + " exceeded maximum hold time: attempting to kill it"); try { TServerConnection connection = tserverSet.getConnection(instance); if (connection != null) connection.fastHalt(masterLock); } catch (TException e) { log.error(e, e); } tserverSet.remove(instance); } } private long balanceTablets() { List<TabletMigration> migrationsOut = new ArrayList<TabletMigration>(); Set<KeyExtent> migrationsCopy = new HashSet<KeyExtent>(); synchronized (migrations) { migrationsCopy.addAll(migrations.keySet()); } long wait = tabletBalancer.balance(Collections.unmodifiableSortedMap(tserverStatus), Collections.unmodifiableSet(migrationsCopy), migrationsOut); for (TabletMigration m : TabletBalancer.checkMigrationSanity(tserverStatus.keySet(), migrationsOut)) { if (migrations.containsKey(m.tablet)) { log.warn("balancer requested migration more than once, skipping " + m); continue; } migrations.put(m.tablet, m.newServer); log.debug("migration " + m); } if (migrationsOut.size() > 0) { nextEvent.event("Migrating %d more tablets, %d total", migrationsOut.size(), migrations.size()); } return wait; } } private SortedMap<TServerInstance,TabletServerStatus> gatherTableInformation() { long start = System.currentTimeMillis(); SortedMap<TServerInstance,TabletServerStatus> result = new TreeMap<TServerInstance,TabletServerStatus>(); Set<TServerInstance> currentServers = tserverSet.getCurrentServers(); for (TServerInstance server : currentServers) { try { Thread t = Thread.currentThread(); String oldName = t.getName(); try { t.setName("Getting status from " + server); TServerConnection connection = tserverSet.getConnection(server); if (connection == null) throw new IOException("No connection to " + server); TabletServerStatus status = connection.getTableMap(false); result.put(server, status); } finally { t.setName(oldName); } } catch (Exception ex) { log.error("unable to get tablet server status " + server + " " + ex.toString()); log.debug("unable to get tablet server status " + server, ex); if (badServers.get(server).incrementAndGet() > MAX_BAD_STATUS_COUNT) { log.warn("attempting to stop " + server); try { TServerConnection connection = tserverSet.getConnection(server); if (connection != null) connection.halt(masterLock); } catch (TTransportException e) { // ignore: it's probably down } catch (Exception e) { log.info("error talking to troublesome tablet server ", e); } badServers.remove(server); tserverSet.remove(server); } } } synchronized (badServers) { badServers.keySet().retainAll(currentServers); badServers.keySet().removeAll(result.keySet()); } log.debug(String.format("Finished gathering information from %d servers in %.2f seconds", result.size(), (System.currentTimeMillis() - start) / 1000.)); return result; } public void run() throws IOException, InterruptedException, KeeperException { final String zroot = ZooUtil.getRoot(instance); getMasterLock(zroot + Constants.ZMASTER_LOCK); recoveryManager = new RecoveryManager(this); TableManager.getInstance().addObserver(this); StatusThread statusThread = new StatusThread(); statusThread.start(); MigrationCleanupThread migrationCleanupThread = new MigrationCleanupThread(); migrationCleanupThread.start(); tserverSet.startListeningForTabletServerChanges(); ZooReaderWriter.getInstance().getChildren(zroot + Constants.ZRECOVERY, new Watcher() { @Override public void process(WatchedEvent event) { nextEvent.event("Noticed recovery changes", event.getType()); try { // watcher only fires once, add it back ZooReaderWriter.getInstance().getChildren(zroot + Constants.ZRECOVERY, this); } catch (Exception e) { log.error("Failed to add log recovery watcher back", e); } } }); Credentials systemCreds = SystemCredentials.get(); watchers.add(new TabletGroupWatcher(this, new MetaDataStateStore(instance, systemCreds, this), null)); watchers.add(new TabletGroupWatcher(this, new RootTabletStateStore(instance, systemCreds, this), watchers.get(0))); watchers.add(new TabletGroupWatcher(this, new ZooTabletStateStore(new ZooStore(zroot)), watchers.get(1))); for (TabletGroupWatcher watcher : watchers) { watcher.start(); } // Once we are sure the upgrade is complete, we can safely allow fate use. waitForMetadataUpgrade.await(); try { final AgeOffStore<Master> store = new AgeOffStore<Master>(new org.apache.accumulo.fate.ZooStore<Master>(ZooUtil.getRoot(instance) + Constants.ZFATE, ZooReaderWriter.getRetryingInstance()), 1000 * 60 * 60 * 8); int threads = this.getConfiguration().getConfiguration().getCount(Property.MASTER_FATE_THREADPOOL_SIZE); fate = new Fate<Master>(this, store, threads); SimpleTimer.getInstance().schedule(new Runnable() { @Override public void run() { store.ageOff(); } }, 63000, 63000); } catch (KeeperException e) { throw new IOException(e); } catch (InterruptedException e) { throw new IOException(e); } Processor<Iface> processor = new Processor<Iface>(RpcWrapper.service(new MasterClientServiceHandler(this))); ServerAddress sa = TServerUtils.startServer(getSystemConfiguration(), hostname, Property.MASTER_CLIENTPORT, processor, "Master", "Master Client Service Handler", null, Property.MASTER_MINTHREADS, Property.MASTER_THREADCHECK, Property.GENERAL_MAX_MESSAGE_SIZE); clientService = sa.server; String address = sa.address.toString(); log.info("Setting master lock data to " + address); masterLock.replaceLockData(address.getBytes()); while (!clientService.isServing()) { UtilWaitThread.sleep(100); } while (clientService.isServing()) { UtilWaitThread.sleep(500); } log.info("Shutting down fate."); fate.shutdown(); final long deadline = System.currentTimeMillis() + MAX_CLEANUP_WAIT_TIME; statusThread.join(remaining(deadline)); // quit, even if the tablet servers somehow jam up and the watchers // don't stop for (TabletGroupWatcher watcher : watchers) { watcher.join(remaining(deadline)); } log.info("exiting"); } private long remaining(long deadline) { return Math.max(1, deadline - System.currentTimeMillis()); } public ZooLock getMasterLock() { return masterLock; } private static class MasterLockWatcher implements ZooLock.AsyncLockWatcher { boolean acquiredLock = false; boolean failedToAcquireLock = false; @Override public void lostLock(LockLossReason reason) { Halt.halt("Master lock in zookeeper lost (reason = " + reason + "), exiting!", -1); } @Override public void unableToMonitorLockNode(final Throwable e) { Halt.halt(-1, new Runnable() { @Override public void run() { log.fatal("No longer able to monitor master lock node", e); } }); } @Override public synchronized void acquiredLock() { log.debug("Acquired master lock"); if (acquiredLock || failedToAcquireLock) { Halt.halt("Zoolock in unexpected state AL " + acquiredLock + " " + failedToAcquireLock, -1); } acquiredLock = true; notifyAll(); } @Override public synchronized void failedToAcquireLock(Exception e) { log.warn("Failed to get master lock " + e); if (acquiredLock) { Halt.halt("Zoolock in unexpected state FAL " + acquiredLock + " " + failedToAcquireLock, -1); } failedToAcquireLock = true; notifyAll(); } public synchronized void waitForChange() { while (!acquiredLock && !failedToAcquireLock) { try { wait(); } catch (InterruptedException e) {} } } } private void getMasterLock(final String zMasterLoc) throws KeeperException, InterruptedException { log.info("trying to get master lock"); final String masterClientAddress = hostname + ":" + getSystemConfiguration().getPort(Property.MASTER_CLIENTPORT); while (true) { MasterLockWatcher masterLockWatcher = new MasterLockWatcher(); masterLock = new ZooLock(zMasterLoc); masterLock.lockAsync(masterLockWatcher, masterClientAddress.getBytes()); masterLockWatcher.waitForChange(); if (masterLockWatcher.acquiredLock) { break; } if (!masterLockWatcher.failedToAcquireLock) { throw new IllegalStateException("master lock in unknown state"); } masterLock.tryToCancelAsyncLockOrUnlock(); UtilWaitThread.sleep(TIME_TO_WAIT_BETWEEN_LOCK_CHECKS); } setMasterState(MasterState.HAVE_LOCK); } public static void main(String[] args) throws Exception { try { SecurityUtil.serverLogin(ServerConfiguration.getSiteConfiguration()); VolumeManager fs = VolumeManagerImpl.get(); ServerOpts opts = new ServerOpts(); opts.parseArgs("master", args); String hostname = opts.getAddress(); Instance instance = HdfsZooInstance.getInstance(); ServerConfiguration conf = new ServerConfiguration(instance); Accumulo.init(fs, conf, "master"); Master master = new Master(conf, fs, hostname); Accumulo.enableTracing(hostname, "master"); master.run(); } catch (Exception ex) { log.error("Unexpected exception, exiting", ex); System.exit(1); } } @Override public void update(LiveTServerSet current, Set<TServerInstance> deleted, Set<TServerInstance> added) { DeadServerList obit = new DeadServerList(ZooUtil.getRoot(instance) + Constants.ZDEADTSERVERS); if (added.size() > 0) { log.info("New servers: " + added); for (TServerInstance up : added) obit.delete(up.hostPort()); } for (TServerInstance dead : deleted) { String cause = "unexpected failure"; if (serversToShutdown.contains(dead)) cause = "clean shutdown"; // maybe an incorrect assumption if (!getMasterGoalState().equals(MasterGoalState.CLEAN_STOP)) obit.post(dead.hostPort(), cause); } Set<TServerInstance> unexpected = new HashSet<TServerInstance>(deleted); unexpected.removeAll(this.serversToShutdown); if (unexpected.size() > 0) { if (stillMaster() && !getMasterGoalState().equals(MasterGoalState.CLEAN_STOP)) { log.warn("Lost servers " + unexpected); } } serversToShutdown.removeAll(deleted); badServers.keySet().removeAll(deleted); // clear out any bad server with the same host/port as a new server synchronized (badServers) { cleanListByHostAndPort(badServers.keySet(), deleted, added); } synchronized (serversToShutdown) { cleanListByHostAndPort(serversToShutdown, deleted, added); } synchronized (migrations) { Iterator<Entry<KeyExtent,TServerInstance>> iter = migrations.entrySet().iterator(); while (iter.hasNext()) { Entry<KeyExtent,TServerInstance> entry = iter.next(); if (deleted.contains(entry.getValue())) { log.info("Canceling migration of " + entry.getKey() + " to " + entry.getValue()); iter.remove(); } } } nextEvent.event("There are now %d tablet servers", current.size()); } private static void cleanListByHostAndPort(Collection<TServerInstance> badServers, Set<TServerInstance> deleted, Set<TServerInstance> added) { Iterator<TServerInstance> badIter = badServers.iterator(); while (badIter.hasNext()) { TServerInstance bad = badIter.next(); for (TServerInstance add : added) { if (bad.hostPort().equals(add.hostPort())) { badIter.remove(); break; } } for (TServerInstance del : deleted) { if (bad.hostPort().equals(del.hostPort())) { badIter.remove(); break; } } } } @Override public void stateChanged(String tableId, TableState state) { nextEvent.event("Table state in zookeeper changed for %s to %s", tableId, state); } @Override public void initialize(Map<String,TableState> tableIdToStateMap) {} @Override public void sessionExpired() {} @Override public Set<String> onlineTables() { Set<String> result = new HashSet<String>(); if (getMasterState() != MasterState.NORMAL) { if (getMasterState() != MasterState.UNLOAD_METADATA_TABLETS) result.add(MetadataTable.ID); if (getMasterState() != MasterState.UNLOAD_ROOT_TABLET) result.add(RootTable.ID); return result; } TableManager manager = TableManager.getInstance(); for (String tableId : Tables.getIdToNameMap(instance).keySet()) { TableState state = manager.getTableState(tableId); if (state != null) { if (state == TableState.ONLINE) result.add(tableId); } } return result; } @Override public Set<TServerInstance> onlineTabletServers() { return tserverSet.getCurrentServers(); } @Override public Collection<MergeInfo> merges() { List<MergeInfo> result = new ArrayList<MergeInfo>(); for (String tableId : Tables.getIdToNameMap(instance).keySet()) { result.add(getMergeInfo(new Text(tableId))); } return result; } // recovers state from the persistent transaction to shutdown a server public void shutdownTServer(TServerInstance server) { nextEvent.event("Tablet Server shutdown requested for %s", server); serversToShutdown.add(server); } public EventCoordinator getEventCoordinator() { return nextEvent; } public Instance getInstance() { return this.instance; } public AccumuloConfiguration getSystemConfiguration() { return serverConfig.getConfiguration(); } public ServerConfiguration getConfiguration() { return serverConfig; } public VolumeManager getFileSystem() { return this.fs; } public void assignedTablet(KeyExtent extent) { if (extent.isMeta()) { if (getMasterState().equals(MasterState.UNLOAD_ROOT_TABLET)) { setMasterState(MasterState.UNLOAD_METADATA_TABLETS); } } if (extent.isRootTablet()) { // probably too late, but try anyhow if (getMasterState().equals(MasterState.STOP)) { setMasterState(MasterState.UNLOAD_ROOT_TABLET); } } } }
ACCUMULO-1010 Support upgrades from 1.4 to 1.5 Description: Add steps necessary to move a zk from 1.4 state to 1.5. This leaves it in a good state to be picked up by the rest of the 1.6 upgrade path. Author: kturner Ref: ACCUMULO-2988 Cherry picking caused a huge mess and it was simpler to manually select the parts of the upgrade code that we needed based on the 1.5.1 tag. Gathered from commits 317c669, aa6b4309, and 8811859.
server/master/src/main/java/org/apache/accumulo/master/Master.java
ACCUMULO-1010 Support upgrades from 1.4 to 1.5
Java
apache-2.0
7950d726d452a00919b1213067e463a8f7bb67c6
0
XiveZ/XposedAppSettings,rovo89/XposedAppSettings,Arnie97/XposedAppSettings,Unpublished/XposedAppSettings,xyzr0482/XposedAppSettings,Ni2014/XposedAppSettings,djh123/XposedAppSettings,cooldroid/XposedAppSettings,d8ahazard/XposedAppSettings
package de.robv.android.xposed.mods.appsettings; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; import android.annotation.SuppressLint; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.graphics.Color; import android.os.AsyncTask; import android.os.Bundle; import android.text.method.LinkMovementMethod; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.Filter; import android.widget.ImageView; import android.widget.ListView; import android.widget.SearchView; import android.widget.SectionIndexer; import android.widget.TabHost; import android.widget.TabHost.TabSpec; import android.widget.TextView; import de.robv.android.xposed.mods.appsettings.settings.ApplicationSettings; public class XposedModActivity extends Activity { private ArrayList<ApplicationInfo> appList = new ArrayList<ApplicationInfo>(); private ArrayList<ApplicationInfo> filteredAppList = new ArrayList<ApplicationInfo>(); private String activeFilter; private SharedPreferences prefs; @SuppressLint("WorldReadableFiles") @Override public void onCreate(Bundle savedInstanceState) { setTitle(R.string.app_name); super.onCreate(savedInstanceState); prefs = getSharedPreferences(XposedMod.PREFS, Context.MODE_WORLD_READABLE); setContentView(R.layout.main); TabHost tabHost=(TabHost)findViewById(R.id.tabHost); tabHost.setup(); TabSpec spec1=tabHost.newTabSpec("App Settings"); spec1.setIndicator("App Settings"); spec1.setContent(R.id.tab1); TabSpec spec2=tabHost.newTabSpec("About"); spec2.setIndicator("About"); spec2.setContent(R.id.tab2); tabHost.addTab(spec1); tabHost.addTab(spec2); tabHost.setCurrentTab(0); ((TextView) findViewById(R.id.about_title)).setMovementMethod(LinkMovementMethod.getInstance()); try { ((TextView) findViewById(R.id.version)).setText("Version: " + getPackageManager().getPackageInfo(getPackageName(), 0).versionName); } catch (NameNotFoundException e) { } ListView list = (ListView) findViewById(R.id.lstApps); list.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // Open settings activity when clicking on an application String pkgName = ((TextView) view.findViewById(R.id.app_package)).getText().toString(); Intent i = new Intent(getApplicationContext(), ApplicationSettings.class); i.putExtra("package", pkgName); startActivityForResult(i, position); } }); // Load the list of apps in the background new PrepareAppsAdapter().execute(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // Refresh the app that was just edited, if it's visible in the list ListView list = (ListView) findViewById(R.id.lstApps); if (requestCode >= list.getFirstVisiblePosition() && requestCode <= list.getLastVisiblePosition()) { View v = list.getChildAt(requestCode - list.getFirstVisiblePosition()); list.getAdapter().getView(requestCode, v, list); } } @SuppressLint("DefaultLocale") private void loadApps() { appList.clear(); PackageManager pm = getPackageManager(); List<ApplicationInfo> apps = getPackageManager().getInstalledApplications(0); for (ApplicationInfo appInfo : apps) { appInfo.name = appInfo.loadLabel(pm).toString(); appList.add(appInfo); } Collections.sort(appList, new Comparator<ApplicationInfo>() { @Override public int compare(ApplicationInfo lhs, ApplicationInfo rhs) { if (lhs.name == null) { return -1; } else if (rhs.name == null) { return 1; } else { return lhs.name.toUpperCase().compareTo(rhs.name.toUpperCase()); } } }); } private void prepareAppList() { final AppListAdaptor appListAdaptor = new AppListAdaptor(XposedModActivity.this,appList); ((ListView) findViewById(R.id.lstApps)).setAdapter(appListAdaptor); ((SearchView) findViewById(R.id.searchApp)).setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { activeFilter = query; appListAdaptor.getFilter().filter(activeFilter); ((SearchView) findViewById(R.id.searchApp)).clearFocus(); return false; } @Override public boolean onQueryTextChange(String newText) { activeFilter = newText; appListAdaptor.getFilter().filter(activeFilter); return false; } }); ((CheckBox) findViewById(R.id.chkOnlyTweaked)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { appListAdaptor.getFilter().filter(activeFilter); } }); } // Handle background loading of apps private class PrepareAppsAdapter extends AsyncTask<Void,Void,AppListAdaptor> { ProgressDialog dialog; @Override protected void onPreExecute() { dialog = new ProgressDialog(((ListView) findViewById(R.id.lstApps)).getContext()); dialog.setMessage("Loading apps, please wait"); dialog.setIndeterminate(true); dialog.setCancelable(false); dialog.show(); } @Override protected AppListAdaptor doInBackground(Void... params) { if (appList.size() == 0) { loadApps(); } return null; } @Override protected void onPostExecute(final AppListAdaptor result) { prepareAppList(); try { dialog.dismiss(); } catch (Exception e) { } } } private class AppListFilter extends Filter { private AppListAdaptor adaptor; AppListFilter(AppListAdaptor adaptor) { super(); this.adaptor = adaptor; } @SuppressLint("WorldReadableFiles") @Override protected FilterResults performFiltering(CharSequence constraint) { // NOTE: this function is *always* called from a background thread, and // not the UI thread. ArrayList<ApplicationInfo> items = new ArrayList<ApplicationInfo>(); synchronized (this) { items.addAll(appList); } boolean onlyTweaked = ((CheckBox) findViewById(R.id.chkOnlyTweaked)).isChecked(); SharedPreferences prefs = getSharedPreferences(XposedMod.PREFS, Context.MODE_WORLD_READABLE); FilterResults result = new FilterResults(); if (constraint != null && constraint.length() > 0) { Pattern regexp = Pattern.compile(constraint.toString(), Pattern.LITERAL | Pattern.CASE_INSENSITIVE); for (Iterator<ApplicationInfo> i = items.iterator(); i.hasNext(); ) { ApplicationInfo app = i.next(); if (!regexp.matcher(app.name == null ? "" : app.name).find() && !regexp.matcher(app.packageName).find()) { i.remove(); } } } for (Iterator<ApplicationInfo> i = items.iterator(); i.hasNext(); ) { ApplicationInfo app = i.next(); if (onlyTweaked && !prefs.getBoolean(app.packageName + XposedMod.PREF_ACTIVE, false)) { i.remove(); } } result.values = items; result.count = items.size(); return result; } @SuppressWarnings("unchecked") @Override protected void publishResults(CharSequence constraint, FilterResults results) { // NOTE: this function is *always* called from the UI thread. filteredAppList = (ArrayList<ApplicationInfo>) results.values; adaptor.notifyDataSetChanged(); adaptor.clear(); for(int i = 0, l = filteredAppList.size(); i < l; i++) { adaptor.add(filteredAppList.get(i)); } adaptor.notifyDataSetInvalidated(); } } class AppListAdaptor extends ArrayAdapter<ApplicationInfo> implements SectionIndexer { private Map<String, Integer> alphaIndexer; private String[] sections; private Filter filter; @SuppressLint("DefaultLocale") public AppListAdaptor(Context context, List<ApplicationInfo> items) { super(context, R.layout.app_list_item, new ArrayList<ApplicationInfo>(items)); filteredAppList.addAll(items); filter = new AppListFilter(this); alphaIndexer = new HashMap<String, Integer>(); for(int i = filteredAppList.size() - 1; i >= 0; i--) { ApplicationInfo app = filteredAppList.get(i); String appName = app.name; String firstChar; if (appName == null || appName.length() < 1) { firstChar = "@"; } else { firstChar = appName.substring(0, 1).toUpperCase(); if(firstChar.charAt(0) > 'Z' || firstChar.charAt(0) < 'A') firstChar = "@"; } alphaIndexer.put(firstChar, i); } Set<String> sectionLetters = alphaIndexer.keySet(); // create a list from the set to sort List<String> sectionList = new ArrayList<String>(sectionLetters); Collections.sort(sectionList); sections = new String[sectionList.size()]; sectionList.toArray(sections); } @Override public View getView(int position, View convertView, ViewGroup parent) { // Load or reuse the view for this row View row = convertView; if (row == null) { row = getLayoutInflater().inflate(R.layout.app_list_item, parent, false); } ApplicationInfo app = filteredAppList.get(position); ((TextView) row.findViewById(R.id.app_name)).setText(app.name == null ? "" : app.name); ((TextView) row.findViewById(R.id.app_package)).setTextColor(prefs.getBoolean(app.packageName + XposedMod.PREF_ACTIVE, false) ? Color.RED : Color.parseColor("#0099CC")); ((TextView) row.findViewById(R.id.app_package)).setText(app.packageName); ((ImageView) row.findViewById(R.id.app_icon)).setImageDrawable(app.loadIcon(getPackageManager())); return row; } @SuppressLint("DefaultLocale") @Override public void notifyDataSetInvalidated() { alphaIndexer.clear(); for (int i = filteredAppList.size() - 1; i >= 0; i--) { ApplicationInfo app = filteredAppList.get(i); String appName = app.name; String firstChar; if (appName == null || appName.length() < 1) { firstChar = "@"; } else { firstChar = appName.substring(0, 1).toUpperCase(); if(firstChar.charAt(0) > 'Z' || firstChar.charAt(0) < 'A') firstChar = "@"; } alphaIndexer.put(firstChar, i); } Set<String> keys = alphaIndexer.keySet(); Iterator<String> it = keys.iterator(); ArrayList<String> keyList = new ArrayList<String>(); while (it.hasNext()) { keyList.add(it.next()); } Collections.sort(keyList); sections = new String[keyList.size()]; keyList.toArray(sections); super.notifyDataSetInvalidated(); } @Override public int getPositionForSection(int section) { return alphaIndexer.get(sections[section]); } @Override public int getSectionForPosition(int position) { // Iterate over the sections to find the closest index // that is not greater than the position int closestIndex = 0; int latestDelta = Integer.MAX_VALUE; for (int i = 0; i < sections.length; i++) { int current = alphaIndexer.get(sections[i]); if (current == position) { // If position matches an index, return it immediately return i; } else if (current < position) { // Check if this is closer than the last index we inspected int delta = position - current; if (delta < latestDelta) { closestIndex = i; latestDelta = delta; } } } return closestIndex; } @Override public Object[] getSections() { return sections; } @Override public Filter getFilter() { return filter; } } }
src/de/robv/android/xposed/mods/appsettings/XposedModActivity.java
package de.robv.android.xposed.mods.appsettings; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; import android.annotation.SuppressLint; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.graphics.Color; import android.os.AsyncTask; import android.os.Bundle; import android.text.method.LinkMovementMethod; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.Filter; import android.widget.ImageView; import android.widget.ListView; import android.widget.SearchView; import android.widget.SectionIndexer; import android.widget.TabHost; import android.widget.TabHost.TabSpec; import android.widget.TextView; import de.robv.android.xposed.mods.appsettings.settings.ApplicationSettings; public class XposedModActivity extends Activity { private ArrayList<ApplicationInfo> appList = new ArrayList<ApplicationInfo>(); private ArrayList<ApplicationInfo> filteredAppList = new ArrayList<ApplicationInfo>(); private String activeFilter; private SharedPreferences prefs; @SuppressLint("WorldReadableFiles") @Override public void onCreate(Bundle savedInstanceState) { setTitle(R.string.app_name); super.onCreate(savedInstanceState); prefs = getSharedPreferences(XposedMod.PREFS, Context.MODE_WORLD_READABLE); setContentView(R.layout.main); TabHost tabHost=(TabHost)findViewById(R.id.tabHost); tabHost.setup(); TabSpec spec1=tabHost.newTabSpec("App Settings"); spec1.setIndicator("App Settings"); spec1.setContent(R.id.tab1); TabSpec spec2=tabHost.newTabSpec("About"); spec2.setIndicator("About"); spec2.setContent(R.id.tab2); tabHost.addTab(spec1); tabHost.addTab(spec2); tabHost.setCurrentTab(0); ((TextView) findViewById(R.id.about_title)).setMovementMethod(LinkMovementMethod.getInstance()); try { ((TextView) findViewById(R.id.version)).setText("Version: " + getPackageManager().getPackageInfo(getPackageName(), 0).versionName); } catch (NameNotFoundException e) { } ListView list = (ListView) findViewById(R.id.lstApps); list.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // Open settings activity when clicking on an application String pkgName = ((TextView) view.findViewById(R.id.app_package)).getText().toString(); Intent i = new Intent(getApplicationContext(), ApplicationSettings.class); i.putExtra("package", pkgName); startActivityForResult(i, position); } }); // Load the list of apps in the background new PrepareAppsAdapter().execute(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // Refresh the app that was just edited, if it's visible in the list ListView list = (ListView) findViewById(R.id.lstApps); if (requestCode >= list.getFirstVisiblePosition() && requestCode <= list.getLastVisiblePosition()) { View v = list.getChildAt(requestCode - list.getFirstVisiblePosition()); list.getAdapter().getView(requestCode, v, list); } } @SuppressLint("DefaultLocale") private void loadApps() { appList.clear(); PackageManager pm = getPackageManager(); List<ApplicationInfo> apps = getPackageManager().getInstalledApplications(0); for (ApplicationInfo appInfo : apps) { appInfo.name = appInfo.loadLabel(pm).toString(); appList.add(appInfo); } Collections.sort(appList, new Comparator<ApplicationInfo>() { @Override public int compare(ApplicationInfo lhs, ApplicationInfo rhs) { if (lhs.name == null) { return -1; } else if (rhs.name == null) { return 1; } else { return lhs.name.toUpperCase().compareTo(rhs.name.toUpperCase()); } } }); } private void prepareAppList() { final AppListAdaptor appListAdaptor = new AppListAdaptor(XposedModActivity.this,appList); ((ListView) findViewById(R.id.lstApps)).setAdapter(appListAdaptor); ((SearchView) findViewById(R.id.searchApp)).setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { activeFilter = query; appListAdaptor.getFilter().filter(activeFilter); ((SearchView) findViewById(R.id.searchApp)).clearFocus(); return false; } @Override public boolean onQueryTextChange(String newText) { activeFilter = newText; appListAdaptor.getFilter().filter(activeFilter); return false; } }); ((CheckBox) findViewById(R.id.chkOnlyTweaked)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { appListAdaptor.getFilter().filter(activeFilter); } }); } // Handle background loading of apps private class PrepareAppsAdapter extends AsyncTask<Void,Void,AppListAdaptor> { ProgressDialog dialog; @Override protected void onPreExecute() { dialog = new ProgressDialog(((ListView) findViewById(R.id.lstApps)).getContext()); dialog.setMessage("Loading apps, please wait"); dialog.setIndeterminate(true); dialog.setCancelable(false); dialog.show(); } @Override protected AppListAdaptor doInBackground(Void... params) { if (appList.size() == 0) { loadApps(); } return null; } @Override protected void onPostExecute(final AppListAdaptor result) { prepareAppList(); try { dialog.dismiss(); } catch (Exception e) { } } } private class AppListFilter extends Filter { private AppListAdaptor adaptor; AppListFilter(AppListAdaptor adaptor) { super(); this.adaptor = adaptor; } @SuppressLint("WorldReadableFiles") @Override protected FilterResults performFiltering(CharSequence constraint) { // NOTE: this function is *always* called from a background thread, and // not the UI thread. ArrayList<ApplicationInfo> items = new ArrayList<ApplicationInfo>(); synchronized (this) { items.addAll(appList); } boolean onlyTweaked = ((CheckBox) findViewById(R.id.chkOnlyTweaked)).isChecked(); SharedPreferences prefs = getSharedPreferences(XposedMod.PREFS, Context.MODE_WORLD_READABLE); FilterResults result = new FilterResults(); if (constraint != null && constraint.length() > 0) { Pattern regexp = Pattern.compile(constraint.toString(), Pattern.LITERAL | Pattern.CASE_INSENSITIVE); for (Iterator<ApplicationInfo> i = items.iterator(); i.hasNext(); ) { ApplicationInfo app = i.next(); if (!regexp.matcher(app.name).find() && !regexp.matcher(app.packageName).find()) { i.remove(); } } } for (Iterator<ApplicationInfo> i = items.iterator(); i.hasNext(); ) { ApplicationInfo app = i.next(); if (onlyTweaked && !prefs.getBoolean(app.packageName + XposedMod.PREF_ACTIVE, false)) { i.remove(); } } result.values = items; result.count = items.size(); return result; } @SuppressWarnings("unchecked") @Override protected void publishResults(CharSequence constraint, FilterResults results) { // NOTE: this function is *always* called from the UI thread. filteredAppList = (ArrayList<ApplicationInfo>) results.values; adaptor.notifyDataSetChanged(); adaptor.clear(); for(int i = 0, l = filteredAppList.size(); i < l; i++) { adaptor.add(filteredAppList.get(i)); } adaptor.notifyDataSetInvalidated(); } } class AppListAdaptor extends ArrayAdapter<ApplicationInfo> implements SectionIndexer { private Map<String, Integer> alphaIndexer; private String[] sections; private Filter filter; @SuppressLint("DefaultLocale") public AppListAdaptor(Context context, List<ApplicationInfo> items) { super(context, R.layout.app_list_item, new ArrayList<ApplicationInfo>(items)); filteredAppList.addAll(items); filter = new AppListFilter(this); alphaIndexer = new HashMap<String, Integer>(); for(int i = filteredAppList.size() - 1; i >= 0; i--) { ApplicationInfo app = filteredAppList.get(i); String firstChar = app.name.substring(0, 1).toUpperCase(); if(firstChar.charAt(0) > 'Z' || firstChar.charAt(0) < 'A') firstChar = "@"; alphaIndexer.put(firstChar, i); } Set<String> sectionLetters = alphaIndexer.keySet(); // create a list from the set to sort List<String> sectionList = new ArrayList<String>(sectionLetters); Collections.sort(sectionList); sections = new String[sectionList.size()]; sectionList.toArray(sections); } @Override public View getView(int position, View convertView, ViewGroup parent) { // Load or reuse the view for this row View row = convertView; if (row == null) { row = getLayoutInflater().inflate(R.layout.app_list_item, parent, false); } ApplicationInfo app = filteredAppList.get(position); ((TextView) row.findViewById(R.id.app_name)).setText(app.name); ((TextView) row.findViewById(R.id.app_package)).setTextColor(prefs.getBoolean(app.packageName + XposedMod.PREF_ACTIVE, false) ? Color.RED : Color.parseColor("#0099CC")); ((TextView) row.findViewById(R.id.app_package)).setText(app.packageName); ((ImageView) row.findViewById(R.id.app_icon)).setImageDrawable(app.loadIcon(getPackageManager())); return row; } @SuppressLint("DefaultLocale") @Override public void notifyDataSetInvalidated() { alphaIndexer.clear(); for (int i = filteredAppList.size() - 1; i >= 0; i--) { ApplicationInfo app = filteredAppList.get(i); String firstChar = app.name.substring(0, 1).toUpperCase(); if (firstChar.charAt(0) > 'Z' || firstChar.charAt(0) < 'A') firstChar = "@"; alphaIndexer.put(firstChar, i); } Set<String> keys = alphaIndexer.keySet(); Iterator<String> it = keys.iterator(); ArrayList<String> keyList = new ArrayList<String>(); while (it.hasNext()) { keyList.add(it.next()); } Collections.sort(keyList); sections = new String[keyList.size()]; keyList.toArray(sections); super.notifyDataSetInvalidated(); } @Override public int getPositionForSection(int section) { return alphaIndexer.get(sections[section]); } @Override public int getSectionForPosition(int position) { // Iterate over the sections to find the closest index // that is not greater than the position int closestIndex = 0; int latestDelta = Integer.MAX_VALUE; for (int i = 0; i < sections.length; i++) { int current = alphaIndexer.get(sections[i]); if (current == position) { // If position matches an index, return it immediately return i; } else if (current < position) { // Check if this is closer than the last index we inspected int delta = position - current; if (delta < latestDelta) { closestIndex = i; latestDelta = delta; } } } return closestIndex; } @Override public Object[] getSections() { return sections; } @Override public Filter getFilter() { return filter; } } }
Fix FC when apps have an empty name
src/de/robv/android/xposed/mods/appsettings/XposedModActivity.java
Fix FC when apps have an empty name
Java
bsd-2-clause
c6c5dea588908fedac89004078dc2d70588f1efe
0
TehSAUCE/imagej,biovoxxel/imagej,biovoxxel/imagej,TehSAUCE/imagej,TehSAUCE/imagej,biovoxxel/imagej
/* * #%L * ImageJ software for multidimensional image processing and analysis. * %% * Copyright (C) 2009 - 2014 Board of Regents of the University of * Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck * Institute of Molecular Cell Biology and Genetics. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * #L% */ package imagej.legacy; import imagej.command.CommandService; import imagej.data.DatasetService; import imagej.data.display.DatasetView; import imagej.data.display.ImageDisplay; import imagej.data.display.ImageDisplayService; import imagej.data.display.OverlayService; import imagej.data.options.OptionsChannels; import imagej.data.threshold.ThresholdService; import imagej.display.DisplayService; import imagej.display.event.DisplayActivatedEvent; import imagej.display.event.input.KyPressedEvent; import imagej.display.event.input.KyReleasedEvent; import imagej.legacy.plugin.LegacyCommand; import imagej.legacy.plugin.LegacyPluginFinder; import imagej.menu.MenuService; import imagej.options.OptionsService; import imagej.options.event.OptionsEvent; import imagej.ui.ApplicationFrame; import imagej.ui.UIService; import imagej.ui.viewer.DisplayWindow; import imagej.ui.viewer.image.ImageDisplayViewer; import imagej.util.ColorRGB; import java.awt.GraphicsEnvironment; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import org.scijava.app.StatusService; import org.scijava.event.EventHandler; import org.scijava.event.EventService; import org.scijava.input.KeyCode; import org.scijava.log.LogService; import org.scijava.plugin.Parameter; import org.scijava.plugin.Plugin; import org.scijava.plugin.PluginInfo; import org.scijava.plugin.PluginService; import org.scijava.service.AbstractService; import org.scijava.service.Service; /** * Default service for working with legacy ImageJ 1.x. * <p> * The legacy service overrides the behavior of various legacy ImageJ methods, * inserting seams so that (e.g.) the modern UI is aware of legacy ImageJ events * as they occur. * </p> * <p> * It also maintains an image map between legacy ImageJ {@link ij.ImagePlus} * objects and modern ImageJ {@link ImageDisplay}s. * </p> * <p> * In this fashion, when a legacy command is executed on a {@link ImageDisplay}, * the service transparently translates it into an {@link ij.ImagePlus}, and vice * versa, enabling backward compatibility with legacy commands. * </p> * * @author Barry DeZonia * @author Curtis Rueden * @author Johannes Schindelin */ @Plugin(type = Service.class) public final class DefaultLegacyService extends AbstractService implements LegacyService { private final static LegacyInjector legacyInjector; static { final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); legacyInjector = new LegacyInjector(); legacyInjector.injectHooks(contextClassLoader); } @Parameter private OverlayService overlayService; @Parameter private LogService log; @Parameter private EventService eventService; @Parameter private PluginService pluginService; @Parameter private CommandService commandService; @Parameter private OptionsService optionsService; @Parameter private ImageDisplayService imageDisplayService; @Parameter private DisplayService displayService; @Parameter private ThresholdService thresholdService; @Parameter private DatasetService datasetService; @Parameter private MenuService menuService; @Parameter private StatusService statusService; @Parameter(required = false) private UIService uiService; private static DefaultLegacyService instance; /** Mapping between modern and legacy image data structures. */ private LegacyImageMap imageMap; /** Method of synchronizing modern & legacy options. */ private OptionsSynchronizer optionsSynchronizer; /** Keep references to ImageJ 1.x separate */ private IJ1Helper ij1Helper; /** Legacy ImageJ 1.x mode: stop synchronizing */ private boolean legacyIJ1Mode; // -- LegacyService methods -- @Override public LogService log() { return log; } @Override public StatusService status() { return statusService; } @Override public LegacyImageMap getImageMap() { return imageMap; } @Override public OptionsSynchronizer getOptionsSynchronizer() { return optionsSynchronizer; } @Override public void runLegacyCommand(final String ij1ClassName, final String argument) { final String arg = argument == null ? "" : argument; final Map<String, Object> inputMap = new HashMap<String, Object>(); inputMap.put("className", ij1ClassName); inputMap.put("arg", arg); commandService.run(LegacyCommand.class, true, inputMap); } @Override public void syncActiveImage() { final ImageDisplay activeDisplay = imageDisplayService.getActiveImageDisplay(); ij1Helper.syncActiveImage(activeDisplay); } @Override public boolean isInitialized() { return instance != null; } @Override public void syncColors() { final DatasetView view = imageDisplayService.getActiveDatasetView(); if (view == null) return; final OptionsChannels channels = getChannels(); final ColorRGB fgColor = view.getColor(channels.getFgValues()); final ColorRGB bgColor = view.getColor(channels.getBgValues()); optionsSynchronizer.colorOptions(fgColor, bgColor); } /** * States whether we're running in legacy ImageJ 1.x mode. * <p> * To support work flows which are incompatible with ImageJ2, we want to allow * users to run in legacy ImageJ 1.x mode, where the ImageJ2 GUI is hidden and * the ImageJ 1.x GUI is shown. During this time, no synchronization should * take place. * </p> */ @Override public boolean isLegacyMode() { return legacyIJ1Mode; } /** * Switch to/from running legacy ImageJ 1.x mode. */ @Override public void toggleLegacyMode(final boolean wantIJ1) { toggleLegacyMode(wantIJ1, false); } public synchronized void toggleLegacyMode(final boolean wantIJ1, final boolean initializing) { if (wantIJ1) legacyIJ1Mode = true; // TODO: hide/show Brightness/Contrast, Color Picker, Command Launcher, etc // TODO: prevent IJ1 from quitting without IJ2 quitting, too if (!initializing) { if (uiService != null) { // hide/show the IJ2 main window final ApplicationFrame appFrame = uiService.getDefaultUI().getApplicationFrame(); if (appFrame == null) { if (!wantIJ1) uiService.showUI(); } else { appFrame.setVisible(!wantIJ1); } } // TODO: move this into the LegacyImageMap's toggleLegacyMode, passing // the uiService // hide/show the IJ2 datasets corresponding to legacy ImagePlus instances for (final ImageDisplay display : imageMap.getImageDisplays()) { final ImageDisplayViewer viewer = (ImageDisplayViewer) uiService.getDisplayViewer(display); if (viewer == null) continue; final DisplayWindow window = viewer.getWindow(); if (window != null) window.showDisplay(!wantIJ1); } } // hide/show IJ1 main window ij1Helper.setVisible(wantIJ1); if (wantIJ1 && !initializing) { optionsSynchronizer.updateLegacyImageJSettingsFromModernImageJ(); } if (!wantIJ1) legacyIJ1Mode = false; imageMap.toggleLegacyMode(wantIJ1); } @Override public String getLegacyVersion() { return ij1Helper.getVersion(); } // -- Service methods -- @Override public void initialize() { checkInstance(); ij1Helper = new IJ1Helper(this); boolean hasIJ1Instance = ij1Helper.hasInstance(); // as long as we're starting up, we're in legacy mode legacyIJ1Mode = true; imageMap = new LegacyImageMap(this); optionsSynchronizer = new OptionsSynchronizer(optionsService); synchronized (DefaultLegacyService.class) { checkInstance(); instance = this; legacyInjector.setLegacyService(this); } ij1Helper.initialize(); SwitchToModernMode.registerMenuItem(); // discover legacy plugins final boolean enableBlacklist = true; addLegacyCommands(enableBlacklist); if (!hasIJ1Instance && !GraphicsEnvironment.isHeadless()) toggleLegacyMode(false, true); } // -- Disposable methods -- @Override public void dispose() { ij1Helper.dispose(); legacyInjector.setLegacyService(new DummyLegacyService()); instance = null; } // -- Event handlers -- /** * Keeps the active legacy {@link ij.ImagePlus} in sync with the active modern * {@link ImageDisplay}. */ @EventHandler protected void onEvent( @SuppressWarnings("unused") final DisplayActivatedEvent event) { syncActiveImage(); } @EventHandler protected void onEvent(@SuppressWarnings("unused") final OptionsEvent event) { optionsSynchronizer.updateModernImageJSettingsFromLegacyImageJ(); } @EventHandler protected void onEvent(final KyPressedEvent event) { final KeyCode code = event.getCode(); if (code == KeyCode.SPACE) ij1Helper.setKeyDown(KeyCode.SPACE.getCode()); if (code == KeyCode.ALT) ij1Helper.setKeyDown(KeyCode.ALT.getCode()); if (code == KeyCode.SHIFT) ij1Helper.setKeyDown(KeyCode.SHIFT.getCode()); if (code == KeyCode.CONTROL) ij1Helper.setKeyDown(KeyCode.CONTROL.getCode()); if (ij1Helper.isMacintosh() && code == KeyCode.META) { ij1Helper.setKeyDown(KeyCode.CONTROL.getCode()); } } @EventHandler protected void onEvent(final KyReleasedEvent event) { final KeyCode code = event.getCode(); if (code == KeyCode.SPACE) ij1Helper.setKeyUp(KeyCode.SPACE.getCode()); if (code == KeyCode.ALT) ij1Helper.setKeyUp(KeyCode.ALT.getCode()); if (code == KeyCode.SHIFT) ij1Helper.setKeyUp(KeyCode.SHIFT.getCode()); if (code == KeyCode.CONTROL) ij1Helper.setKeyUp(KeyCode.CONTROL.getCode()); if (ij1Helper.isMacintosh() && code == KeyCode.META) { ij1Helper.setKeyUp(KeyCode.CONTROL.getCode()); } } // -- pre-initialization /** * Makes sure that the ImageJ 1.x classes are patched. * <p> * We absolutely require that the LegacyInjector did its job before we use the * ImageJ 1.x classes. * </p> * <p> * Just loading the {@link DefaultLegacyService} class is not enough; it will * not necessarily get initialized. So we provide this method just to force * class initialization (and thereby the LegacyInjector to patch ImageJ 1.x). * </p> */ public static void preinit() { if (legacyInjector == null) { throw new RuntimeException("LegacyInjector was not instantiated!"); } } // -- helpers -- /** * Returns the legacy service associated with the ImageJ 1.x instance in the * current class loader. This method is intended to be used by the * {@link CodeHacker}; it is invoked by the javassisted methods. * * @return the legacy service */ public static DefaultLegacyService getInstance() { return instance; } /** * @throws UnsupportedOperationException if the singleton * {@code DefaultLegacyService} already exists. */ private void checkInstance() { if (instance != null) { throw new UnsupportedOperationException( "Cannot instantiate more than one DefaultLegacyService"); } } private OptionsChannels getChannels() { return optionsService.getOptions(OptionsChannels.class); } @SuppressWarnings("unused") private void updateMenus(final boolean enableBlacklist) { pluginService.reloadPlugins(); addLegacyCommands(enableBlacklist); } private void addLegacyCommands(final boolean enableBlacklist) { final LegacyPluginFinder finder = new LegacyPluginFinder(log, menuService.getMenu(), enableBlacklist); final ArrayList<PluginInfo<?>> plugins = new ArrayList<PluginInfo<?>>(); finder.findPlugins(plugins); pluginService.addPlugins(plugins); } }
core/legacy/src/main/java/imagej/legacy/DefaultLegacyService.java
/* * #%L * ImageJ software for multidimensional image processing and analysis. * %% * Copyright (C) 2009 - 2014 Board of Regents of the University of * Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck * Institute of Molecular Cell Biology and Genetics. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * #L% */ package imagej.legacy; import imagej.command.CommandService; import imagej.data.DatasetService; import imagej.data.display.DatasetView; import imagej.data.display.ImageDisplay; import imagej.data.display.ImageDisplayService; import imagej.data.display.OverlayService; import imagej.data.options.OptionsChannels; import imagej.data.threshold.ThresholdService; import imagej.display.DisplayService; import imagej.display.event.DisplayActivatedEvent; import imagej.display.event.input.KyPressedEvent; import imagej.display.event.input.KyReleasedEvent; import imagej.legacy.plugin.LegacyCommand; import imagej.legacy.plugin.LegacyPluginFinder; import imagej.menu.MenuService; import imagej.options.OptionsService; import imagej.options.event.OptionsEvent; import imagej.ui.ApplicationFrame; import imagej.ui.UIService; import imagej.ui.viewer.DisplayWindow; import imagej.ui.viewer.image.ImageDisplayViewer; import imagej.util.ColorRGB; import java.awt.GraphicsEnvironment; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import org.scijava.app.StatusService; import org.scijava.event.EventHandler; import org.scijava.event.EventService; import org.scijava.input.KeyCode; import org.scijava.log.LogService; import org.scijava.plugin.Parameter; import org.scijava.plugin.Plugin; import org.scijava.plugin.PluginInfo; import org.scijava.plugin.PluginService; import org.scijava.service.AbstractService; import org.scijava.service.Service; /** * Default service for working with legacy ImageJ 1.x. * <p> * The legacy service overrides the behavior of various legacy ImageJ methods, * inserting seams so that (e.g.) the modern UI is aware of legacy ImageJ events * as they occur. * </p> * <p> * It also maintains an image map between legacy ImageJ {@link ij.ImagePlus} * objects and modern ImageJ {@link ImageDisplay}s. * </p> * <p> * In this fashion, when a legacy command is executed on a {@link ImageDisplay}, * the service transparently translates it into an {@link ij.ImagePlus}, and vice * versa, enabling backward compatibility with legacy commands. * </p> * * @author Barry DeZonia * @author Curtis Rueden * @author Johannes Schindelin */ @Plugin(type = Service.class) public final class DefaultLegacyService extends AbstractService implements LegacyService { private final static LegacyInjector legacyInjector; static { final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); legacyInjector = new LegacyInjector(); legacyInjector.injectHooks(contextClassLoader); } @Parameter private OverlayService overlayService; @Parameter private LogService log; @Parameter private EventService eventService; @Parameter private PluginService pluginService; @Parameter private CommandService commandService; @Parameter private OptionsService optionsService; @Parameter private ImageDisplayService imageDisplayService; @Parameter private DisplayService displayService; @Parameter private ThresholdService thresholdService; @Parameter private DatasetService datasetService; @Parameter private MenuService menuService; @Parameter private StatusService statusService; @Parameter(required = false) private UIService uiService; private static DefaultLegacyService instance; /** Mapping between modern and legacy image data structures. */ private LegacyImageMap imageMap; /** Method of synchronizing modern & legacy options. */ private OptionsSynchronizer optionsSynchronizer; /** Keep references to ImageJ 1.x separate */ private IJ1Helper ij1Helper; /** Legacy ImageJ 1.x mode: stop synchronizing */ private boolean legacyIJ1Mode; // -- LegacyService methods -- @Override public LogService log() { return log; } @Override public StatusService status() { return statusService; } @Override public LegacyImageMap getImageMap() { return imageMap; } @Override public OptionsSynchronizer getOptionsSynchronizer() { return optionsSynchronizer; } @Override public void runLegacyCommand(final String ij1ClassName, final String argument) { final String arg = argument == null ? "" : argument; final Map<String, Object> inputMap = new HashMap<String, Object>(); inputMap.put("className", ij1ClassName); inputMap.put("arg", arg); commandService.run(LegacyCommand.class, true, inputMap); } @Override public void syncActiveImage() { final ImageDisplay activeDisplay = imageDisplayService.getActiveImageDisplay(); ij1Helper.syncActiveImage(activeDisplay); } @Override public boolean isInitialized() { return instance != null; } @Override public void syncColors() { final DatasetView view = imageDisplayService.getActiveDatasetView(); if (view == null) return; final OptionsChannels channels = getChannels(); final ColorRGB fgColor = view.getColor(channels.getFgValues()); final ColorRGB bgColor = view.getColor(channels.getBgValues()); optionsSynchronizer.colorOptions(fgColor, bgColor); } /** * States whether we're running in legacy ImageJ 1.x mode. * <p> * To support work flows which are incompatible with ImageJ2, we want to allow * users to run in legacy ImageJ 1.x mode, where the ImageJ2 GUI is hidden and * the ImageJ 1.x GUI is shown. During this time, no synchronization should * take place. * </p> */ @Override public boolean isLegacyMode() { return legacyIJ1Mode; } /** * Switch to/from running legacy ImageJ 1.x mode. */ @Override public void toggleLegacyMode(final boolean wantIJ1) { toggleLegacyMode(wantIJ1, false); } public synchronized void toggleLegacyMode(final boolean wantIJ1, final boolean initializing) { if (wantIJ1) legacyIJ1Mode = true; // TODO: hide/show Brightness/Contrast, Color Picker, Command Launcher, etc // TODO: prevent IJ1 from quitting without IJ2 quitting, too if (!initializing) { if (uiService != null) { // hide/show the IJ2 main window final ApplicationFrame appFrame = uiService.getDefaultUI().getApplicationFrame(); if (appFrame == null) { if (!wantIJ1) uiService.showUI(); } else { appFrame.setVisible(!wantIJ1); } } // TODO: move this into the LegacyImageMap's toggleLegacyMode, passing // the uiService // hide/show the IJ2 datasets corresponding to legacy ImagePlus instances for (final ImageDisplay display : imageMap.getImageDisplays()) { final ImageDisplayViewer viewer = (ImageDisplayViewer) uiService.getDisplayViewer(display); if (viewer == null) continue; final DisplayWindow window = viewer.getWindow(); if (window != null) window.showDisplay(!wantIJ1); } } // hide/show IJ1 main window ij1Helper.setVisible(wantIJ1); if (wantIJ1 && !initializing) { optionsSynchronizer.updateLegacyImageJSettingsFromModernImageJ(); } if (!wantIJ1) legacyIJ1Mode = false; imageMap.toggleLegacyMode(wantIJ1); } @Override public String getLegacyVersion() { return ij1Helper.getVersion(); } // -- Service methods -- @Override public void initialize() { checkInstance(); ij1Helper = new IJ1Helper(this); boolean hasIJ1Instance = ij1Helper.hasInstance(); // as long as we're starting up, we're in legacy mode legacyIJ1Mode = true; imageMap = new LegacyImageMap(this); optionsSynchronizer = new OptionsSynchronizer(optionsService); synchronized (DefaultLegacyService.class) { checkInstance(); instance = this; legacyInjector.setLegacyService(this); } ij1Helper.initialize(); SwitchToModernMode.registerMenuItem(); // discover legacy plugins final boolean enableBlacklist = true; addLegacyCommands(enableBlacklist); if (!hasIJ1Instance && !GraphicsEnvironment.isHeadless()) toggleLegacyMode(false, true); } // -- Disposable methods -- @Override public void dispose() { ij1Helper.dispose(); legacyInjector.setLegacyService(new DummyLegacyService()); instance = null; } // -- Event handlers -- /** * Keeps the active legacy {@link ij.ImagePlus} in sync with the active modern * {@link ImageDisplay}. */ @EventHandler protected void onEvent( @SuppressWarnings("unused") final DisplayActivatedEvent event) { syncActiveImage(); } @EventHandler protected void onEvent(@SuppressWarnings("unused") final OptionsEvent event) { optionsSynchronizer.updateModernImageJSettingsFromLegacyImageJ(); } @EventHandler protected void onEvent(final KyPressedEvent event) { final KeyCode code = event.getCode(); if (code == KeyCode.SPACE) ij1Helper.setKeyDown(KeyCode.SPACE.getCode()); if (code == KeyCode.ALT) ij1Helper.setKeyDown(KeyCode.ALT.getCode()); if (code == KeyCode.SHIFT) ij1Helper.setKeyDown(KeyCode.SHIFT.getCode()); if (code == KeyCode.CONTROL) ij1Helper.setKeyDown(KeyCode.CONTROL.getCode()); if (ij1Helper.isMacintosh() && code == KeyCode.META) { ij1Helper.setKeyDown(KeyCode.CONTROL.getCode()); } } @EventHandler protected void onEvent(final KyReleasedEvent event) { final KeyCode code = event.getCode(); if (code == KeyCode.SPACE) ij1Helper.setKeyUp(KeyCode.SPACE.getCode()); if (code == KeyCode.ALT) ij1Helper.setKeyUp(KeyCode.ALT.getCode()); if (code == KeyCode.SHIFT) ij1Helper.setKeyUp(KeyCode.SHIFT.getCode()); if (code == KeyCode.CONTROL) ij1Helper.setKeyUp(KeyCode.CONTROL.getCode()); if (ij1Helper.isMacintosh() && code == KeyCode.META) { ij1Helper.setKeyUp(KeyCode.CONTROL.getCode()); } } // -- pre-initialization /** * Makes sure that the ImageJ 1.x classes are patched. * <p> * We absolutely require that the LegacyInjector did its job before we use the * ImageJ 1.x classes. * </p> * <p> * Just loading the {@link DefaultLegacyService} class is not enough; it will * not necessarily get initialized. So we provide this method just to force * class initialization (and thereby the LegacyInjector to patch ImageJ 1.x). * </p> */ public static void preinit() { if (legacyInjector == null) { throw new RuntimeException("LegacyInjector was not instantiated!"); } } // -- helpers -- /** * Returns the legacy service associated with the ImageJ 1.x instance in the * current class loader. This method is intended to be used by the * {@link CodeHacker}; it is invoked by the javassisted methods. * * @return the legacy service */ public static DefaultLegacyService getInstance() { return instance; } /** * @throws UnsupportedOperationException if the singleton * {@code DefaultLegacyService} already exists. */ private void checkInstance() { if (instance != null) { throw new UnsupportedOperationException( "Cannot instantiate more than one DefaultLegacyService"); } } private OptionsChannels getChannels() { return optionsService.getOptions(OptionsChannels.class); } @SuppressWarnings("unused") private void updateMenus(final boolean enableBlacklist) { pluginService.reloadPlugins(); addLegacyCommands(enableBlacklist); } private void addLegacyCommands(final boolean enableBlacklist) { final LegacyPluginFinder finder = new LegacyPluginFinder(log, menuService.getMenu(), enableBlacklist); final ArrayList<PluginInfo<?>> plugins = new ArrayList<PluginInfo<?>>(); finder.findPlugins(plugins); pluginService.addPlugins(plugins); } /* 3-1-12 We are no longer going to synchronize colors from IJ1 to modern ImageJ protected class IJ1EventListener implements IJEventListener { @Override public void eventOccurred(final int eventID) { final OptionsChannels colorOpts = optionsService.getOptions(OptionsChannels.class); ColorRGB color; switch (eventID) { case ij.IJEventListener.COLOR_PICKER_CLOSED: color = AWTColors.getColorRGB(Toolbar.getForegroundColor()); colorOpts.setFgColor(color); color = AWTColors.getColorRGB(Toolbar.getBackgroundColor()); colorOpts.setBgColor(color); colorOpts.save(); break; case ij.IJEventListener.FOREGROUND_COLOR_CHANGED: color = AWTColors.getColorRGB(Toolbar.getForegroundColor()); colorOpts.setFgColor(color); colorOpts.save(); break; case ij.IJEventListener.BACKGROUND_COLOR_CHANGED: color = AWTColors.getColorRGB(Toolbar.getBackgroundColor()); colorOpts.setBgColor(color); colorOpts.save(); break; case ij.IJEventListener.LOG_WINDOW_CLOSED: // TODO - do something??? break; case ij.IJEventListener.TOOL_CHANGED: // TODO - do something??? break; default: // unknown event // do nothing break; } } } */ }
Remove dead code Signed-off-by: Johannes Schindelin <[email protected]>
core/legacy/src/main/java/imagej/legacy/DefaultLegacyService.java
Remove dead code
Java
mit
144b93420365f1970c1ae7283bf55a6bb063bc78
0
jotatoledo/Programmieren-WS16-17
package edu.kit.informatik.kachelung; public enum PositionInBoard { UPPER_RIGHT_CORNER("UPPER_RIGHT_CORNER", 3, 4, 5), DOWN_RIGH_CORNER("DOWN_RIGH_CORNER", 0, 4, 5), UPPER_LEFT_CORNER("UPPER_LEFT_CORNER", 2, 3), DOWN_LEFT_CORNER("DOWN_LEFT_CORNER", 0, 1, 2), INTERNAL("INTERNAL", 0, 1, 2, 3, 4, 5), UPPER_SIDE("UPPER_SIDE", 2, 3, 4, 5), DOWN_SIDE("DOWN_SIDE", 0, 1, 2, 5), LEFT_SIDE("LEFT_SIDE", 0, 1, 2, 3), RIGHT_SIDE("RIGHT_SIDE", 0, 3, 4, 5); public static final int UPPER_LEFT_CORNER_VALUE = 0; public static final int DOWN_LEFT_CORNER_VALUE = Board.ELEMENTS_IN_COLUMN - 1; public static final int UPPER_RIGHT_CORNER_VALUE = (Board.ELEMENTS_IN_ROW - 1) * Board.ELEMENTS_IN_COLUMN; public static final int DOWN_RIGHT_CORNER_VALUE = (Board.ELEMENTS_IN_ROW * Board.ELEMENTS_IN_COLUMN) - 1; private final int[] positions; private final String representation; PositionInBoard(String representation, int... positions) { this.positions = new int[positions.length]; for (int i = 0; i < positions.length; i++) { this.positions[i] = positions[i]; } this.representation = representation; } public int[] getPositions() { return positions; } public static PositionInBoard calculatePosition(int position) { PositionInBoard boardPositon = null; switch(position) { case(UPPER_LEFT_CORNER_VALUE): boardPositon = PositionInBoard.UPPER_LEFT_CORNER; break; case(DOWN_LEFT_CORNER_VALUE): boardPositon = PositionInBoard.DOWN_LEFT_CORNER; break; case(UPPER_RIGHT_CORNER_VALUE): boardPositon = PositionInBoard.UPPER_RIGHT_CORNER; break; case(DOWN_RIGHT_CORNER_VALUE): boardPositon = PositionInBoard.DOWN_RIGH_CORNER; break; default: if ( position % DOWN_LEFT_CORNER_VALUE != 0) { boardPositon = PositionInBoard.LEFT_SIDE; } else { if ( position % DOWN_RIGHT_CORNER_VALUE != 0) { boardPositon = PositionInBoard.RIGHT_SIDE; } else { if (position % Board.ELEMENTS_IN_COLUMN == 0) { boardPositon = PositionInBoard.UPPER_SIDE; } else { if (position % Board.ELEMENTS_IN_COLUMN == DOWN_LEFT_CORNER_VALUE) { boardPositon = PositionInBoard.DOWN_SIDE; } else { boardPositon = PositionInBoard.INTERNAL; } } } } } return boardPositon; } public String toString() { return representation; } }
src/edu/kit/informatik/kachelung/PositionInBoard.java
package edu.kit.informatik.kachelung; public enum PositionInBoard { UPPER_RIGHT_CORNER(3, 4, 5), DOWN_RIGH_CORNER(0, 4, 5), UPPER_LEFT_CORNER(2, 3), DOWN_LEFT_CORNER(0, 1, 2), INTERNAL(0, 1, 2, 3, 4, 5), UPPER_SIDE(2, 3, 4, 5), DOWN_SIDE(0, 1, 2, 5), LEFT_SIDE(0, 1, 2, 3), RIGHT_SIDE(0, 3, 4, 5); public static final int UPPER_LEFT_CORNER_VALUE = 0; public static final int DOWN_LEFT_CORNER_VALUE = Board.ELEMENTS_IN_COLUMN - 1; public static final int UPPER_RIGHT_CORNER_VALUE = (Board.ELEMENTS_IN_ROW - 1) * Board.ELEMENTS_IN_COLUMN; public static final int DOWN_RIGHT_CORNER_VALUE = (Board.ELEMENTS_IN_ROW * Board.ELEMENTS_IN_COLUMN) - 1; private final int[] positions; PositionInBoard(int... positions) { this.positions = new int[positions.length]; } public int[] getPositions() { return positions; } public static PositionInBoard calculatePosition(int position) { PositionInBoard boardPositon = null; switch(position) { case(UPPER_LEFT_CORNER_VALUE): boardPositon = PositionInBoard.UPPER_LEFT_CORNER; break; case(DOWN_LEFT_CORNER_VALUE): boardPositon = PositionInBoard.DOWN_LEFT_CORNER; break; case(UPPER_RIGHT_CORNER_VALUE): boardPositon = PositionInBoard.UPPER_RIGHT_CORNER; break; case(DOWN_RIGHT_CORNER_VALUE): boardPositon = PositionInBoard.DOWN_RIGH_CORNER; break; default: if ( position % DOWN_LEFT_CORNER_VALUE != 0) { boardPositon = PositionInBoard.LEFT_SIDE; } else { if ( position % DOWN_RIGHT_CORNER_VALUE != 0) { boardPositon = PositionInBoard.RIGHT_SIDE; } else { if (position % Board.ELEMENTS_IN_COLUMN == 0) { boardPositon = PositionInBoard.UPPER_SIDE; } else { if (position % Board.ELEMENTS_IN_COLUMN == DOWN_LEFT_CORNER_VALUE) { boardPositon = PositionInBoard.DOWN_SIDE; } else { boardPositon = PositionInBoard.INTERNAL; } } } } } return boardPositon; } }
Added string representation Corrected constructor method Implemented toString method
src/edu/kit/informatik/kachelung/PositionInBoard.java
Added string representation Corrected constructor method Implemented toString method
Java
mit
0bc92c6c3fbbb509bcc4d2dcb1a0925580f3623e
0
mscott250/GroupProgrammingTimer
package com.mscott.timer; import com.mscott.timer.scheduling.TurnScheduler; import javafx.application.Application; import javafx.stage.Stage; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.support.AbstractApplicationContext; public class MainApplication extends Application { private AbstractApplicationContext context; @Override public void start(Stage primaryStage) throws Exception { context = new AnnotationConfigApplicationContext("com.mscott.timer"); HostServicesWrapper hostServicesWrapper = context.getBean(HostServicesWrapper.class); hostServicesWrapper.setHostServices(getHostServices()); WindowManager windowManager = context.getBean(WindowManager.class); windowManager.showMainWindow(); } @Override public void stop() throws Exception { // stop the turn scheduler to ensure any child threads started by the timer are terminated before exiting, // if this isn't done then the application window closes but the process continues running until its killed TurnScheduler turnScheduler = context.getBean(TurnScheduler.class); turnScheduler.stopTurn(); context.close(); } public static void main(String[] args) { launch(args); } }
src/main/java/com/mscott/timer/MainApplication.java
package com.mscott.timer; import javafx.application.Application; import javafx.stage.Stage; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.support.AbstractApplicationContext; public class MainApplication extends Application { private AbstractApplicationContext context; @Override public void start(Stage primaryStage) throws Exception { context = new AnnotationConfigApplicationContext("com.mscott.timer"); HostServicesWrapper hostServicesWrapper = context.getBean(HostServicesWrapper.class); hostServicesWrapper.setHostServices(getHostServices()); WindowManager windowManager = context.getBean(WindowManager.class); windowManager.showMainWindow(); } @Override public void stop() throws Exception { context.close(); } public static void main(String[] args) { launch(args); } }
Fix Shutdown Bug When the application is stopped, explicitly stop the turn scheduler, to ensure that the threads created by the timer are stopped. This fixes an issue whereby when quitting the application, the window disappears but the application process carries on running until forcefully killed.
src/main/java/com/mscott/timer/MainApplication.java
Fix Shutdown Bug
Java
mit
e6f460378f9cfe6c1d9fefc07c74a28e7f90509d
0
Permafrost/Tundra.java,Permafrost/Tundra.java
/* * The MIT License (MIT) * * Copyright (c) 2015 Lachlan Dowding * * 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 permafrost.tundra.time; import java.util.Arrays; import java.util.Calendar; import java.util.SortedSet; import java.util.TimeZone; import java.util.TreeSet; import java.util.regex.Pattern; /** * A collection of convenience methods for working with time zones. */ public class TimeZoneHelper { /** * A sorted set of all time zone IDs known to the JVM. */ protected static final SortedSet<String> ZONES = new TreeSet(Arrays.asList(TimeZone.getAvailableIDs())); /** * Regular expression pattern for matching a time zone offset specified as HH:mm (hours and minutes). */ protected static final Pattern OFFSET_HHMM_PATTERN = Pattern.compile("([\\+-])?(\\d?\\d):(\\d\\d)"); /** * Regular expression pattern for matching a time zone offset specified as an XML duration string. */ protected static final Pattern OFFSET_XML_PATTERN = Pattern.compile("-?P(\\d+|T\\d+).+"); /** * Regular expression pattern for matching a time zone offset specified in milliseconds. */ protected static final Pattern OFFSET_RAW_PATTERN = Pattern.compile("[\\+-]?\\d+"); /** * The default time zone used by Tundra. */ public static final TimeZone DEFAULT_TIME_ZONE = TimeZone.getTimeZone("UTC"); /** * Disallow instantiation of this class. */ private TimeZoneHelper() {} /** * Returns the time zone associated with the given ID. * @param id A time zone ID. * @return The time zone associated with the given ID. */ public static TimeZone get(String id) { if (id == null) return null; TimeZone timezone = null; if (id.equals("$default") || id.equalsIgnoreCase("local") || id.equalsIgnoreCase("self")) { timezone = self(); } else { if (id.equals("Z")) { id = "UTC"; } else { java.util.regex.Matcher matcher = OFFSET_HHMM_PATTERN.matcher(id); if (matcher.matches()) { String sign = matcher.group(1); String hours = matcher.group(2); String minutes = matcher.group(3); int offset = Integer.parseInt(hours) * 60 * 60 * 1000 + Integer.parseInt(minutes) * 60 * 1000; if (sign != null && sign.equals("-")) offset = offset * -1; String candidate = get(offset); if (candidate != null) id = candidate; } else { matcher = OFFSET_XML_PATTERN.matcher(id); if (matcher.matches()) { try { String candidate = get(Integer.parseInt(DurationHelper.format(id, "xml", "milliseconds"))); if (candidate != null) id = candidate; } catch (NumberFormatException ex) { // ignore } } else { matcher = OFFSET_RAW_PATTERN.matcher(id); if (matcher.matches()) { // try parsing the id as a raw millisecond offset try { String candidate = get(Integer.parseInt(id)); if (candidate != null) id = candidate; } catch (NumberFormatException ex) { // ignore } } } } } if (ZONES.contains(id)) { timezone = TimeZone.getTimeZone(id); } } if (timezone == null) throw new IllegalArgumentException("Unknown time zone specified: '" + id + "'"); return timezone; } /** * Returns the first matching time zone ID for the given raw millisecond time zone offset. * @param offset A time zone offset in milliseconds. * @return The ID of the first matching time zone with the given offset. */ protected static String get(int offset) { String id = null; String[] candidates = TimeZone.getAvailableIDs(offset); if (candidates != null && candidates.length > 0) id = candidates[0]; // default to the first candidate timezone ID return id; } /** * @return The JVM's default time zone. */ public static TimeZone self() { return TimeZone.getDefault(); } /** * @return All time zones known to the JVM. */ public static TimeZone[] list() { String[] id = TimeZone.getAvailableIDs(); TimeZone[] zones = new TimeZone[id.length]; for (int i = 0; i < id.length; i++) { zones[i] = get(id[i]); } return zones; } /** * Returns the given Calendar object converted to the default time zone. * @param calendar The Calendar object to be normalized. * @return The given Calendar object converted to the default time zone. */ public static Calendar normalize(Calendar calendar) { return convert(calendar, DEFAULT_TIME_ZONE); } /** * Converts the given calendar to the given time zone. * @param input The calendar to be coverted to another time zone. * @param timezone The time zone ID identifying the time zone the calendar * will be converted to. * @return A new calendar representing the same instant in time * as the given calendar but in the given time. */ public static Calendar convert(Calendar input, String timezone) { return convert(input, get(timezone)); } /** * Converts the given calendar to the given time zone. * @param input The calendar to be converted to another time zone. * @param timezone The time zone the calendar will be converted to. * @return A new calendar representing the same instant in time * as the given calendar but in the given time. */ public static Calendar convert(Calendar input, TimeZone timezone) { if (input == null || timezone == null) return input; Calendar output = Calendar.getInstance(timezone); output.setTimeInMillis(input.getTimeInMillis()); return output; } /** * Replaces the time zone on the given calendar with the given time zone. * @param input The calendar to replace the time zone on. * @param timezone A time zone ID identifying the time zone the calendar will be forced into. * @return A new calendar that has been forced into a new time zone. */ public static Calendar replace(Calendar input, String timezone) { return replace(input, get(timezone)); } /** * Replaces the time zone on the given calendar with the given time zone. * @param input The calendar to replace the time zone on. * @param timezone The new time zone the calendar will be forced into. * @return A new calendar that has been forced into a new time zone. */ public static Calendar replace(Calendar input, TimeZone timezone) { if (input == null || timezone == null) return input; long instant = input.getTimeInMillis(); TimeZone currentZone = input.getTimeZone(); int currentOffset = currentZone.getOffset(instant); int desiredOffset = timezone.getOffset(instant); // reset instant to UTC time then force it to input timezone instant = instant + currentOffset - desiredOffset; // convert to output zone Calendar output = Calendar.getInstance(timezone); output.setTimeInMillis(instant); return output; } }
src/main/java/permafrost/tundra/time/TimeZoneHelper.java
/* * The MIT License (MIT) * * Copyright (c) 2015 Lachlan Dowding * * 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 permafrost.tundra.time; /** * A collection of convenience methods for working with time zones. */ public class TimeZoneHelper { private static java.util.SortedSet<String> ZONES = new java.util.TreeSet(java.util.Arrays.asList(java.util.TimeZone.getAvailableIDs())); private static java.util.regex.Pattern OFFSET_HHMM_PATTERN = java.util.regex.Pattern.compile("([\\+-])?(\\d?\\d):(\\d\\d)"); private static java.util.regex.Pattern OFFSET_XML_PATTERN = java.util.regex.Pattern.compile("-?P(\\d+|T\\d+).+"); private static java.util.regex.Pattern OFFSET_RAW_PATTERN = java.util.regex.Pattern.compile("[\\+-]?\\d+"); /** * Disallow instantiation of this class. */ private TimeZoneHelper() {} /** * Returns the time zone associated with the given ID. * @param id A time zone ID. * @return The time zone associated with the given ID. */ public static java.util.TimeZone get(String id) { if (id == null) return null; java.util.TimeZone timezone = null; if (id.equals("$default") || id.equalsIgnoreCase("local") || id.equalsIgnoreCase("self")) { timezone = self(); } else { if (id.equals("Z")) { id = "UTC"; } else { java.util.regex.Matcher matcher = OFFSET_HHMM_PATTERN.matcher(id); if (matcher.matches()) { String sign = matcher.group(1); String hours = matcher.group(2); String minutes = matcher.group(3); int offset = Integer.parseInt(hours) * 60 * 60 * 1000 + Integer.parseInt(minutes) * 60 * 1000; if (sign != null && sign.equals("-")) offset = offset * -1; String candidate = get(offset); if (candidate != null) id = candidate; } else { matcher = OFFSET_XML_PATTERN.matcher(id); if (matcher.matches()) { try { String candidate = get(Integer.parseInt(DurationHelper.format(id, "xml", "milliseconds"))); if (candidate != null) id = candidate; } catch (NumberFormatException ex) { // ignore } } else { matcher = OFFSET_RAW_PATTERN.matcher(id); if (matcher.matches()) { // try parsing the id as a raw millisecond offset try { String candidate = get(Integer.parseInt(id)); if (candidate != null) id = candidate; } catch (NumberFormatException ex) { // ignore } } } } } if (ZONES.contains(id)) { timezone = java.util.TimeZone.getTimeZone(id); } } if (timezone == null) throw new IllegalArgumentException("Unknown time zone specified: '" + id + "'"); return timezone; } /** * Returns the first matching time zone ID for the given raw millisecond time zone offset. * @param offset A time zone offset in milliseconds. * @return The ID of the first matching time zone with the given offset. */ protected static String get(int offset) { String id = null; String[] candidates = java.util.TimeZone.getAvailableIDs(offset); if (candidates != null && candidates.length > 0) id = candidates[0]; // default to the first candidate timezone ID return id; } /** * @return The JVM's default time zone. */ public static java.util.TimeZone self() { return java.util.TimeZone.getDefault(); } /** * @return All time zones known to the JVM. */ public static java.util.TimeZone[] list() { String[] id = java.util.TimeZone.getAvailableIDs(); java.util.TimeZone[] zones = new java.util.TimeZone[id.length]; for (int i = 0; i < id.length; i++) { zones[i] = get(id[i]); } return zones; } /** * Converts the given calendar to the given time zone. * @param input The calendar to be coverted to another time zone. * @param timezone The time zone ID identifying the time zone the calendar * will be converted to. * @return A new calendar representing the same instant in time * as the given calendar but in the given time. */ public static java.util.Calendar convert(java.util.Calendar input, String timezone) { return convert(input, get(timezone)); } /** * Converts the given calendar to the given time zone. * @param input The calendar to be converted to another time zone. * @param timezone The time zone the calendar will be converted to. * @return A new calendar representing the same instant in time * as the given calendar but in the given time. */ public static java.util.Calendar convert(java.util.Calendar input, java.util.TimeZone timezone) { if (input == null || timezone == null) return input; java.util.Calendar output = java.util.Calendar.getInstance(timezone); output.setTimeInMillis(input.getTimeInMillis()); return output; } /** * Replaces the time zone on the given calendar with the given time zone. * @param input The calendar to replace the time zone on. * @param timezone A time zone ID identifying the time zone the calendar will be forced into. * @return A new calendar that has been forced into a new time zone. */ public static java.util.Calendar replace(java.util.Calendar input, String timezone) { return replace(input, get(timezone)); } /** * Replaces the time zone on the given calendar with the given time zone. * @param input The calendar to replace the time zone on. * @param timezone The new time zone the calendar will be forced into. * @return A new calendar that has been forced into a new time zone. */ public static java.util.Calendar replace(java.util.Calendar input, java.util.TimeZone timezone) { if (input == null || timezone == null) return input; long instant = input.getTimeInMillis(); java.util.TimeZone currentZone = input.getTimeZone(); int currentOffset = currentZone.getOffset(instant); int desiredOffset = timezone.getOffset(instant); // reset instant to UTC time then force it to input timezone instant = instant + currentOffset - desiredOffset; // convert to output zone java.util.Calendar output = java.util.Calendar.getInstance(timezone); output.setTimeInMillis(instant); return output; } }
Add TimeZoneHelper.normalize method
src/main/java/permafrost/tundra/time/TimeZoneHelper.java
Add TimeZoneHelper.normalize method
Java
mit
b850ce827b56f484f9442e4bf743228238b117a0
0
PeterVerzijl/Qwirkle
package com.peterverzijl.softwaresystems.qwirkle; import java.util.ArrayList; import java.util.List; //import com.peterverzijl.softwaresystems.qwirkle.collision.RectangleCollider; import com.peterverzijl.softwaresystems.qwirkle.gameengine.ui.Sprite; import com.peterverzijl.softwaresystems.qwirkle.exceptions.NotYourBlockException; import com.peterverzijl.softwaresystems.qwirkle.exceptions.NotYourTurnException; import com.peterverzijl.softwaresystems.qwirkle.gameengine.GameObject; import com.peterverzijl.softwaresystems.qwirkle.gameengine.Rect; import com.peterverzijl.softwaresystems.qwirkle.gameengine.Transform; import com.peterverzijl.softwaresystems.qwirkle.graphics.Bitmap; import com.peterverzijl.softwaresystems.qwirkle.graphics.Camera; import com.peterverzijl.softwaresystems.qwirkle.graphics.SpriteRenderer; import com.peterverzijl.softwaresystems.qwirkle.scripts.MoveOnMouse; /** * Master class for the game, this handles the setting up and running of the * game. * * @author Peter Verzijl * */ public class Game { public static final int HAND_SIZE = 6; private BlockBag mBag; private List<Player> mPlayers = new ArrayList<Player>(); private Bitmap mTilemap; private Sprite tileSprite; private Camera mMainCamera; // TODO (dennis) : Change this to a reference to the player object, please! private int mCurrentPlayer = 0; private Board mBoard; public GameObject currentBlock; public Game(List<Player> aPlayerList) { mBag = new BlockBag(); mBoard = new Board(); // TODO: DENNIS score resetten mPlayers = aPlayerList; for (int i = 0; i < mPlayers.size(); i++) { mPlayers.get(i).resetHand(); mPlayers.get(i).initHand(mBag, 6); mPlayers.get(i).setGame(this); } // Add first possible move } //test unit public void run() { while(!hasEnded()) { try { doMove(mPlayers.get(mCurrentPlayer).determineMove(mBoard.getEmptySpaces())); addBlocks(mPlayers.get(mCurrentPlayer)); mCurrentPlayer = ((mCurrentPlayer + 1) % mPlayers.size()); } catch (IllegalMoveException e) { System.err.println("Er gaan dingen mis!!!"); } } //doe iets als de game klaar is } public boolean hasEnded() { return false; } public boolean checkHand(Player player,Block block) { boolean result = false; if(player==mPlayers.get(mCurrentPlayer)){ List<Block> playerHand= mPlayers.get(mCurrentPlayer).getHand(); for (Block b : playerHand) { if (b.equals(block)) { result = true; } }} return result; } /** * Checks if all the given blocks are in the hand of the player. * * @param set * The set of blocks to check. * @return Weighter all the blocks are in the hand of the player. */ public boolean checkHand(List<Node> set) { boolean result = true; for (Node n : set) { if (!checkHand(mPlayers.get(mCurrentPlayer),n.getBlock())) { result = false; } } return result; } public void doMove(List<Node> aPlayerMove) throws IllegalMoveException{ List<Node> playersMove = aPlayerMove; boolean trade = false; if (playersMove.size() > 0 && playersMove.get(0).getPosition().getX()==GameConstants.UNSET_NODE) { trade = true; } System.out.println("checking hand!"); System.out.println("Trade = " + trade); if (checkHand(playersMove)) { System.out.println("Set in hand"); System.out.println(playersMove.size()); for (int i = 0; i < playersMove.size(); i++) { if (!trade) { //boardScale(playersMove.get(i).getPosition()); if (Board.isValid(playersMove)) { System.out.println("if isValid"); mBoard.setFrontier(playersMove.get(i)); mBoard.getPlacedBlocks().add(playersMove.get(i)); } } else { System.out.println("Now trading"); tradeBlocks(playersMove.get(i).getBlock()); } try { mPlayers.get(mCurrentPlayer).removeBlock(playersMove.get(i).getBlock()); } catch (NotYourBlockException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } else {System.out.println("checkHand was false");} System.out.println("De zet is gezet"); } public List<Node> getFrontier() { List<Node> copy = new ArrayList<Node>(); List<Node> original = mBoard.getEmptySpaces(); for(Node v : original){ copy.add(v); } return copy; } public List<Player> getPlayers(){ return mPlayers; } /** * Function gets called every frame. */ public void tick() { /* * renderHand(mPlayers.get(mCurrentPlayer)); * mPlayers.get(mCurrentPlayer).setMove(mFrontier); mCurrentPlayer = * (mCurrentPlayer + 1) % mPlayers.size(); * addBlocks(mPlayers.get(mCurrentPlayer)); System.out.println( * "Now the new board will get rendered"); renderBlocks(); */ } /** * Method that makes sure that the player gets enough stones from the gameBag * @param aPlayer * @return */ public List<Block> addBlocks(Player aPlayer) { List<Block> newBlocks= new ArrayList<Block>(); while (aPlayer.getHand().size() != 6 && mBag.blocks.size() - (6 - aPlayer.getHand().size()) > -1) { Block blockFromBag=mBag.drawBlock(); newBlocks.add(blockFromBag); aPlayer.addBlock(blockFromBag); } return newBlocks; } public List<Node> getCopyBoard(){ return mBoard.getPlacedBlocks(); } public List<Block> addStone(int aAmount) { List<Block> newBlocks = new ArrayList<Block>(); for (int i = 0; i < aAmount; i++) { newBlocks.add(mBag.drawBlock()); } return newBlocks; } public void tradeBlocks(Block aBlock) { mBag.blocks.add(aBlock); } /** * Trades a block with the bag. * @param player The player who does the trade. * @param block The block type the player wants to trade. * @throws NotYourTurnException Thrown if this function is called when the player is not the current player. * @throws NotYourBlockException Thrown if you try to trade a block that is not yours. */ public Block tradeBlock(Player player, Block block) throws NotYourTurnException, NotYourBlockException { // Look if we are the current player if (player == mPlayers.get(mCurrentPlayer)) { if (checkHand(player,block)) { // Do the trade Block newBlock = mBag.drawBlock(); player.removeBlock(block); // Don't change this order! player.addBlock(newBlock); // !! mBag.returnBlock(block); // !! return newBlock; } else { throw new NotYourBlockException(); } } else { throw new NotYourTurnException(); } } /** * Removes a player from the game. * @param player */ public void removePlayer(Player player) { mPlayers.remove(player); } /** * Returns the current amount of stones in the stone bag. * @return The amount of stones left in the bag. */ public int getNumStonesInBag() { return mBag.blocks.size();} }
src/com/peterverzijl/softwaresystems/qwirkle/Game.java
package com.peterverzijl.softwaresystems.qwirkle; import java.util.ArrayList; import java.util.List; //import com.peterverzijl.softwaresystems.qwirkle.collision.RectangleCollider; import com.peterverzijl.softwaresystems.qwirkle.gameengine.ui.Sprite; import com.peterverzijl.softwaresystems.qwirkle.exceptions.NotYourBlockException; import com.peterverzijl.softwaresystems.qwirkle.exceptions.NotYourTurnException; import com.peterverzijl.softwaresystems.qwirkle.gameengine.GameObject; import com.peterverzijl.softwaresystems.qwirkle.gameengine.Rect; import com.peterverzijl.softwaresystems.qwirkle.gameengine.Transform; import com.peterverzijl.softwaresystems.qwirkle.graphics.Bitmap; import com.peterverzijl.softwaresystems.qwirkle.graphics.Camera; import com.peterverzijl.softwaresystems.qwirkle.graphics.SpriteRenderer; import com.peterverzijl.softwaresystems.qwirkle.scripts.MoveOnMouse; /** * Master class for the game, this handles the setting up and running of the * game. * * @author Peter Verzijl * */ public class Game { public static final int HAND_SIZE = 6; private BlockBag mBag; private List<Player> mPlayers = new ArrayList<Player>(); private Bitmap mTilemap; private Sprite tileSprite; private Camera mMainCamera; // TODO (dennis) : Change this to a reference to the player object, please! private int mCurrentPlayer = 0; private Board mBoard; public GameObject currentBlock; public Game(List<Player> aPlayerList) { mBag = new BlockBag(); mBoard = new Board(); // TODO: DENNIS score resetten mPlayers = aPlayerList; for (int i = 0; i < mPlayers.size(); i++) { mPlayers.get(i).resetHand(); mPlayers.get(i).initHand(mBag, 6); mPlayers.get(i).setGame(this); } // Add first possible move } //test unit public void run() { while(!hasEnded()) { try { doMove(mPlayers.get(mCurrentPlayer).determineMove(mBoard.getEmptySpaces())); addBlocks(mPlayers.get(mCurrentPlayer)); mCurrentPlayer = ((mCurrentPlayer + 1) % mPlayers.size()); } catch (IllegalMoveException e) { System.err.println("Er gaan dingen mis!!!"); } } //doe iets als de game klaar is } public boolean hasEnded() { return false; } public boolean checkHand(Player player,Block block) { boolean result = false; if(player==mPlayers.get(mCurrentPlayer)){ List<Block> playerHand= mPlayers.get(mCurrentPlayer).getHand(); for (Block b : playerHand) { if (b.equals(block)) { result = true; } }} return result; } /** * Checks if all the given blocks are in the hand of the player. * * @param set * The set of blocks to check. * @return Weighter all the blocks are in the hand of the player. */ public boolean checkHand(List<Node> set) { boolean result = true; for (Node n : set) { if (!checkHand(mPlayers.get(mCurrentPlayer),n.getBlock())) { result = false; } } return result; } public void doMove(List<Node> aPlayerMove) throws IllegalMoveException{ List<Node> playersMove = aPlayerMove; boolean trade = false; if (playersMove.size() > 0 && playersMove.get(0).getPosition().getX()==GameConstants.UNSET_NODE) { trade = true; } System.out.println("checking hand!"); System.out.println("Trade = " + trade); if (checkHand(playersMove)) { System.out.println("Set in hand"); System.out.println(playersMove.size()); for (int i = 0; i < playersMove.size(); i++) { if (!trade) { //boardScale(playersMove.get(i).getPosition()); if (Board.isValid(playersMove)) { System.out.println("if isValid"); mBoard.setFrontier(playersMove.get(i)); mBoard.getPlacedBlocks().add(playersMove.get(i)); } } else { System.out.println("Now trading"); tradeBlocks(playersMove.get(i).getBlock()); } try { mPlayers.get(mCurrentPlayer).removeBlock(playersMove.get(i).getBlock()); } catch (NotYourBlockException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } else {System.out.println("checkHand was false");} System.out.println("De zet is gezet"); } public List<Node> getFrontier() { List<Node> copy = new ArrayList<Node>(); List<Node> original = mBoard.getEmptySpaces(); for(Node v : original){ copy.add(v); } return copy; } public List<Player> getPlayers(){ return mPlayers; } /** * Function gets called every frame. */ public void tick() { /* * renderHand(mPlayers.get(mCurrentPlayer)); * mPlayers.get(mCurrentPlayer).setMove(mFrontier); mCurrentPlayer = * (mCurrentPlayer + 1) % mPlayers.size(); * addBlocks(mPlayers.get(mCurrentPlayer)); System.out.println( * "Now the new board will get rendered"); renderBlocks(); */ } public void addBlocks(Player aPlayer) { while (aPlayer.getHand().size() != 6 && mBag.blocks.size() - (6 - aPlayer.getHand().size()) > -1) { aPlayer.addBlock(mBag.drawBlock()); } } public List<Node> getCopyBoard(){ return mBoard.getPlacedBlocks(); } public List<Block> addStone(int aAmount) { List<Block> newBlocks = new ArrayList<Block>(); for (int i = 0; i < aAmount; i++) { newBlocks.add(mBag.drawBlock()); } return newBlocks; } public void tradeBlocks(Block aBlock) { mBag.blocks.add(aBlock); } /** * Trades a block with the bag. * @param player The player who does the trade. * @param block The block type the player wants to trade. * @throws NotYourTurnException Thrown if this function is called when the player is not the current player. * @throws NotYourBlockException Thrown if you try to trade a block that is not yours. */ public Block tradeBlock(Player player, Block block) throws NotYourTurnException, NotYourBlockException { // Look if we are the current player if (player == mPlayers.get(mCurrentPlayer)) { if (checkHand(player,block)) { // Do the trade Block newBlock = mBag.drawBlock(); player.removeBlock(block); // Don't change this order! player.addBlock(newBlock); // !! mBag.returnBlock(block); // !! return newBlock; } else { throw new NotYourBlockException(); } } else { throw new NotYourTurnException(); } } /** * Removes a player from the game. * @param player */ public void removePlayer(Player player) { mPlayers.remove(player); } /** * Returns the current amount of stones in the stone bag. * @return The amount of stones left in the bag. */ public int getNumStonesInBag() { return mBag.blocks.size();} }
Chagned addBlocks(Player aPlayer) Added a List<Block> as a return
src/com/peterverzijl/softwaresystems/qwirkle/Game.java
Chagned addBlocks(Player aPlayer)
Java
mit
de0aeda0c8324f8f2b531ddefb4225600c823f13
0
btk5h/skript-mirror
package com.btk5h.skriptmirror.skript; import ch.njol.skript.ScriptLoader; import ch.njol.skript.classes.ClassInfo; import ch.njol.skript.classes.Converter; import ch.njol.skript.classes.Parser; import ch.njol.skript.classes.Serializer; import ch.njol.skript.lang.ParseContext; import ch.njol.skript.registrations.Classes; import ch.njol.skript.registrations.Converters; import ch.njol.yggdrasil.Fields; import com.btk5h.skriptmirror.JavaType; import com.btk5h.skriptmirror.LibraryLoader; import com.btk5h.skriptmirror.Null; import com.btk5h.skriptmirror.ObjectWrapper; import com.btk5h.skriptmirror.skript.custom.CustomImport; import org.bukkit.event.Event; import java.io.File; import java.io.NotSerializableException; import java.io.StreamCorruptedException; import java.util.Arrays; import java.util.stream.Collectors; public class Types { static { Classes.registerClass(new ClassInfo<>(Event.class, "event") .user("events?") .parser(new Parser<Event>() { @Override public Event parse(String s, ParseContext parseContext) { return null; } @Override public boolean canParse(ParseContext context) { return false; } @Override public String toString(Event e, int i) { return e.getEventName(); } @Override public String toVariableNameString(Event e) { return e.toString(); } @Override public String getVariableNamePattern() { return ".+"; } })); Classes.registerClass(new ClassInfo<>(JavaType.class, "javatype") .user("javatypes?") .parser(new Parser<JavaType>() { @Override public JavaType parse(String s, ParseContext context) { File script = ScriptLoader.currentScript == null ? null : ScriptLoader.currentScript.getFile(); return CustomImport.lookup(script, s); } @Override public boolean canParse(ParseContext context) { // default context handled in CustomImport$ImportHandler return context != ParseContext.DEFAULT; } @Override public String toString(JavaType o, int flags) { return o.getJavaClass().getName(); } @Override public String toVariableNameString(JavaType o) { return "type:" + o.getJavaClass().getName(); } @Override public String getVariableNamePattern() { return "type:.+"; } }) .serializer(new Serializer<JavaType>() { @Override public Fields serialize(JavaType cls) throws NotSerializableException { Fields f = new Fields(); f.putObject("type", cls.getJavaClass().getName()); return f; } @Override public void deserialize(JavaType o, Fields f) throws StreamCorruptedException, NotSerializableException { } @Override protected JavaType deserialize(Fields fields) throws StreamCorruptedException, NotSerializableException { try { return new JavaType(LibraryLoader.getClassLoader().loadClass((String) fields.getObject("type"))); } catch (ClassNotFoundException e) { throw new NotSerializableException(); } } @Override public boolean mustSyncDeserialization() { return false; } @Override public boolean canBeInstantiated(Class<? extends JavaType> aClass) { return false; } })); Converters.registerConverter(ClassInfo.class, JavaType.class, ((Converter<ClassInfo, JavaType>) c -> new JavaType(c.getC()))); Classes.registerClass(new ClassInfo<>(Null.class, "null") .parser(new Parser<Null>() { @Override public Null parse(String s, ParseContext context) { return null; } @Override public boolean canParse(ParseContext context) { return false; } @Override public String toString(Null o, int flags) { return "null"; } @Override public String toVariableNameString(Null o) { return "null"; } @Override public String getVariableNamePattern() { return "null"; } }) .serializer(new Serializer<Null>() { @Override public Fields serialize(Null o) throws NotSerializableException { return new Fields(); } @Override public void deserialize(Null o, Fields f) throws StreamCorruptedException, NotSerializableException { } @Override protected Null deserialize(Fields fields) throws StreamCorruptedException, NotSerializableException { return Null.getInstance(); } @Override public boolean mustSyncDeserialization() { return false; } @Override public boolean canBeInstantiated(Class<? extends Null> c) { return false; } }) ); Classes.registerClass(new ClassInfo<>(ObjectWrapper.class, "javaobject") .user("javaobjects?") .parser(new Parser<ObjectWrapper>() { @Override public ObjectWrapper parse(String s, ParseContext context) { return null; } @Override public boolean canParse(ParseContext context) { return false; } @Override public String toString(ObjectWrapper o, int flags) { if (o instanceof ObjectWrapper.OfArray) { return Arrays.stream(((ObjectWrapper.OfArray) o).get()) .map(Classes::toString) .collect(Collectors.joining(", ")); } return Classes.toString(o.get()); } @Override public String toVariableNameString(ObjectWrapper o) { return o.toString(); } @Override public String getVariableNamePattern() { return ".+"; } }) ); } }
src/main/java/com/btk5h/skriptmirror/skript/Types.java
package com.btk5h.skriptmirror.skript; import ch.njol.skript.classes.ClassInfo; import ch.njol.skript.classes.Converter; import ch.njol.skript.classes.Parser; import ch.njol.skript.classes.Serializer; import ch.njol.skript.lang.ParseContext; import ch.njol.skript.registrations.Classes; import ch.njol.skript.registrations.Converters; import ch.njol.yggdrasil.Fields; import com.btk5h.skriptmirror.JavaType; import com.btk5h.skriptmirror.LibraryLoader; import com.btk5h.skriptmirror.Null; import com.btk5h.skriptmirror.ObjectWrapper; import org.bukkit.event.Event; import java.io.NotSerializableException; import java.io.StreamCorruptedException; import java.util.Arrays; import java.util.stream.Collectors; public class Types { static { Classes.registerClass(new ClassInfo<>(Event.class, "event") .user("events?") .parser(new Parser<Event>() { @Override public Event parse(String s, ParseContext parseContext) { return null; } @Override public boolean canParse(ParseContext context) { return false; } @Override public String toString(Event e, int i) { return e.getEventName(); } @Override public String toVariableNameString(Event e) { return e.toString(); } @Override public String getVariableNamePattern() { return ".+"; } })); Classes.registerClass(new ClassInfo<>(JavaType.class, "javatype") .user("javatypes?") .parser(new Parser<JavaType>() { @Override public JavaType parse(String s, ParseContext context) { return null; } @Override public boolean canParse(ParseContext context) { return false; } @Override public String toString(JavaType o, int flags) { return o.getJavaClass().getName(); } @Override public String toVariableNameString(JavaType o) { return "type:" + o.getJavaClass().getName(); } @Override public String getVariableNamePattern() { return "type:.+"; } }) .serializer(new Serializer<JavaType>() { @Override public Fields serialize(JavaType cls) throws NotSerializableException { Fields f = new Fields(); f.putObject("type", cls.getJavaClass().getName()); return f; } @Override public void deserialize(JavaType o, Fields f) throws StreamCorruptedException, NotSerializableException { } @Override protected JavaType deserialize(Fields fields) throws StreamCorruptedException, NotSerializableException { try { return new JavaType(LibraryLoader.getClassLoader().loadClass((String) fields.getObject("type"))); } catch (ClassNotFoundException e) { throw new NotSerializableException(); } } @Override public boolean mustSyncDeserialization() { return false; } @Override public boolean canBeInstantiated(Class<? extends JavaType> aClass) { return false; } })); Converters.registerConverter(ClassInfo.class, JavaType.class, ((Converter<ClassInfo, JavaType>) c -> new JavaType(c.getC()))); Classes.registerClass(new ClassInfo<>(Null.class, "null") .parser(new Parser<Null>() { @Override public Null parse(String s, ParseContext context) { return null; } @Override public boolean canParse(ParseContext context) { return false; } @Override public String toString(Null o, int flags) { return "null"; } @Override public String toVariableNameString(Null o) { return "null"; } @Override public String getVariableNamePattern() { return "null"; } }) .serializer(new Serializer<Null>() { @Override public Fields serialize(Null o) throws NotSerializableException { return new Fields(); } @Override public void deserialize(Null o, Fields f) throws StreamCorruptedException, NotSerializableException { } @Override protected Null deserialize(Fields fields) throws StreamCorruptedException, NotSerializableException { return Null.getInstance(); } @Override public boolean mustSyncDeserialization() { return false; } @Override public boolean canBeInstantiated(Class<? extends Null> c) { return false; } }) ); Classes.registerClass(new ClassInfo<>(ObjectWrapper.class, "javaobject") .user("javaobjects?") .parser(new Parser<ObjectWrapper>() { @Override public ObjectWrapper parse(String s, ParseContext context) { return null; } @Override public boolean canParse(ParseContext context) { return false; } @Override public String toString(ObjectWrapper o, int flags) { if (o instanceof ObjectWrapper.OfArray) { return Arrays.stream(((ObjectWrapper.OfArray) o).get()) .map(Classes::toString) .collect(Collectors.joining(", ")); } return Classes.toString(o.get()); } @Override public String toVariableNameString(ObjectWrapper o) { return o.toString(); } @Override public String getVariableNamePattern() { return ".+"; } }) ); } }
Allow imports to be parsed as literals
src/main/java/com/btk5h/skriptmirror/skript/Types.java
Allow imports to be parsed as literals
Java
mit
bfc262a45fa2db44c02530f672b0ec6406cb65ef
0
mschmidae/analysis-model,jenkinsci/analysis-model,jenkinsci/analysis-model,jenkinsci/analysis-model,mschmidae/analysis-model,mschmidae/analysis-model,jenkinsci/analysis-model
package edu.hm.hafner.analysis; import javax.annotation.Nonnull; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Spliterator; import java.util.Spliterators; import java.util.UUID; import java.util.function.Function; import java.util.function.Predicate; import java.util.regex.Pattern; import java.util.stream.Stream; import java.util.stream.StreamSupport; import org.eclipse.collections.api.list.ImmutableList; import org.eclipse.collections.api.set.ImmutableSet; import org.eclipse.collections.api.set.sorted.ImmutableSortedSet; import org.eclipse.collections.impl.collector.Collectors2; import org.eclipse.collections.impl.factory.Lists; import edu.hm.hafner.util.Ensure; import edu.hm.hafner.util.NoSuchElementException; import static java.util.stream.Collectors.*; /** * A set of {@link Issue issues}: it contains no duplicate elements, i.e. it models the mathematical <i>set</i> * abstraction. Furthermore, this set of issues provides a <i>total ordering</i> on its elements. I.e., the issues in * this set are ordered by their index in this set: the first added issue is at position 0, the second added issues is * at position 1, and so on. <p> <p> Additionally, this set of issues provides methods to find and filter issues based * on different properties. In order to create issues use the provided {@link IssueBuilder builder} class. </p> * * @param <T> * type of the issues * * @author Ullrich Hafner */ @SuppressWarnings("PMD.ExcessivePublicCount") public class Issues<T extends Issue> implements Iterable<T>, Serializable { private static final long serialVersionUID = 1L; // release 1.0.0 private static final String DEFAULT_ID = "unset"; private final Set<T> elements = new LinkedHashSet<>(); private final int[] sizeOfPriority = new int[Priority.values().length]; private final List<String> infoMessages = new ArrayList<>(); private final List<String> errorMessages = new ArrayList<>(); private int sizeOfDuplicates = 0; private String id = DEFAULT_ID; /** * Returns a predicate that checks if the package name of an issue is equal to the specified package name. * * @param packageName * the package name to match * * @return the predicate */ public static Predicate<Issue> byPackageName(final String packageName) { return issue -> issue.getPackageName().equals(packageName); } /** * Returns a predicate that checks if the file name of an issue is equal to the specified file name. * * @param fileName * the package name to match * * @return the predicate */ public static Predicate<Issue> byFileName(final String fileName) { return issue -> issue.getFileName().equals(fileName); } /** * Creates a new empty instance of {@link Issues}. */ public Issues() { // no elements to add } /** * Creates a new instance of {@link Issues} that will be initialized with the specified collection of {@link Issue} * instances. * * @param issues * the initial set of issues for this instance */ public Issues(final Collection<? extends T> issues) { for (T issue : issues) { add(issue); } } /** * Creates a new instance of {@link Issues} that will be initialized with the specified collection of {@link Issue} * instances. * * @param issues * the initial set of issues for this instance */ public Issues(final Stream<? extends T> issues) { issues.forEach(issue -> add(issue)); } /** * Appends all of the specified elements to the end of this container, preserving the order of the array elements. * Duplicates will be skipped (the number of skipped elements is available using the method {@link * #getDuplicatesSize()}. * * @param issue * the issue to append * @param additionalIssues * the additional issue to append */ @SafeVarargs public final void add(final T issue, final T... additionalIssues) { add(issue); for (T additional : additionalIssues) { add(additional); } } private void add(final T issue) { if (elements.contains(issue)) { sizeOfDuplicates++; // elements are marked as duplicate if the fingerprint is different } else { elements.add(issue); sizeOfPriority[issue.getPriority().ordinal()]++; } } /** * Appends all of the elements in the specified collection to the end of this container, in the order that they are * returned by the specified collection's iterator. Duplicates will be skipped (the number of skipped elements is * available using the method {@link #getDuplicatesSize()}. * * @param issues * the issues to append */ public void addAll(final Collection<? extends T> issues) { for (T issue : issues) { add(issue); } } /** * Appends all of the elements in the specified array of issues to the end of this container, in the order that they * are returned by the specified collection's iterator. Duplicates will be skipped (the number of skipped elements * is available using the method {@link #getDuplicatesSize()}. * * @param issues * the issues to append * @param additionalIssues * the additional issue to append */ @SafeVarargs public final void addAll(final Issues<T> issues, final Issues<T>... additionalIssues) { copyProperties(issues, this); for (Issues<T> other : additionalIssues) { copyProperties(other, this); } } /** * Removes the issue with the specified ID. Note that the number of reported duplicates is not affected by calling * this method. * * @param issueId * the ID of the issue * * @return the removed element * @throws NoSuchElementException * if there is no such issue found */ public T remove(final UUID issueId) { for (T element : elements) { if (element.getId().equals(issueId)) { elements.remove(element); return element; } } throw new NoSuchElementException("No issue found with id %s.", issueId); } /** * Returns the issue with the specified ID. * * @param issueId * the ID of the issue * * @return the found issue * @throws NoSuchElementException * if there is no such issue found */ public T findById(final UUID issueId) { for (T issue : elements) { if (issue.getId().equals(issueId)) { return issue; } } throw new NoSuchElementException("No issue found with id %s.", issueId); } /** * Finds all issues that match the specified criterion. * * @param criterion * the filter criterion * * @return the found issues */ public ImmutableSet<T> findByProperty(final Predicate<? super T> criterion) { return filterElements(criterion).collect(Collectors2.toImmutableSet()); } /** * Finds all issues that match the specified criterion. * * @param criterion * the filter criterion * * @return the found issues */ public Issues<T> filter(final Predicate<? super T> criterion) { return new Issues<>(filterElements(criterion).collect(toList())); } private Stream<T> filterElements(final Predicate<? super T> criterion) { return elements.stream().filter(criterion); } @Nonnull @Override public Iterator<T> iterator() { return Lists.immutable.withAll(elements).iterator(); } /** * Creates a new sequential {@code Stream} of {@link Issue} instances from a {@code Spliterator}. * * @return a new sequential {@code Stream} */ public Stream<Issue> stream() { return StreamSupport.stream(Spliterators.spliterator(iterator(), 0L, Spliterator.NONNULL), false); } /** * Returns the number of issues in this container. * * @return total number of issues */ public int size() { return elements.size(); } /** * Returns whether this container is empty. * * @return {@code true} if this container is empty, {@code false} otherwise * @see #isNotEmpty() */ public boolean isEmpty() { return size() == 0; } /** * Returns whether this container is not empty. * * @return {@code true} if this container is not empty, {@code false} otherwise * @see #isEmpty() */ public boolean isNotEmpty() { return !isEmpty(); } /** * Returns the number of issues in this container. * * @return total number of issues */ public int getSize() { return size(); } /** * Returns the number of duplicates. Every issue that has been added to this container, but already is part of this * container (based on {@link #equals(Object)}) is counted as a duplicate. Duplicates are not stored in this * container. * * @return total number of duplicates */ public int getDuplicatesSize() { return sizeOfDuplicates; } /** * Returns the number of issues of the specified priority. * * @param priority * the priority of the issues * * @return total number of issues */ public int getSizeOf(final Priority priority) { return sizeOfPriority[priority.ordinal()]; } /** * Returns the number of issues of the specified priority. * * @param priority * the priority of the issues * * @return total number of issues */ public int sizeOf(final Priority priority) { return getSizeOf(priority); } /** * Returns the number of high priority issues in this container. * * @return total number of high priority issues */ public int getHighPrioritySize() { return getSizeOf(Priority.HIGH); } /** * Returns the number of normal priority issues in this container. * * @return total number of normal priority issues */ public int getNormalPrioritySize() { return getSizeOf(Priority.NORMAL); } /** * Returns the number of low priority issues in this container. * * @return total number of low priority of issues */ public int getLowPrioritySize() { return getSizeOf(Priority.LOW); } /** * Returns the issue with the specified index. * * @param index * the index * * @return the issue at the specified index * @throws IndexOutOfBoundsException * if there is no element for the given index */ public T get(final int index) { if (index < 0 || index >= size()) { throw new IndexOutOfBoundsException("No such index " + index + " in " + toString()); } Iterator<T> all = elements.iterator(); for (int i = 0; i < index; i++) { all.next(); // skip this element } return all.next(); } @Override public String toString() { return String.format("%d issues", size()); } // FIXME: why immutable? This is no internal representation /** * Returns the affected modules for all issues of this container. * * @return the affected modules */ public ImmutableSortedSet<String> getModules() { return getProperties(issue -> issue.getModuleName()); } /** * Returns the affected packages for all issues of this container. * * @return the affected packages */ public ImmutableSortedSet<String> getPackages() { return getProperties(issue -> issue.getPackageName()); } /** * Returns the affected files for all issues of this container. * * @return the affected files */ public ImmutableSortedSet<String> getFiles() { return getProperties(issue -> issue.getFileName()); } /** * Returns the used categories for all issues of this container. * * @return the used categories */ public ImmutableSortedSet<String> getCategories() { return getProperties(issue -> issue.getCategory()); } /** * Returns the used types for all issues of this container. * * @return the used types */ public ImmutableSortedSet<String> getTypes() { return getProperties(issue -> issue.getType()); } /** * Returns the names of the tools that did report the issues of this container. * * @return the tools */ public ImmutableSortedSet<String> getToolNames() { return getProperties(issue -> issue.getOrigin()); } /** * Returns the different values for a given property for all issues of this container. * * @param propertiesMapper * the properties mapper that selects the property * * @return the set of different values * @see #getFiles() */ public ImmutableSortedSet<String> getProperties(final Function<? super T, String> propertiesMapper) { return elements.stream().map(propertiesMapper).collect(Collectors2.toImmutableSortedSet()); } /** * Returns the number of occurrences for every existing value of a given property for all issues of this container. * * @param propertiesMapper * the properties mapper that selects the property to evaluate * * @return a mapping of: property value -> number of issues for that value * @see #getProperties(Function) */ public Map<String, Integer> getPropertyCount(final Function<? super T, String> propertiesMapper) { return elements.stream().collect(groupingBy(propertiesMapper, reducing(0, issue -> 1, Integer::sum))); } /** * Returns the number of occurrences for every existing value of a given property for all issues of this container. * * @param propertiesMapper * the properties mapper that selects the property to evaluate * * @return a mapping of: property value -> number of issues for that value * @see #getProperties(Function) */ public Map<String, Issues<T>> groupByProperty(final Function<? super T, String> propertiesMapper) { Map<String, List<T>> issues = elements.stream().collect(groupingBy(propertiesMapper)); return issues.entrySet().stream() .collect(toMap(e -> e.getKey(), e -> new Issues<>(e.getValue()))); } /** * Returns a shallow copy of this issue container. * * @return a new issue container that contains the same elements in the same order */ public Issues<T> copy() { Issues<T> copied = new Issues<>(); copyProperties(this, copied); return copied; } private void copyProperties(final Issues<T> source, final Issues<T> destination) { if (destination.hasId() && !source.id.equals(destination.id)) { throw new IllegalArgumentException( String.format("When merging two issues instances the IDs must match: %s <-> %s", source.getId(), destination.getId())); } destination.addAll(source.elements); destination.sizeOfDuplicates += source.sizeOfDuplicates; destination.infoMessages.addAll(source.infoMessages); destination.errorMessages.addAll(source.errorMessages); destination.id = source.id; } /** * Sets the ID of this set of issues. * * @param id * ID of this set of issues */ public void setId(final String id) { Ensure.that(id).isNotNull(); this.id = id; } /** * Returns the ID of this set of issues. * * @return the ID */ public String getId() { return id; } /** * Returns whether this set of issues has an associated ID. * * @return {@code true} if this set has an ID; {@code false} otherwise */ public boolean hasId() { return !DEFAULT_ID.equals(getId()); } /** * Logs the specified information message. Use this method to log any useful information when composing this set of issues. * * @param format * A <a href="../util/Formatter.html#syntax">format string</a> * @param args * Arguments referenced by the format specifiers in the format string. If there are more arguments than * format specifiers, the extra arguments are ignored. The number of arguments is variable and may be * zero. * * @see #getInfoMessages() */ public void logInfo(final String format, final Object... args) { infoMessages.add(String.format(format, args)); } /** * Logs the specified error message. Use this method to log any error when composing this set of issues. * * @param format * A <a href="../util/Formatter.html#syntax">format string</a> * @param args * Arguments referenced by the format specifiers in the format string. If there are more arguments than * format specifiers, the extra arguments are ignored. The number of arguments is variable and may be * zero. * * @see #getInfoMessages() */ public void logError(final String format, final Object... args) { errorMessages.add(String.format(format, args)); } /** * Returns the info messages that have been reported since the creation of this set of issues. * * @return the info messages */ public ImmutableList<String> getInfoMessages() { return Lists.immutable.ofAll(infoMessages); } /** * Returns the error messages that have been reported since the creation of this set of issues. * * @return the error messages */ public ImmutableList<String> getErrorMessages() { return Lists.immutable.ofAll(errorMessages); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } Issues<?> issues = (Issues<?>) obj; if (sizeOfDuplicates != issues.sizeOfDuplicates) { return false; } if (!elements.equals(issues.elements)) { return false; } if (!Arrays.equals(sizeOfPriority, issues.sizeOfPriority)) { return false; } if (!infoMessages.equals(issues.infoMessages)) { return false; } return id.equals(issues.id); } @Override public int hashCode() { int result = elements.hashCode(); result = 31 * result + Arrays.hashCode(sizeOfPriority); result = 31 * result + infoMessages.hashCode(); result = 31 * result + sizeOfDuplicates; result = 31 * result + id.hashCode(); return result; } /** * Builds a combined filter based on several include and exclude filters. * * @author Raphael Furch */ public static class IssueFilterBuilder { private final Collection<Predicate<Issue>> includeFilters = new ArrayList<>(); private final Collection<Predicate<Issue>> excludeFilters = new ArrayList<>(); /** * Add a new filter for each pattern string. Add filter to include or exclude list. * * @param pattern * filter pattern. * @param propertyToFilter * Function to get a string from Issue for pattern */ private void addNewFilter(final Collection<String> pattern, final Function<Issue, String> propertyToFilter, final boolean include) { Collection<Predicate<Issue>> filters = new ArrayList<>(); for (String patter : pattern) { filters.add(issueToFilter -> Pattern.compile(patter) .matcher(propertyToFilter.apply(issueToFilter)).matches() == include); } if (include) { includeFilters.addAll(filters); } else { excludeFilters.addAll(filters); } } /** * Create a IssueFilter. Combine by default all includes with or and all excludes with and. * * @return a IssueFilter which has all added filter as filter criteria. */ public Predicate<Issue> build() { return includeFilters.stream().reduce(Predicate::or).orElse(issue -> true) .and(excludeFilters.stream().reduce(Predicate::and).orElse(issue -> true)); } //<editor-fold desc="File name"> /** * Add a new filter. * * @param pattern * pattern * * @return this. */ public IssueFilterBuilder setIncludeFilenameFilter(final Collection<String> pattern) { addNewFilter(pattern, Issue::getFileName, true); return this; } /** * Add a new filter. * * @param pattern * pattern * * @return this. */ public IssueFilterBuilder setIncludeFilenameFilter(final String... pattern) { return setIncludeFilenameFilter(Arrays.asList(pattern)); } /** * Add a new filter. * * @param pattern * pattern * * @return this. */ public IssueFilterBuilder setExcludeFilenameFilter(final Collection<String> pattern) { addNewFilter(pattern, Issue::getFileName, false); return this; } /** * Add a new filter. * * @param pattern * pattern * * @return this. */ public IssueFilterBuilder setExcludeFilenameFilter(final String... pattern) { return setExcludeFilenameFilter(Arrays.asList(pattern)); } //</editor-fold> //<editor-fold desc="Package name"> /** * Add a new filter. * * @param pattern * pattern * * @return this. */ public IssueFilterBuilder setIncludePackageNameFilter(final Collection<String> pattern) { addNewFilter(pattern, Issue::getPackageName, true); return this; } /** * Add a new filter. * * @param pattern * pattern * * @return this. */ public IssueFilterBuilder setIncludePackageNameFilter(final String... pattern) { return setIncludePackageNameFilter(Arrays.asList(pattern)); } /** * Add a new filter. * * @param pattern * pattern * * @return this. */ public IssueFilterBuilder setExcludePackageNameFilter(final Collection<String> pattern) { addNewFilter(pattern, Issue::getPackageName, false); return this; } /** * Add a new filter. * * @param pattern * pattern * * @return this. */ public IssueFilterBuilder setExcludePackageNameFilter(final String... pattern) { return setExcludePackageNameFilter(Arrays.asList(pattern)); } //</editor-fold> //<editor-fold desc="Module name"> /** * Add a new filter. * * @param pattern * pattern * * @return this. */ public IssueFilterBuilder setIncludeModuleNameFilter(final Collection<String> pattern) { addNewFilter(pattern, Issue::getModuleName, true); return this; } /** * Add a new filter. * * @param pattern * pattern * * @return this. */ public IssueFilterBuilder setIncludeModuleNameFilter(final String... pattern) { return setIncludeModuleNameFilter(Arrays.asList(pattern)); } /** * Add a new filter. * * @param pattern * pattern * * @return this. */ public IssueFilterBuilder setExcludeModuleNameFilter(final Collection<String> pattern) { addNewFilter(pattern, Issue::getModuleName, false); return this; } /** * Add a new filter. * * @param pattern * pattern * * @return this. */ public IssueFilterBuilder setExcludeModuleNameFilter(final String... pattern) { return setExcludeModuleNameFilter(Arrays.asList(pattern)); } //</editor-fold> //<editor-fold desc="Category"> /** * Add a new filter. * * @param pattern * pattern * * @return this. */ public IssueFilterBuilder setIncludeCategoryFilter(final Collection<String> pattern) { addNewFilter(pattern, Issue::getCategory, true); return this; } /** * Add a new filter. * * @param pattern * pattern * * @return this. */ public IssueFilterBuilder setIncludeCategoryFilter(final String... pattern) { return setIncludeCategoryFilter(Arrays.asList(pattern)); } /** * Add a new filter. * * @param pattern * pattern * * @return this. */ public IssueFilterBuilder setExcludeCategoryFilter(final Collection<String> pattern) { addNewFilter(pattern, Issue::getCategory, false); return this; } /** * Add a new filter. * * @param pattern * pattern * * @return this. */ public IssueFilterBuilder setExcludeCategoryFilter(final String... pattern) { return setExcludeCategoryFilter(Arrays.asList(pattern)); } //</editor-fold> //<editor-fold desc="Type"> /** * Add a new filter. * * @param pattern * pattern * * @return this. */ public IssueFilterBuilder setIncludeTypeFilter(final Collection<String> pattern) { addNewFilter(pattern, Issue::getType, true); return this; } /** * Add a new filter. * * @param pattern * pattern * * @return this. */ public IssueFilterBuilder setIncludeTypeFilter(final String... pattern) { return setIncludeTypeFilter(Arrays.asList(pattern)); } /** * Add a new filter. * * @param pattern * pattern * * @return this. */ public IssueFilterBuilder setExcludeTypeFilter(final Collection<String> pattern) { addNewFilter(pattern, Issue::getType, false); return this; } /** * Add a new filter. * * @param pattern * pattern * * @return this. */ public IssueFilterBuilder setExcludeTypeFilter(final String... pattern) { return setExcludeTypeFilter(Arrays.asList(pattern)); } //</editor-fold> } }
src/main/java/edu/hm/hafner/analysis/Issues.java
package edu.hm.hafner.analysis; import javax.annotation.Nonnull; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Spliterator; import java.util.Spliterators; import java.util.UUID; import java.util.function.Function; import java.util.function.Predicate; import java.util.regex.Pattern; import java.util.stream.Stream; import java.util.stream.StreamSupport; import org.eclipse.collections.api.list.ImmutableList; import org.eclipse.collections.api.set.ImmutableSet; import org.eclipse.collections.api.set.sorted.ImmutableSortedSet; import org.eclipse.collections.impl.collector.Collectors2; import org.eclipse.collections.impl.factory.Lists; import edu.hm.hafner.util.Ensure; import edu.hm.hafner.util.NoSuchElementException; import static java.util.stream.Collectors.*; /** * A set of {@link Issue issues}: it contains no duplicate elements, i.e. it models the mathematical <i>set</i> * abstraction. Furthermore, this set of issues provides a <i>total ordering</i> on its elements. I.e., the issues in * this set are ordered by their index in this set: the first added issue is at position 0, the second added issues is * at position 1, and so on. <p> <p> Additionally, this set of issues provides methods to find and filter issues based * on different properties. In order to create issues use the provided {@link IssueBuilder builder} class. </p> * * @param <T> * type of the issues * * @author Ullrich Hafner */ @SuppressWarnings("PMD.ExcessivePublicCount") public class Issues<T extends Issue> implements Iterable<T>, Serializable { private static final long serialVersionUID = 1L; // release 1.0.0 private static final String DEFAULT_ID = "unset"; private final Set<T> elements = new LinkedHashSet<>(); private final int[] sizeOfPriority = new int[Priority.values().length]; private final List<String> infoMessages = new ArrayList<>(); private final List<String> errorMessages = new ArrayList<>(); private int sizeOfDuplicates = 0; private String id = DEFAULT_ID; /** * Returns a predicate that checks if the package name of an issue is equal to the specified package name. * * @param packageName * the package name to match * * @return the predicate */ public static Predicate<Issue> byPackageName(final String packageName) { return issue -> issue.getPackageName().equals(packageName); } /** * Returns a predicate that checks if the file name of an issue is equal to the specified file name. * * @param fileName * the package name to match * * @return the predicate */ public static Predicate<Issue> byFileName(final String fileName) { return issue -> issue.getFileName().equals(fileName); } /** * Creates a new empty instance of {@link Issues}. */ public Issues() { // no elements to add } /** * Creates a new instance of {@link Issues} that will be initialized with the specified collection of {@link Issue} * instances. * * @param issues * the initial set of issues for this instance */ public Issues(final Collection<? extends T> issues) { for (T issue : issues) { add(issue); } } /** * Creates a new instance of {@link Issues} that will be initialized with the specified collection of {@link Issue} * instances. * * @param issues * the initial set of issues for this instance */ public Issues(final Stream<? extends T> issues) { issues.forEach(issue -> add(issue)); } /** * Appends all of the specified elements to the end of this container, preserving the order of the array elements. * Duplicates will be skipped (the number of skipped elements is available using the method {@link * #getDuplicatesSize()}. * * @param issue * the issue to append * @param additionalIssues * the additional issue to append */ @SafeVarargs public final void add(final T issue, final T... additionalIssues) { add(issue); for (T additional : additionalIssues) { add(additional); } } private void add(final T issue) { if (elements.contains(issue)) { sizeOfDuplicates++; // elements are marked as duplicate if the fingerprint is different } else { elements.add(issue); sizeOfPriority[issue.getPriority().ordinal()]++; } } /** * Appends all of the elements in the specified collection to the end of this container, in the order that they are * returned by the specified collection's iterator. Duplicates will be skipped (the number of skipped elements is * available using the method {@link #getDuplicatesSize()}. * * @param issues * the issues to append */ public void addAll(final Collection<? extends T> issues) { for (T issue : issues) { add(issue); } } /** * Appends all of the elements in the specified array of issues to the end of this container, in the order that they * are returned by the specified collection's iterator. Duplicates will be skipped (the number of skipped elements * is available using the method {@link #getDuplicatesSize()}. * * @param issues * the issues to append * @param additionalIssues * the additional issue to append */ @SafeVarargs public final void addAll(final Issues<T> issues, final Issues<T>... additionalIssues) { copyProperties(issues, this); for (Issues<T> other : additionalIssues) { copyProperties(other, this); } } /** * Removes the issue with the specified ID. Note that the number of reported duplicates is not affected by calling * this method. * * @param issueId * the ID of the issue * * @return the removed element * @throws NoSuchElementException * if there is no such issue found */ public T remove(final UUID issueId) { for (T element : elements) { if (element.getId().equals(issueId)) { elements.remove(element); return element; } } throw new NoSuchElementException("No issue found with id %s.", issueId); } /** * Returns the issue with the specified ID. * * @param issueId * the ID of the issue * * @return the found issue * @throws NoSuchElementException * if there is no such issue found */ public T findById(final UUID issueId) { for (T issue : elements) { if (issue.getId().equals(issueId)) { return issue; } } throw new NoSuchElementException("No issue found with id %s.", issueId); } /** * Finds all issues that match the specified criterion. * * @param criterion * the filter criterion * * @return the found issues */ public ImmutableSet<T> findByProperty(final Predicate<? super T> criterion) { return filterElements(criterion).collect(Collectors2.toImmutableSet()); } /** * Finds all issues that match the specified criterion. * * @param criterion * the filter criterion * * @return the found issues */ public Issues<T> filter(final Predicate<? super T> criterion) { return new Issues<>(filterElements(criterion).collect(toList())); } private Stream<T> filterElements(final Predicate<? super T> criterion) { return elements.stream().filter(criterion); } @Nonnull @Override public Iterator<T> iterator() { return Lists.immutable.withAll(elements).iterator(); } /** * Creates a new sequential {@code Stream} of {@link Issue} instances from a {@code Spliterator}. * * @return a new sequential {@code Stream} */ public Stream<Issue> stream() { return StreamSupport.stream(Spliterators.spliterator(iterator(), 0L, Spliterator.NONNULL), false); } /** * Returns the number of issues in this container. * * @return total number of issues */ public int size() { return elements.size(); } /** * Returns whether this container is empty. * * @return {@code true} if this container is empty, {@code false} otherwise * @see #isNotEmpty() */ public boolean isEmpty() { return size() == 0; } /** * Returns whether this container is not empty. * * @return {@code true} if this container is not empty, {@code false} otherwise * @see #isEmpty() */ public boolean isNotEmpty() { return !isEmpty(); } /** * Returns the number of issues in this container. * * @return total number of issues */ public int getSize() { return size(); } /** * Returns the number of duplicates. Every issue that has been added to this container, but already is part of this * container (based on {@link #equals(Object)}) is counted as a duplicate. Duplicates are not stored in this * container. * * @return total number of duplicates */ public int getDuplicatesSize() { return sizeOfDuplicates; } /** * Returns the number of issues of the specified priority. * * @param priority * the priority of the issues * * @return total number of issues */ public int getSizeOf(final Priority priority) { return sizeOfPriority[priority.ordinal()]; } /** * Returns the number of issues of the specified priority. * * @param priority * the priority of the issues * * @return total number of issues */ public int sizeOf(final Priority priority) { return getSizeOf(priority); } /** * Returns the number of high priority issues in this container. * * @return total number of high priority issues */ public int getHighPrioritySize() { return getSizeOf(Priority.HIGH); } /** * Returns the number of normal priority issues in this container. * * @return total number of normal priority issues */ public int getNormalPrioritySize() { return getSizeOf(Priority.NORMAL); } /** * Returns the number of low priority issues in this container. * * @return total number of low priority of issues */ public int getLowPrioritySize() { return getSizeOf(Priority.LOW); } /** * Returns the issue with the specified index. * * @param index * the index * * @return the issue at the specified index * @throws IndexOutOfBoundsException * if there is no element for the given index */ public T get(final int index) { if (index < 0 || index >= size()) { throw new IndexOutOfBoundsException("No such index " + index + " in " + toString()); } Iterator<T> all = elements.iterator(); for (int i = 0; i < index; i++) { all.next(); // skip this element } return all.next(); } @Override public String toString() { return String.format("%d issues", size()); } /** * Returns the affected modules for all issues of this container. * * @return the affected modules */ public ImmutableSortedSet<String> getModules() { return getProperties(issue -> issue.getModuleName()); } /** * Returns the affected packages for all issues of this container. * * @return the affected packages */ public ImmutableSortedSet<String> getPackages() { return getProperties(issue -> issue.getPackageName()); } /** * Returns the affected files for all issues of this container. * * @return the affected files */ public ImmutableSortedSet<String> getFiles() { return getProperties(issue -> issue.getFileName()); } /** * Returns the used categories for all issues of this container. * * @return the used categories */ public ImmutableSortedSet<String> getCategories() { return getProperties(issue -> issue.getCategory()); } /** * Returns the used types for all issues of this container. * * @return the used types */ public ImmutableSortedSet<String> getTypes() { return getProperties(issue -> issue.getType()); } /** * Returns the names of the tools that did report the issues of this container. * * @return the tools */ public ImmutableSortedSet<String> getToolNames() { return getProperties(issue -> issue.getOrigin()); } /** * Returns the different values for a given property for all issues of this container. * * @param propertiesMapper * the properties mapper that selects the property * * @return the set of different values * @see #getFiles() */ public ImmutableSortedSet<String> getProperties(final Function<? super T, String> propertiesMapper) { return elements.stream().map(propertiesMapper).collect(Collectors2.toImmutableSortedSet()); } /** * Returns the number of occurrences for every existing value of a given property for all issues of this container. * * @param propertiesMapper * the properties mapper that selects the property to evaluate * * @return a mapping of: property value -> number of issues for that value * @see #getProperties(Function) */ public Map<String, Integer> getPropertyCount(final Function<? super T, String> propertiesMapper) { return elements.stream().collect(groupingBy(propertiesMapper, reducing(0, e -> 1, Integer::sum))); } /** * Returns a shallow copy of this issue container. * * @return a new issue container that contains the same elements in the same order */ public Issues<T> copy() { Issues<T> copied = new Issues<>(); copyProperties(this, copied); return copied; } private void copyProperties(final Issues<T> source, final Issues<T> destination) { if (destination.hasId() && !source.id.equals(destination.id)) { throw new IllegalArgumentException( String.format("When merging two issues instances the IDs must match: %s <-> %s", source.getId(), destination.getId())); } destination.addAll(source.elements); destination.sizeOfDuplicates += source.sizeOfDuplicates; destination.infoMessages.addAll(source.infoMessages); destination.errorMessages.addAll(source.errorMessages); destination.id = source.id; } /** * Sets the ID of this set of issues. * * @param id * ID of this set of issues */ public void setId(final String id) { Ensure.that(id).isNotNull(); this.id = id; } /** * Returns the ID of this set of issues. * * @return the ID */ public String getId() { return id; } /** * Returns whether this set of issues has an associated ID. * * @return {@code true} if this set has an ID; {@code false} otherwise */ public boolean hasId() { return !DEFAULT_ID.equals(getId()); } /** * Logs the specified information message. Use this method to log any useful information when composing this set of issues. * * @param format * A <a href="../util/Formatter.html#syntax">format string</a> * @param args * Arguments referenced by the format specifiers in the format string. If there are more arguments than * format specifiers, the extra arguments are ignored. The number of arguments is variable and may be * zero. * * @see #getInfoMessages() */ public void logInfo(final String format, final Object... args) { infoMessages.add(String.format(format, args)); } /** * Logs the specified error message. Use this method to log any error when composing this set of issues. * * @param format * A <a href="../util/Formatter.html#syntax">format string</a> * @param args * Arguments referenced by the format specifiers in the format string. If there are more arguments than * format specifiers, the extra arguments are ignored. The number of arguments is variable and may be * zero. * * @see #getInfoMessages() */ public void logError(final String format, final Object... args) { errorMessages.add(String.format(format, args)); } /** * Returns the info messages that have been reported since the creation of this set of issues. * * @return the info messages */ public ImmutableList<String> getInfoMessages() { return Lists.immutable.ofAll(infoMessages); } /** * Returns the error messages that have been reported since the creation of this set of issues. * * @return the error messages */ public ImmutableList<String> getErrorMessages() { return Lists.immutable.ofAll(errorMessages); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } Issues<?> issues = (Issues<?>) obj; if (sizeOfDuplicates != issues.sizeOfDuplicates) { return false; } if (!elements.equals(issues.elements)) { return false; } if (!Arrays.equals(sizeOfPriority, issues.sizeOfPriority)) { return false; } if (!infoMessages.equals(issues.infoMessages)) { return false; } return id.equals(issues.id); } @Override public int hashCode() { int result = elements.hashCode(); result = 31 * result + Arrays.hashCode(sizeOfPriority); result = 31 * result + infoMessages.hashCode(); result = 31 * result + sizeOfDuplicates; result = 31 * result + id.hashCode(); return result; } /** * Builds a combined filter based on several include and exclude filters. * * @author Raphael Furch */ public static class IssueFilterBuilder { private final Collection<Predicate<Issue>> includeFilters = new ArrayList<>(); private final Collection<Predicate<Issue>> excludeFilters = new ArrayList<>(); /** * Add a new filter for each pattern string. Add filter to include or exclude list. * * @param pattern * filter pattern. * @param propertyToFilter * Function to get a string from Issue for pattern */ private void addNewFilter(final Collection<String> pattern, final Function<Issue, String> propertyToFilter, final boolean include) { Collection<Predicate<Issue>> filters = new ArrayList<>(); for (String patter : pattern) { filters.add(issueToFilter -> Pattern.compile(patter) .matcher(propertyToFilter.apply(issueToFilter)).matches() == include); } if (include) { includeFilters.addAll(filters); } else { excludeFilters.addAll(filters); } } /** * Create a IssueFilter. Combine by default all includes with or and all excludes with and. * * @return a IssueFilter which has all added filter as filter criteria. */ public Predicate<Issue> build() { return includeFilters.stream().reduce(Predicate::or).orElse(issue -> true) .and(excludeFilters.stream().reduce(Predicate::and).orElse(issue -> true)); } //<editor-fold desc="File name"> /** * Add a new filter. * * @param pattern * pattern * * @return this. */ public IssueFilterBuilder setIncludeFilenameFilter(final Collection<String> pattern) { addNewFilter(pattern, Issue::getFileName, true); return this; } /** * Add a new filter. * * @param pattern * pattern * * @return this. */ public IssueFilterBuilder setIncludeFilenameFilter(final String... pattern) { return setIncludeFilenameFilter(Arrays.asList(pattern)); } /** * Add a new filter. * * @param pattern * pattern * * @return this. */ public IssueFilterBuilder setExcludeFilenameFilter(final Collection<String> pattern) { addNewFilter(pattern, Issue::getFileName, false); return this; } /** * Add a new filter. * * @param pattern * pattern * * @return this. */ public IssueFilterBuilder setExcludeFilenameFilter(final String... pattern) { return setExcludeFilenameFilter(Arrays.asList(pattern)); } //</editor-fold> //<editor-fold desc="Package name"> /** * Add a new filter. * * @param pattern * pattern * * @return this. */ public IssueFilterBuilder setIncludePackageNameFilter(final Collection<String> pattern) { addNewFilter(pattern, Issue::getPackageName, true); return this; } /** * Add a new filter. * * @param pattern * pattern * * @return this. */ public IssueFilterBuilder setIncludePackageNameFilter(final String... pattern) { return setIncludePackageNameFilter(Arrays.asList(pattern)); } /** * Add a new filter. * * @param pattern * pattern * * @return this. */ public IssueFilterBuilder setExcludePackageNameFilter(final Collection<String> pattern) { addNewFilter(pattern, Issue::getPackageName, false); return this; } /** * Add a new filter. * * @param pattern * pattern * * @return this. */ public IssueFilterBuilder setExcludePackageNameFilter(final String... pattern) { return setExcludePackageNameFilter(Arrays.asList(pattern)); } //</editor-fold> //<editor-fold desc="Module name"> /** * Add a new filter. * * @param pattern * pattern * * @return this. */ public IssueFilterBuilder setIncludeModuleNameFilter(final Collection<String> pattern) { addNewFilter(pattern, Issue::getModuleName, true); return this; } /** * Add a new filter. * * @param pattern * pattern * * @return this. */ public IssueFilterBuilder setIncludeModuleNameFilter(final String... pattern) { return setIncludeModuleNameFilter(Arrays.asList(pattern)); } /** * Add a new filter. * * @param pattern * pattern * * @return this. */ public IssueFilterBuilder setExcludeModuleNameFilter(final Collection<String> pattern) { addNewFilter(pattern, Issue::getModuleName, false); return this; } /** * Add a new filter. * * @param pattern * pattern * * @return this. */ public IssueFilterBuilder setExcludeModuleNameFilter(final String... pattern) { return setExcludeModuleNameFilter(Arrays.asList(pattern)); } //</editor-fold> //<editor-fold desc="Category"> /** * Add a new filter. * * @param pattern * pattern * * @return this. */ public IssueFilterBuilder setIncludeCategoryFilter(final Collection<String> pattern) { addNewFilter(pattern, Issue::getCategory, true); return this; } /** * Add a new filter. * * @param pattern * pattern * * @return this. */ public IssueFilterBuilder setIncludeCategoryFilter(final String... pattern) { return setIncludeCategoryFilter(Arrays.asList(pattern)); } /** * Add a new filter. * * @param pattern * pattern * * @return this. */ public IssueFilterBuilder setExcludeCategoryFilter(final Collection<String> pattern) { addNewFilter(pattern, Issue::getCategory, false); return this; } /** * Add a new filter. * * @param pattern * pattern * * @return this. */ public IssueFilterBuilder setExcludeCategoryFilter(final String... pattern) { return setExcludeCategoryFilter(Arrays.asList(pattern)); } //</editor-fold> //<editor-fold desc="Type"> /** * Add a new filter. * * @param pattern * pattern * * @return this. */ public IssueFilterBuilder setIncludeTypeFilter(final Collection<String> pattern) { addNewFilter(pattern, Issue::getType, true); return this; } /** * Add a new filter. * * @param pattern * pattern * * @return this. */ public IssueFilterBuilder setIncludeTypeFilter(final String... pattern) { return setIncludeTypeFilter(Arrays.asList(pattern)); } /** * Add a new filter. * * @param pattern * pattern * * @return this. */ public IssueFilterBuilder setExcludeTypeFilter(final Collection<String> pattern) { addNewFilter(pattern, Issue::getType, false); return this; } /** * Add a new filter. * * @param pattern * pattern * * @return this. */ public IssueFilterBuilder setExcludeTypeFilter(final String... pattern) { return setExcludeTypeFilter(Arrays.asList(pattern)); } //</editor-fold> } }
Fixed priority bars.
src/main/java/edu/hm/hafner/analysis/Issues.java
Fixed priority bars.
Java
epl-1.0
92d8410f812218fc07d999d85cadeb629851bf32
0
rgom/Pydev,fabioz/Pydev,fabioz/Pydev,rajul/Pydev,rajul/Pydev,rajul/Pydev,fabioz/Pydev,rajul/Pydev,rgom/Pydev,RandallDW/Aruba_plugin,rajul/Pydev,akurtakov/Pydev,akurtakov/Pydev,fabioz/Pydev,RandallDW/Aruba_plugin,fabioz/Pydev,rajul/Pydev,aptana/Pydev,rgom/Pydev,rgom/Pydev,aptana/Pydev,akurtakov/Pydev,fabioz/Pydev,RandallDW/Aruba_plugin,akurtakov/Pydev,RandallDW/Aruba_plugin,RandallDW/Aruba_plugin,rgom/Pydev,aptana/Pydev,RandallDW/Aruba_plugin,rgom/Pydev,akurtakov/Pydev,akurtakov/Pydev
/* * Created on Nov 12, 2004 * * @author Fabio Zadrozny */ package org.python.pydev.core; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.Reader; import java.io.StringReader; import java.io.UnsupportedEncodingException; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.nio.charset.Charset; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.codec.binary.Base64; import org.eclipse.core.filebuffers.FileBuffers; import org.eclipse.core.filebuffers.ITextFileBuffer; import org.eclipse.core.filebuffers.ITextFileBufferManager; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.util.Assert; import org.python.pydev.core.log.Log; /** * @author Fabio Zadrozny */ public class REF { public static boolean hasAttr(Object o, String attr){ try { o.getClass().getDeclaredField(attr); } catch (SecurityException e) { return false; } catch (NoSuchFieldException e) { return false; } return true; } public static Field getAttr(Object o, String attr){ try { return o.getClass().getDeclaredField(attr); } catch (SecurityException e) { return null; } catch (NoSuchFieldException e) { return null; } } public static Object getAttrObj(Object o, String attr){ if (REF.hasAttr(o, attr)) { Field field = REF.getAttr(o, attr); try { Object obj = field.get(o); return obj; }catch (Exception e) { return null; } } return null; } /** * @param file the file we want to read * @return the contents of the fil as a string */ public static String getFileContents(File file) { try { FileInputStream stream = new FileInputStream(file); return getFileContents(stream, null, null); } catch (Exception e) { throw new RuntimeException(e); } } /** * @param stream * @return * @throws IOException */ private static String getFileContents(InputStream contentStream, String encoding, IProgressMonitor monitor) throws IOException { Reader in= null; final int DEFAULT_FILE_SIZE= 15 * 1024; if (encoding == null){ in= new BufferedReader(new InputStreamReader(contentStream), DEFAULT_FILE_SIZE); }else{ try { in = new BufferedReader(new InputStreamReader(contentStream, encoding), DEFAULT_FILE_SIZE); } catch (UnsupportedEncodingException e) { Log.log(e); //keep going without the encoding in= new BufferedReader(new InputStreamReader(contentStream), DEFAULT_FILE_SIZE); } } StringBuffer buffer= new StringBuffer(DEFAULT_FILE_SIZE); char[] readBuffer= new char[2048]; int n= in.read(readBuffer); while (n > 0) { if (monitor != null && monitor.isCanceled()) return null; buffer.append(readBuffer, 0, n); n= in.read(readBuffer); } return buffer.toString(); } /** * @param o the object we want as a string * @return the string representing the object as base64 */ public static String getObjAsStr(Object o) { ByteArrayOutputStream out = new ByteArrayOutputStream(); try { ObjectOutputStream stream = new ObjectOutputStream(out); stream.writeObject(o); stream.close(); } catch (Exception e) { Log.log(e); throw new RuntimeException(e); } return new String(encodeBase64(out)); } public static byte[] encodeBase64(ByteArrayOutputStream out) { byte[] byteArray = out.toByteArray(); return encodeBase64(byteArray); } public static byte[] encodeBase64(byte[] byteArray) { return Base64.encodeBase64(byteArray); } /** * * @param persisted the base64 string that should be converted to an object. * @param readFromFileMethod should be the calback from the plugin that is calling this function * * * The callback should be something as: new ICallback<Object, ObjectInputStream>(){ public Object call(ObjectInputStream arg) { try { return arg.readObject(); } catch (IOException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } }}; * * @return * @throws IOException * @throws ClassNotFoundException */ public static Object getStrAsObj(String persisted, ICallback<Object, ObjectInputStream> readFromFileMethod) throws IOException, ClassNotFoundException { InputStream input = new ByteArrayInputStream(decodeBase64(persisted)); Object o = readFromInputStreamAndCloseIt(readFromFileMethod, input); return o; } /** * @param readFromFileMethod * @param input * @return * @throws IOException */ public static Object readFromInputStreamAndCloseIt(ICallback<Object, ObjectInputStream> readFromFileMethod, InputStream input) { ObjectInputStream in = null; Object o = null; try { try { in = new ObjectInputStream(input); o = readFromFileMethod.call(in); } finally { if(in!=null){ in.close(); } input.close(); } } catch (Exception e) { throw new RuntimeException(e); } return o; } public static byte[] decodeBase64(String persisted) { return Base64.decodeBase64(persisted.getBytes()); } public static void writeStrToFile(String str, String file) { writeStrToFile(str, new File(file)); } public static void writeStrToFile(String str, File file) { try { FileOutputStream stream = new FileOutputStream(file); try { stream.write(str.getBytes()); } finally{ stream.close(); } } catch (FileNotFoundException e) { Log.log(e); } catch (IOException e) { Log.log(e); } } /** * @param file * @param astManager */ public static void writeToFile(Object o, File file) { try { OutputStream out = new FileOutputStream(file); writeToStreamAndCloseIt(o, out); } catch (Exception e) { Log.log(e); } } /** * @param o * @param out * @throws IOException */ public static void writeToStreamAndCloseIt(Object o, OutputStream out) throws IOException { try { ObjectOutputStream stream = new ObjectOutputStream(out); stream.writeObject(o); stream.close(); } catch (Exception e) { Log.log(e); throw new RuntimeException(e); } finally{ out.close(); } } public static Object readFromFile(File file){ try { InputStream in = new FileInputStream(file); try { ObjectInputStream stream = new ObjectInputStream(in); try { Object o = stream.readObject(); return o; } finally { stream.close(); } } finally { in.close(); } } catch (Exception e) { Log.log(e); return null; } } public static String getFileAbsolutePath(String f) { return getFileAbsolutePath(new File(f)); } /** * @param f * @return */ public static String getFileAbsolutePath(File f) { try { return f.getCanonicalPath(); } catch (IOException e) { return f.getAbsolutePath(); } } /** * Calls a method for an object * * @param obj the object with the method we want to call * @param name the method name * @param args the arguments received for the call * @return the return of the method */ public static Object invoke(Object obj, String name, Object... args) { //the args are not checked for the class because if a subclass is passed, the method is not correctly gotten //another method might do it... Method m = findMethod(obj, name, args); return invoke(obj, m, args); } public static Object invoke(Object obj, Method m, Object... args) { try { return m.invoke(obj, args); } catch (Exception e) { throw new RuntimeException(e); } } public static Method findMethod(Object obj, String name, Object... args) { return findMethod(obj.getClass(), name, args); } public static Method findMethod(Class class_, String name, Object... args) { try { Method[] methods = class_.getMethods(); for (Method method : methods) { Class[] parameterTypes = method.getParameterTypes(); if(method.getName().equals(name) && parameterTypes.length == args.length){ //check the parameters int i = 0; for (Class param : parameterTypes) { if(!param.isInstance(args[i])){ continue; } i++; } //invoke it return method; } } } catch (Exception e) { throw new RuntimeException(e); } throw new RuntimeException("The method with name: "+name+" was not found (or maybe it was found but the parameters didn't match)."); } public static char [] INVALID_FILESYSTEM_CHARS = { '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '[', ']', '{', '}', '=', '+', '.', ' ', '`', '~', '\'', '"', ',', ';'}; public static String getValidProjectName(IProject project) { String name = project.getName(); for (char c : INVALID_FILESYSTEM_CHARS) { name = name.replace(c, '_'); } return name; } /** * Makes an equal comparisson taking into account that one of the parameters may be null. */ public static boolean nullEq(Object o1, Object o2){ if (o1 == null && o2 == null){ return true; } if(o1 == null || o2 == null){ return false; } return o1.equals(o2); } /** * @return the document given its 'filesystem' file */ public static IDocument getDocFromFile(java.io.File f) { IPath path = Path.fromOSString(getFileAbsolutePath(f)); IDocument doc = getDocFromPath(path); if (doc == null) { return getPythonDocFromFile(f); } return doc; } /** * @return the document given its 'filesystem' file (checks for the declared python encoding in the file) */ private static IDocument getPythonDocFromFile(java.io.File f) { IDocument docFromPath = getDocFromPath(Path.fromOSString(getFileAbsolutePath(f))); if(docFromPath != null){ return docFromPath; } try { Assert.isTrue(f.exists(), "The file: "+f+" does not exist."); Assert.isTrue(f.isFile(), "The file: "+f+" is not recognized as a file."); FileInputStream stream = new FileInputStream(f); String fileContents = ""; try { String encoding = getPythonFileEncoding(f); fileContents = getFileContents(stream, encoding, null); } finally { try { stream.close(); } catch (Exception e) {Log.log(e);} } return new Document(fileContents); } catch (Exception e) { throw new RuntimeException(e); } } /** * @return null if it was unable to get the document from the path (this may happen if it was not refreshed). * Or the document that represents the file */ public static IDocument getDocFromPath(IPath path) { ITextFileBufferManager textFileBufferManager = FileBuffers.getTextFileBufferManager(); if(textFileBufferManager != null){//we don't have it in tests ITextFileBuffer textFileBuffer = textFileBufferManager.getTextFileBuffer(path); if(textFileBuffer != null){ //we don't have it when it is not properly refreshed return textFileBuffer.getDocument(); } } return null; } /** * Returns a document, created with the contents of a resource (first tries to get from the 'FileBuffers', * and if that fails, it creates one reading the file. */ public static IDocument getDocFromResource(IResource resource) { IProject project = resource.getProject(); if (project != null && resource instanceof IFile && resource.exists()) { IFile file = (IFile) resource; try { if(file.exists() && !file.isSynchronized(IResource.DEPTH_ZERO)){ file.refreshLocal(IResource.DEPTH_ZERO, new NullProgressMonitor()); } IPath path = file.getFullPath(); IDocument doc = getDocFromPath(path); if(doc == null){ //can this actually happen?... yeap, it can InputStream contents = file.getContents(); try { int i = contents.available(); byte b[] = new byte[i]; contents.read(b); doc = new Document(new String(b)); } finally{ contents.close(); } } return doc; } catch (Exception e) { Log.log(e); } } return null; } /** * The encoding declared in the document is returned (according to the PEP: http://www.python.org/doc/peps/pep-0263/) */ public static String getPythonFileEncoding(IDocument doc, String fileLocation) { Reader inputStreamReader = new StringReader(doc.get()); return getPythonFileEncoding(inputStreamReader, fileLocation); } /** * The encoding declared in the file is returned (according to the PEP: http://www.python.org/doc/peps/pep-0263/) */ public static String getPythonFileEncoding(File f) { try { final FileInputStream fileInputStream = new FileInputStream(f); try { Reader inputStreamReader = new InputStreamReader(fileInputStream); String pythonFileEncoding = getPythonFileEncoding(inputStreamReader, f.getAbsolutePath()); return pythonFileEncoding; } finally { //NOTE: the reader will be closed at 'getPythonFileEncoding'. try { fileInputStream.close(); } catch (Exception e) {Log.log(e); } } } catch (FileNotFoundException e) { return null; } } /** * The encoding declared in the reader is returned (according to the PEP: http://www.python.org/doc/peps/pep-0263/) * -- may return null * * Will close the reader. * @param fileLocation the file we want to get the encoding from (just passed for giving a better message if it fails -- may be null). */ public static String getPythonFileEncoding(Reader inputStreamReader, String fileLocation) { String ret = null; BufferedReader reader = new BufferedReader(inputStreamReader); try{ //pep defines that coding must be at 1st or second line: http://www.python.org/doc/peps/pep-0263/ String l1 = reader.readLine(); String l2 = reader.readLine(); String lEnc = null; //encoding must be specified in first or second line... if (l1 != null && l1.indexOf("coding") != -1){ lEnc = l1; } else if (l2 != null && l2.indexOf("coding") != -1){ lEnc = l2; } else{ ret = null; } if(lEnc != null){ lEnc = lEnc.trim(); if(lEnc.length() == 0){ ret = null; }else if(lEnc.charAt(0) == '#'){ //it must be a comment line //ok, the encoding line is in lEnc Pattern p = Pattern.compile("coding[:=]+[\\s]*[\\w[\\-]]+[\\s]*"); Matcher matcher = p.matcher(lEnc); if( matcher.find() ){ lEnc = lEnc.substring(matcher.start()+6); char c; while(lEnc.length() > 0 && ((c = lEnc.charAt(0)) == ' ' || c == ':' || c == '=')) { lEnc = lEnc.substring(1); } StringBuffer buffer = new StringBuffer(); while(lEnc.length() > 0 && ((c = lEnc.charAt(0)) != ' ' || c == '-' || c == '*')) { buffer.append(c); lEnc = lEnc.substring(1); } ret = buffer.toString().trim(); } } } } catch (IOException e) { e.printStackTrace(); }finally{ try {reader.close();} catch (IOException e1) {} } ret = getValidEncoding(ret, fileLocation); return ret; } /** * @param fileLocation may be null */ public static String getValidEncoding(String ret, String fileLocation) { if(ret == null){ return ret; } final String lower = ret.trim().toLowerCase(); if(lower.startsWith("latin")){ if(lower.indexOf("1") != -1){ return "latin1"; //latin1 } } if(lower.startsWith("utf")){ if(lower.endsWith("8")){ return "UTF-8"; //exact match } } if(!Charset.isSupported(ret)){ if(LOG_ENCODING_ERROR){ String msg = "The encoding found: >>"+ret+"<< on "+fileLocation+" is not a valid encoding."; Log.log(IStatus.ERROR, msg, new UnsupportedEncodingException(msg)); } return null; //ok, we've been unable to make it supported (better return null than an unsupported encoding). } return ret; } /** * Useful to silent it on tests */ public static boolean LOG_ENCODING_ERROR = true; }
org.python.pydev.core/src/org/python/pydev/core/REF.java
/* * Created on Nov 12, 2004 * * @author Fabio Zadrozny */ package org.python.pydev.core; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.Reader; import java.io.StringReader; import java.io.UnsupportedEncodingException; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.nio.charset.Charset; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.codec.binary.Base64; import org.eclipse.core.filebuffers.FileBuffers; import org.eclipse.core.filebuffers.ITextFileBuffer; import org.eclipse.core.filebuffers.ITextFileBufferManager; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.util.Assert; import org.python.pydev.core.log.Log; /** * @author Fabio Zadrozny */ public class REF { public static boolean hasAttr(Object o, String attr){ try { o.getClass().getDeclaredField(attr); } catch (SecurityException e) { return false; } catch (NoSuchFieldException e) { return false; } return true; } public static Field getAttr(Object o, String attr){ try { return o.getClass().getDeclaredField(attr); } catch (SecurityException e) { return null; } catch (NoSuchFieldException e) { return null; } } public static Object getAttrObj(Object o, String attr){ if (REF.hasAttr(o, attr)) { Field field = REF.getAttr(o, attr); try { Object obj = field.get(o); return obj; }catch (Exception e) { return null; } } return null; } /** * @param file the file we want to read * @return the contents of the fil as a string */ public static String getFileContents(File file) { try { FileInputStream stream = new FileInputStream(file); return getFileContents(stream, null, null); } catch (Exception e) { throw new RuntimeException(e); } } /** * @param stream * @return * @throws IOException */ private static String getFileContents(InputStream contentStream, String encoding, IProgressMonitor monitor) throws IOException { Reader in= null; final int DEFAULT_FILE_SIZE= 15 * 1024; if (encoding == null){ in= new BufferedReader(new InputStreamReader(contentStream), DEFAULT_FILE_SIZE); }else{ try { in = new BufferedReader(new InputStreamReader(contentStream, encoding), DEFAULT_FILE_SIZE); } catch (UnsupportedEncodingException e) { Log.log(e); //keep going without the encoding in= new BufferedReader(new InputStreamReader(contentStream), DEFAULT_FILE_SIZE); } } StringBuffer buffer= new StringBuffer(DEFAULT_FILE_SIZE); char[] readBuffer= new char[2048]; int n= in.read(readBuffer); while (n > 0) { if (monitor != null && monitor.isCanceled()) return null; buffer.append(readBuffer, 0, n); n= in.read(readBuffer); } return buffer.toString(); } /** * @param o the object we want as a string * @return the string representing the object as base64 */ public static String getObjAsStr(Object o) { ByteArrayOutputStream out = new ByteArrayOutputStream(); try { ObjectOutputStream stream = new ObjectOutputStream(out); stream.writeObject(o); stream.close(); } catch (Exception e) { Log.log(e); throw new RuntimeException(e); } return new String(encodeBase64(out)); } public static byte[] encodeBase64(ByteArrayOutputStream out) { byte[] byteArray = out.toByteArray(); return encodeBase64(byteArray); } public static byte[] encodeBase64(byte[] byteArray) { return Base64.encodeBase64(byteArray); } /** * * @param persisted the base64 string that should be converted to an object. * @param readFromFileMethod should be the calback from the plugin that is calling this function * * * The callback should be something as: new ICallback<Object, ObjectInputStream>(){ public Object call(ObjectInputStream arg) { try { return arg.readObject(); } catch (IOException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } }}; * * @return * @throws IOException * @throws ClassNotFoundException */ public static Object getStrAsObj(String persisted, ICallback<Object, ObjectInputStream> readFromFileMethod) throws IOException, ClassNotFoundException { InputStream input = new ByteArrayInputStream(decodeBase64(persisted)); Object o = readFromInputStreamAndCloseIt(readFromFileMethod, input); return o; } /** * @param readFromFileMethod * @param input * @return * @throws IOException */ public static Object readFromInputStreamAndCloseIt(ICallback<Object, ObjectInputStream> readFromFileMethod, InputStream input) { ObjectInputStream in = null; Object o = null; try { try { in = new ObjectInputStream(input); o = readFromFileMethod.call(in); } finally { if(in!=null){ in.close(); } input.close(); } } catch (Exception e) { throw new RuntimeException(e); } return o; } public static byte[] decodeBase64(String persisted) { return Base64.decodeBase64(persisted.getBytes()); } public static void writeStrToFile(String str, String file) { writeStrToFile(str, new File(file)); } public static void writeStrToFile(String str, File file) { try { FileOutputStream stream = new FileOutputStream(file); try { stream.write(str.getBytes()); } finally{ stream.close(); } } catch (FileNotFoundException e) { Log.log(e); } catch (IOException e) { Log.log(e); } } /** * @param file * @param astManager */ public static void writeToFile(Object o, File file) { try { OutputStream out = new FileOutputStream(file); writeToStreamAndCloseIt(o, out); } catch (Exception e) { Log.log(e); } } /** * @param o * @param out * @throws IOException */ public static void writeToStreamAndCloseIt(Object o, OutputStream out) throws IOException { try { ObjectOutputStream stream = new ObjectOutputStream(out); stream.writeObject(o); stream.close(); } catch (Exception e) { Log.log(e); throw new RuntimeException(e); } finally{ out.close(); } } public static Object readFromFile(File file){ try { InputStream in = new FileInputStream(file); try { ObjectInputStream stream = new ObjectInputStream(in); try { Object o = stream.readObject(); return o; } finally { stream.close(); } } finally { in.close(); } } catch (Exception e) { Log.log(e); return null; } } public static String getFileAbsolutePath(String f) { return getFileAbsolutePath(new File(f)); } /** * @param f * @return */ public static String getFileAbsolutePath(File f) { try { return f.getCanonicalPath(); } catch (IOException e) { return f.getAbsolutePath(); } } /** * Calls a method for an object * * @param obj the object with the method we want to call * @param name the method name * @param args the arguments received for the call * @return the return of the method */ public static Object invoke(Object obj, String name, Object... args) { //the args are not checked for the class because if a subclass is passed, the method is not correctly gotten //another method might do it... Method m = findMethod(obj, name, args); return invoke(obj, m, args); } public static Object invoke(Object obj, Method m, Object... args) { try { return m.invoke(obj, args); } catch (Exception e) { throw new RuntimeException(e); } } public static Method findMethod(Object obj, String name, Object... args) { return findMethod(obj.getClass(), name, args); } public static Method findMethod(Class class_, String name, Object... args) { try { Method[] methods = class_.getMethods(); for (Method method : methods) { Class[] parameterTypes = method.getParameterTypes(); if(method.getName().equals(name) && parameterTypes.length == args.length){ //check the parameters int i = 0; for (Class param : parameterTypes) { if(!param.isInstance(args[i])){ continue; } i++; } //invoke it return method; } } } catch (Exception e) { throw new RuntimeException(e); } throw new RuntimeException("The method with name: "+name+" was not found (or maybe it was found but the parameters didn't match)."); } public static char [] INVALID_FILESYSTEM_CHARS = { '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '[', ']', '{', '}', '=', '+', '.', ' ', '`', '~', '\'', '"', ',', ';'}; public static String getValidProjectName(IProject project) { String name = project.getName(); for (char c : INVALID_FILESYSTEM_CHARS) { name = name.replace(c, '_'); } return name; } /** * Makes an equal comparisson taking into account that one of the parameters may be null. */ public static boolean nullEq(Object o1, Object o2){ if (o1 == null && o2 == null){ return true; } if(o1 == null || o2 == null){ return false; } return o1.equals(o2); } /** * @return the document given its 'filesystem' file */ public static IDocument getDocFromFile(java.io.File f) { IPath path = Path.fromOSString(getFileAbsolutePath(f)); IDocument doc = getDocFromPath(path); if (doc == null) { return getPythonDocFromFile(f); } return doc; } /** * @return the document given its 'filesystem' file (checks for the declared python encoding in the file) */ private static IDocument getPythonDocFromFile(java.io.File f) { try { Assert.isTrue(f.exists(), "The file: "+f+" does not exist."); Assert.isTrue(f.isFile(), "The file: "+f+" is not recognized as a file."); FileInputStream stream = new FileInputStream(f); String fileContents = ""; try { String encoding = getPythonFileEncoding(f); fileContents = getFileContents(stream, encoding, null); } finally { try { stream.close(); } catch (Exception e) {Log.log(e);} } return new Document(fileContents); } catch (Exception e) { throw new RuntimeException(e); } } /** * @return null if it was unable to get the document from the path (this may happen if it was not refreshed). * Or the document that represents the file */ public static IDocument getDocFromPath(IPath path) { ITextFileBufferManager textFileBufferManager = FileBuffers.getTextFileBufferManager(); if(textFileBufferManager != null){//we don't have it in tests ITextFileBuffer textFileBuffer = textFileBufferManager.getTextFileBuffer(path); if(textFileBuffer != null){ //we don't have it when it is not properly refreshed return textFileBuffer.getDocument(); } } return null; } /** * Returns a document, created with the contents of a resource (first tries to get from the 'FileBuffers', * and if that fails, it creates one reading the file. */ public static IDocument getDocFromResource(IResource resource) { IProject project = resource.getProject(); if (project != null && resource instanceof IFile && resource.exists()) { IFile file = (IFile) resource; try { if(file.exists() && !file.isSynchronized(IResource.DEPTH_ZERO)){ file.refreshLocal(IResource.DEPTH_ZERO, new NullProgressMonitor()); } IPath path = file.getFullPath(); IDocument doc = getDocFromPath(path); if(doc == null){ //can this actually happen?... yeap, it can InputStream contents = file.getContents(); try { int i = contents.available(); byte b[] = new byte[i]; contents.read(b); doc = new Document(new String(b)); } finally{ contents.close(); } } return doc; } catch (Exception e) { Log.log(e); } } return null; } /** * The encoding declared in the document is returned (according to the PEP: http://www.python.org/doc/peps/pep-0263/) */ public static String getPythonFileEncoding(IDocument doc, String fileLocation) { Reader inputStreamReader = new StringReader(doc.get()); return getPythonFileEncoding(inputStreamReader, fileLocation); } /** * The encoding declared in the file is returned (according to the PEP: http://www.python.org/doc/peps/pep-0263/) */ public static String getPythonFileEncoding(File f) { try { final FileInputStream fileInputStream = new FileInputStream(f); try { Reader inputStreamReader = new InputStreamReader(fileInputStream); String pythonFileEncoding = getPythonFileEncoding(inputStreamReader, f.getAbsolutePath()); return pythonFileEncoding; } finally { //NOTE: the reader will be closed at 'getPythonFileEncoding'. try { fileInputStream.close(); } catch (Exception e) {Log.log(e); } } } catch (FileNotFoundException e) { return null; } } /** * The encoding declared in the reader is returned (according to the PEP: http://www.python.org/doc/peps/pep-0263/) * -- may return null * * Will close the reader. * @param fileLocation the file we want to get the encoding from (just passed for giving a better message if it fails -- may be null). */ public static String getPythonFileEncoding(Reader inputStreamReader, String fileLocation) { String ret = null; BufferedReader reader = new BufferedReader(inputStreamReader); try{ //pep defines that coding must be at 1st or second line: http://www.python.org/doc/peps/pep-0263/ String l1 = reader.readLine(); String l2 = reader.readLine(); String lEnc = null; //encoding must be specified in first or second line... if (l1 != null && l1.indexOf("coding") != -1){ lEnc = l1; } else if (l2 != null && l2.indexOf("coding") != -1){ lEnc = l2; } else{ ret = null; } if(lEnc != null){ lEnc = lEnc.trim(); if(lEnc.length() == 0){ ret = null; }else if(lEnc.charAt(0) == '#'){ //it must be a comment line //ok, the encoding line is in lEnc Pattern p = Pattern.compile("coding[:=]+[\\s]*[\\w[\\-]]+[\\s]*"); Matcher matcher = p.matcher(lEnc); if( matcher.find() ){ lEnc = lEnc.substring(matcher.start()+6); char c; while(lEnc.length() > 0 && ((c = lEnc.charAt(0)) == ' ' || c == ':' || c == '=')) { lEnc = lEnc.substring(1); } StringBuffer buffer = new StringBuffer(); while(lEnc.length() > 0 && ((c = lEnc.charAt(0)) != ' ' || c == '-' || c == '*')) { buffer.append(c); lEnc = lEnc.substring(1); } ret = buffer.toString().trim(); } } } } catch (IOException e) { e.printStackTrace(); }finally{ try {reader.close();} catch (IOException e1) {} } ret = getValidEncoding(ret, fileLocation); return ret; } /** * @param fileLocation may be null */ public static String getValidEncoding(String ret, String fileLocation) { if(ret == null){ return ret; } final String lower = ret.trim().toLowerCase(); if(lower.startsWith("latin")){ if(lower.indexOf("1") != -1){ return "latin1"; //latin1 } } if(lower.startsWith("utf")){ if(lower.endsWith("8")){ return "UTF-8"; //exact match } } if(!Charset.isSupported(ret)){ if(LOG_ENCODING_ERROR){ String msg = "The encoding found: >>"+ret+"<< on "+fileLocation+" is not a valid encoding."; Log.log(IStatus.ERROR, msg, new UnsupportedEncodingException(msg)); } return null; //ok, we've been unable to make it supported (better return null than an unsupported encoding). } return ret; } /** * Useful to silent it on tests */ public static boolean LOG_ENCODING_ERROR = true; }
*** empty log message *** git-svn-id: cdbd3c3453b226d8644b39c93ea790e37ea3ca1b@1241 7f4d9e04-a92a-ab41-bea9-970b690ef4a7
org.python.pydev.core/src/org/python/pydev/core/REF.java
*** empty log message ***
Java
epl-1.0
214fa8cd44ca576bc8ba5ae639e824259582a536
0
elexis/elexis-3-core,elexis/elexis-3-core,elexis/elexis-3-core,elexis/elexis-3-core
package ch.elexis.core.ui.preferences; import java.util.List; import java.util.UUID; import org.eclipse.core.databinding.DataBindingContext; import org.eclipse.core.databinding.beans.PojoProperties; import org.eclipse.core.databinding.observable.value.IObservableValue; import org.eclipse.core.databinding.observable.value.WritableValue; import org.eclipse.jface.databinding.swt.WidgetProperties; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.layout.TableColumnLayout; import org.eclipse.jface.preference.PreferencePage; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.CellLabelProvider; import org.eclipse.jface.viewers.ColumnPixelData; import org.eclipse.jface.viewers.ColumnWeightData; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.TableViewerColumn; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerCell; import org.eclipse.jface.viewers.ViewerComparator; import org.eclipse.jface.window.Window; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.layout.RowLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Link; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.MenuItem; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import org.eclipse.ui.dialogs.ListDialog; import ch.elexis.core.constants.Preferences; import ch.elexis.core.constants.StringConstants; import ch.elexis.core.services.holder.ConfigServiceHolder; import ch.elexis.core.services.holder.StockCommissioningServiceHolder; import ch.elexis.core.ui.UiDesk; import ch.elexis.core.ui.dialogs.KontaktSelektor; import ch.elexis.core.ui.icons.Images; import ch.elexis.core.ui.preferences.ConfigServicePreferenceStore.Scope; import ch.elexis.data.Kontakt; import ch.elexis.data.Mandant; import ch.elexis.data.Query; import ch.elexis.data.Stock; public class StockManagementPreferencePage extends PreferencePage implements IWorkbenchPreferencePage { private DataBindingContext m_bindingContext; private Table tableStocks; private Text txtCode; private Text txtDescription; private Text txtLocation; private Text txtPrio; private Label lblOwnerText; private Label lblResponsibleText; private Button btnChkStoreInvalidNumbers; private Button btnIgnoreOrderedArticlesOnNextOrder; private WritableValue<Stock> stockDetail = new WritableValue<Stock>(null, Stock.class); private TableViewer tableViewer; private Text txtMachineConfig; private Label lblMachineuuid; private Label lblDefaultArticleProvider; private Button btnMachineOutlayPartialPackages; private Button btnStoreBelow; private Button btnStoreAtMin; /** * Create the preference page. */ public StockManagementPreferencePage(){ setTitle(Messages.LagerverwaltungPrefs_storageManagement); } /** * Create contents of the preference page. * * @param parent */ @Override public Control createContents(Composite parent){ Composite container = new Composite(parent, SWT.NULL); container.setLayout(new GridLayout(1, false)); Group group = new Group(container, SWT.NONE); group.setLayout(new GridLayout(1, false)); group.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); group.setText(Messages.StockManagementPreferencePage_group_text); Composite composite = new Composite(group, SWT.NONE); GridData gd_composite = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1); gd_composite.heightHint = 150; composite.setLayoutData(gd_composite); TableColumnLayout tcl_composite = new TableColumnLayout(); composite.setLayout(tcl_composite); tableViewer = new TableViewer(composite, SWT.BORDER | SWT.FULL_SELECTION); tableViewer.setContentProvider(ArrayContentProvider.getInstance()); tableViewer.setComparator(new ViewerComparator() { @Override public int compare(Viewer viewer, Object e1, Object e2){ Stock s1 = (Stock) e1; int s1I = (s1.getPriority() != null) ? s1.getPriority() : Integer.MAX_VALUE; Stock s2 = (Stock) e2; int s2I = (s2.getPriority() != null) ? s2.getPriority() : Integer.MAX_VALUE; return Integer.compare(s1I, s2I); } }); tableViewer.addSelectionChangedListener(e -> { StructuredSelection ss = (StructuredSelection) e.getSelection(); if (ss.isEmpty()) { stockDetail.setValue(null); } else { stockDetail.setValue((Stock) ss.getFirstElement()); } }); tableStocks = tableViewer.getTable(); tableStocks.setHeaderVisible(true); tableStocks.setLinesVisible(true); Menu menu = new Menu(tableStocks); tableStocks.setMenu(menu); MenuItem mntmAddStock = new MenuItem(menu, SWT.NONE); mntmAddStock.setText(Messages.StockManagementPreferencePage_mntmNewItem_text); mntmAddStock.setImage(Images.IMG_NEW.getImage()); mntmAddStock.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e){ Stock stock = new Stock("", Integer.MAX_VALUE); tableViewer.add(stock); tableViewer.setSelection(new StructuredSelection(stock)); } }); MenuItem mntmRemoveStock = new MenuItem(menu, SWT.NONE); mntmRemoveStock.setText(Messages.StockManagementPreferencePage_mntmNewItem_text_1); mntmRemoveStock.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e){ Stock stock = (Stock) stockDetail.getValue(); if (stock != null) { boolean ret = MessageDialog.openQuestion(UiDesk.getTopShell(), "Lager löschen", "Das Löschen dieses Lagers löscht alle darauf verzeichneten Lagerbestände. Sind Sie sicher?"); if (ret) { stock.removeFromDatabase(); tableViewer.remove(stock); } } } }); TableViewerColumn tvcPriority = new TableViewerColumn(tableViewer, SWT.NONE); TableColumn tblclmPriority = tvcPriority.getColumn(); tcl_composite.setColumnData(tblclmPriority, new ColumnPixelData(30, true, true)); tblclmPriority.setText(Messages.StockManagementPreferencePage_tblclmnNewColumn_text); tvcPriority.setLabelProvider(new CellLabelProvider() { @Override public void update(ViewerCell cell){ Stock s = (Stock) cell.getElement(); if (s == null) return; cell.setText(Integer.toString(s.getPriority())); } }); TableViewerColumn tvcCode = new TableViewerColumn(tableViewer, SWT.NONE); TableColumn tblclmnCode = tvcCode.getColumn(); tcl_composite.setColumnData(tblclmnCode, new ColumnPixelData(40)); tblclmnCode.setText(Messages.StockManagementPreferencePage_tblclmnNewColumn_text_1); tvcCode.setLabelProvider(new CellLabelProvider() { @Override public void update(ViewerCell cell){ Stock s = (Stock) cell.getElement(); if (s == null) return; cell.setText(s.getCode()); } }); TableViewerColumn tvcDescription = new TableViewerColumn(tableViewer, SWT.NONE); TableColumn tblclmnDescription = tvcDescription.getColumn(); tcl_composite.setColumnData(tblclmnDescription, new ColumnWeightData(50)); tblclmnDescription.setText(Messages.StockManagementPreferencePage_tblclmnNewColumn_text_3); tvcDescription.setLabelProvider(new CellLabelProvider() { @Override public void update(ViewerCell cell){ Stock s = (Stock) cell.getElement(); if (s == null) return; cell.setText(s.getDescription()); } }); TableViewerColumn tvcOwner = new TableViewerColumn(tableViewer, SWT.NONE); TableColumn tblclmnOwner = tvcOwner.getColumn(); tcl_composite.setColumnData(tblclmnOwner, new ColumnWeightData(40)); tblclmnOwner.setText(Messages.StockManagementPreferencePage_tblclmnNewColumn_text_2); tvcOwner.setLabelProvider(new CellLabelProvider() { @Override public void update(ViewerCell cell){ Stock s = (Stock) cell.getElement(); if (s != null) { Mandant owner = s.getOwner(); if (owner != null) { cell.setText(owner.getLabel()); } } } }); Composite compositeDetail = new Composite(group, SWT.NONE); compositeDetail.setLayout(new GridLayout(4, false)); compositeDetail.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true, 1, 1)); Label lblPrio = new Label(compositeDetail, SWT.NONE); lblPrio.setText(Messages.StockManagementPreferencePage_lblPrio_text); txtPrio = new Text(compositeDetail, SWT.BORDER); GridData gd_txtPrio = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1); gd_txtPrio.widthHint = 150; txtPrio.setLayoutData(gd_txtPrio); Label lblCode = new Label(compositeDetail, SWT.NONE); lblCode.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); lblCode.setToolTipText(Messages.StockManagementPreferencePage_lblCode_toolTipText); lblCode.setText(Messages.StockManagementPreferencePage_lblCode_text); txtCode = new Text(compositeDetail, SWT.BORDER); GridData gd_txtCode = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1); gd_txtCode.widthHint = 100; txtCode.setLayoutData(gd_txtCode); txtCode.setTextLimit(3); Label lblDescription = new Label(compositeDetail, SWT.NONE); lblDescription.setText(Messages.StockManagementPreferencePage_lblDescription_text); txtDescription = new Text(compositeDetail, SWT.BORDER); txtDescription.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); Label lblLocation = new Label(compositeDetail, SWT.NONE); lblLocation.setToolTipText(Messages.StockManagementPreferencePage_lblLocation_toolTipText); lblLocation.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); lblLocation.setText(Messages.StockManagementPreferencePage_lblLocation_text); txtLocation = new Text(compositeDetail, SWT.BORDER); txtLocation.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); Link lblOwner = new Link(compositeDetail, SWT.NONE); lblOwner.setToolTipText(Messages.StockManagementPreferencePage_lblOwner_toolTipText); lblOwner.setText(Messages.StockManagementPreferencePage_lblOwner_text); lblOwner.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e){ Stock s = (Stock) stockDetail.getValue(); if (s == null) return; KontaktSelektor ks = new KontaktSelektor(UiDesk.getTopShell(), Mandant.class, "Mandant auswählen", "Bitte selektieren Sie den Eigentümer", new String[] {}); int ret = ks.open(); if (ret == Window.OK) { Mandant p = (Mandant) ks.getSelection(); s.setOwner(p); String label = (p != null) ? p.getLabel() : ""; lblOwnerText.setText(label); } else { s.setOwner(null); lblOwnerText.setText(StringConstants.EMPTY); } tableViewer.update(s, null); } }); lblOwnerText = new Label(compositeDetail, SWT.NONE); lblOwnerText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1)); Link lblResponsible = new Link(compositeDetail, SWT.NONE); lblResponsible .setToolTipText(Messages.StockManagementPreferencePage_lblResponsible_toolTipText); lblResponsible.setText(Messages.StockManagementPreferencePage_lblResonsible_text); lblResponsible.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e){ Stock s = (Stock) stockDetail.getValue(); if (s == null) return; KontaktSelektor ks = new KontaktSelektor(UiDesk.getTopShell(), Kontakt.class, "Lagerverantwortlichen auswählen", "Bitte selektieren Sie den Lagerverantwortlichen", new String[] {}); int ret = ks.open(); if (ret == Window.OK) { Kontakt p = (Kontakt) ks.getSelection(); s.setResponsible(p); String label = (p != null) ? p.getLabel() : ""; lblResponsibleText.setText(label); } else { s.setResponsible(null); lblResponsibleText.setText(""); } } }); lblResponsibleText = new Label(compositeDetail, SWT.NONE); lblResponsibleText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1)); Label lblNewLabel = new Label(compositeDetail, SWT.SEPARATOR | SWT.HORIZONTAL); lblNewLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 4, 1)); lblNewLabel.setText(Messages.StockManagementPreferencePage_lblNewLabel_text); Link lblMachine = new Link(compositeDetail, SWT.NONE); lblMachine.setToolTipText(Messages.StockManagementPreferencePage_lblMachine_toolTipText); lblMachine.setText(Messages.StockManagementPreferencePage_lblMachine_text); lblMachine.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e){ Stock s = (Stock) stockDetail.getValue(); if (s == null) { return; } List<UUID> allDrivers = StockCommissioningServiceHolder.get().listAllAvailableDrivers(); if (allDrivers.size() == 0) { MessageDialog.openInformation(UiDesk.getTopShell(), "No drivers found", "There are no stock commissioning system drivers available."); return; } ListDialog ld = new ListDialog(UiDesk.getTopShell()); ld.setTitle("Driver selection"); ld.setMessage("Please select a commissioning system driver"); ld.setContentProvider(ArrayContentProvider.getInstance()); ld.setAddCancelButton(true); ld.setLabelProvider(new LabelProvider() { @Override public String getText(Object element){ return StockCommissioningServiceHolder.get() .getInfoStringForDriver((UUID) element, true); } }); ld.setInput(allDrivers); ld.setWidthInChars(80); ld.setHeightInChars(5); int retVal = ld.open(); UUID ics = null; if (Dialog.OK == retVal) { Object[] result = ld.getResult(); if (result.length > 0) { ics = (UUID) result[0]; } } else if (Dialog.CANCEL == retVal) { ics = null; } if (ics != null) { s.setDriverUuid(ics.toString()); lblMachineuuid.setText(StockCommissioningServiceHolder.get() .getInfoStringForDriver(ics, false)); } else { s.setDriverUuid(null); lblMachineuuid.setText(StringConstants.EMPTY); } } }); lblMachineuuid = new Label(compositeDetail, SWT.NONE); lblMachineuuid.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1)); Label lblMachineConfig = new Label(compositeDetail, SWT.NONE); lblMachineConfig.setText(Messages.StockManagementPreferencePage_lblMachineConfig_text); txtMachineConfig = new Text(compositeDetail, SWT.BORDER); txtMachineConfig.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1)); btnMachineOutlayPartialPackages = new Button(compositeDetail, SWT.CHECK); btnMachineOutlayPartialPackages .setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 4, 1)); btnMachineOutlayPartialPackages .setText(Messages.StockManagementPreferencePage_btnMachineOutlayPartialPackages_text); boolean outlayPartialPackages = ConfigServiceHolder.getGlobal(Preferences.INVENTORY_MACHINE_OUTLAY_PARTIAL_PACKAGES, Preferences.INVENTORY_MACHINE_OUTLAY_PARTIAL_PACKAGES_DEFAULT); btnMachineOutlayPartialPackages.setSelection(outlayPartialPackages); btnIgnoreOrderedArticlesOnNextOrder = new Button(container, SWT.CHECK); btnIgnoreOrderedArticlesOnNextOrder .setText(Messages.LagerverwaltungPrefs_ignoreOrderedArticleOnNextOrder); btnIgnoreOrderedArticlesOnNextOrder.setSelection(getPreferenceStore() .getBoolean(Preferences.INVENTORY_ORDER_EXCLUDE_ALREADY_ORDERED_ITEMS_ON_NEXT_ORDER)); btnChkStoreInvalidNumbers = new Button(container, SWT.CHECK); btnChkStoreInvalidNumbers.setText(Messages.LagerverwaltungPrefs_checkForInvalid); btnChkStoreInvalidNumbers.setSelection( getPreferenceStore().getBoolean(Preferences.INVENTORY_CHECK_ILLEGAL_VALUES)); Group group1 = new Group(container, SWT.SHADOW_IN); group1.setText(Messages.LagerverwaltungPrefs_orderCriteria); group1.setLayout(new RowLayout(SWT.VERTICAL)); btnStoreBelow = new Button(group1, SWT.RADIO); btnStoreBelow.setText(Messages.LagerverwaltungPrefs_orderWhenBelowMi); btnStoreAtMin = new Button(group1, SWT.RADIO); btnStoreAtMin.setText(Messages.LagerverwaltungPrefs_orderWhenAtMin); int valInventoryOrderTrigger = ConfigServiceHolder.getGlobal(Preferences.INVENTORY_ORDER_TRIGGER, Preferences.INVENTORY_ORDER_TRIGGER_DEFAULT); boolean isInventoryOrderEqualValue = Preferences.INVENTORY_ORDER_TRIGGER_EQUAL == valInventoryOrderTrigger; btnStoreAtMin.setSelection(isInventoryOrderEqualValue); btnStoreBelow.setSelection(!isInventoryOrderEqualValue); Composite compDefaultProvider = new Composite(container, SWT.NONE); compDefaultProvider.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1)); GridLayout gl_compDefaultProvider = new GridLayout(3, false); gl_compDefaultProvider.marginWidth = 0; gl_compDefaultProvider.marginHeight = 0; compDefaultProvider.setLayout(gl_compDefaultProvider); Link linkDefaultArticleProvider = new Link(compDefaultProvider, SWT.NONE); linkDefaultArticleProvider.setToolTipText( Messages.StockManagementPreferencePage_linkDefaultArticleProvider_toolTipText); linkDefaultArticleProvider .setText(Messages.StockManagementPreferencePage_linkDefaultArticleProvider_text); linkDefaultArticleProvider.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e){ KontaktSelektor ks = new KontaktSelektor(UiDesk.getTopShell(), Kontakt.class, "Standard-Lieferant auswählen", "Bitte selektieren Sie den Standard-Lieferanten", new String[] {}); int ret = ks.open(); if (ret == Window.OK) { Kontakt p = (Kontakt) ks.getSelection(); if (p != null) { ConfigServiceHolder.setGlobal(Preferences.INVENTORY_DEFAULT_ARTICLE_PROVIDER, p.getId()); lblDefaultArticleProvider.setText(p.getLabel()); } } else { ConfigServiceHolder.setGlobal(Preferences.INVENTORY_DEFAULT_ARTICLE_PROVIDER, null); lblDefaultArticleProvider.setText(""); } } }); lblDefaultArticleProvider = new Label(compDefaultProvider, SWT.NONE); lblDefaultArticleProvider .setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); String id = ConfigServiceHolder.getGlobal(Preferences.INVENTORY_DEFAULT_ARTICLE_PROVIDER, null); lblDefaultArticleProvider.setText(""); new Label(compDefaultProvider, SWT.NONE); if (id != null) { Kontakt load = Kontakt.load(id); if (load.exists()) { lblDefaultArticleProvider.setText(load.getLabel()); } } tableViewer.setInput(new Query<Stock>(Stock.class).execute()); m_bindingContext = initDataBindings(); stockDetail.addChangeListener(e -> { Stock stock = (Stock) stockDetail.getValue(); if (stock != null) { Mandant owner = stock.getOwner(); if (owner != null) { lblOwnerText.setText(owner.getLabel()); } else { lblOwnerText.setText(""); } Kontakt responsible = stock.getResponsible(); if (responsible != null) { lblResponsibleText.setText(responsible.getLabel()); } else { lblResponsibleText.setText(""); } String machineUuid = stock.getDriverUuid(); if (machineUuid != null && !machineUuid.isEmpty()) { String info = StockCommissioningServiceHolder.get() .getInfoStringForDriver(UUID.fromString(machineUuid), false); lblMachineuuid.setText(info); } else { lblMachineuuid.setText(""); } } else { lblOwnerText.setText(""); lblResponsibleText.setText(""); } }); return container; } /** * Initialize the preference page. */ public void init(IWorkbench workbench){ setPreferenceStore(new ConfigServicePreferenceStore(Scope.GLOBAL)); getPreferenceStore().setDefault(Preferences.INVENTORY_CHECK_ILLEGAL_VALUES, Preferences.INVENTORY_CHECK_ILLEGAL_VALUES_DEFAULT); getPreferenceStore().setDefault( Preferences.INVENTORY_ORDER_EXCLUDE_ALREADY_ORDERED_ITEMS_ON_NEXT_ORDER, Preferences.INVENTORY_ORDER_EXCLUDE_ALREADY_ORDERED_ITEMS_ON_NEXT_ORDER_DEFAULT); } @Override protected void performApply(){ tableViewer.setInput(new Query<Stock>(Stock.class).execute()); setErrorMessage(null); super.performApply(); } @Override public boolean performOk(){ getPreferenceStore().setValue(Preferences.INVENTORY_CHECK_ILLEGAL_VALUES, btnChkStoreInvalidNumbers.getSelection()); getPreferenceStore().setValue( Preferences.INVENTORY_ORDER_EXCLUDE_ALREADY_ORDERED_ITEMS_ON_NEXT_ORDER, btnIgnoreOrderedArticlesOnNextOrder.getSelection()); getPreferenceStore().setValue(Preferences.INVENTORY_MACHINE_OUTLAY_PARTIAL_PACKAGES, btnMachineOutlayPartialPackages.getSelection()); getPreferenceStore().setValue(Preferences.INVENTORY_ORDER_TRIGGER, btnStoreBelow.getSelection() ? Preferences.INVENTORY_ORDER_TRIGGER_BELOW : Preferences.INVENTORY_ORDER_TRIGGER_EQUAL); return super.performOk(); } protected DataBindingContext initDataBindings(){ DataBindingContext bindingContext = new DataBindingContext(); // IObservableValue observeTextTxtCodeObserveWidget = WidgetProperties.text(SWT.Modify).observe(txtCode); IObservableValue stockDetailCodeObserveDetailValue = PojoProperties.value(Stock.class, "code", String.class).observeDetail(stockDetail); bindingContext.bindValue(observeTextTxtCodeObserveWidget, stockDetailCodeObserveDetailValue, null, null); // IObservableValue observeTextTxtDescriptionObserveWidget = WidgetProperties.text(SWT.Modify).observe(txtDescription); IObservableValue stockDetailDescriptionObserveDetailValue = PojoProperties .value(Stock.class, "description", String.class).observeDetail(stockDetail); bindingContext.bindValue(observeTextTxtDescriptionObserveWidget, stockDetailDescriptionObserveDetailValue, null, null); // IObservableValue observeTextTxtLocationObserveWidget = WidgetProperties.text(SWT.Modify).observe(txtLocation); IObservableValue stockDetailLocationObserveDetailValue = PojoProperties.value(Stock.class, "location", String.class).observeDetail(stockDetail); bindingContext.bindValue(observeTextTxtLocationObserveWidget, stockDetailLocationObserveDetailValue, null, null); // IObservableValue observeTextTxtPrioObserveWidget = WidgetProperties.text(SWT.Modify).observe(txtPrio); IObservableValue stockDetailGlobalPreferenceObserveDetailValue = PojoProperties.value(Stock.class, "priority", Integer.class).observeDetail(stockDetail); bindingContext.bindValue(observeTextTxtPrioObserveWidget, stockDetailGlobalPreferenceObserveDetailValue, null, null); // IObservableValue observeTextTxtMachineConfigObserveWidget = WidgetProperties.text(SWT.Modify).observe(txtMachineConfig); IObservableValue stockDetailMachineConfigObserveDetailValue = PojoProperties .value(Stock.class, "driverConfig", String.class).observeDetail(stockDetail); bindingContext.bindValue(observeTextTxtMachineConfigObserveWidget, stockDetailMachineConfigObserveDetailValue, null, null); // return bindingContext; } }
bundles/ch.elexis.core.ui/src/ch/elexis/core/ui/preferences/StockManagementPreferencePage.java
package ch.elexis.core.ui.preferences; import java.util.List; import java.util.UUID; import org.eclipse.core.databinding.DataBindingContext; import org.eclipse.core.databinding.beans.PojoProperties; import org.eclipse.core.databinding.observable.value.IObservableValue; import org.eclipse.core.databinding.observable.value.WritableValue; import org.eclipse.jface.databinding.swt.WidgetProperties; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.layout.TableColumnLayout; import org.eclipse.jface.preference.PreferencePage; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.CellLabelProvider; import org.eclipse.jface.viewers.ColumnPixelData; import org.eclipse.jface.viewers.ColumnWeightData; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.TableViewerColumn; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerCell; import org.eclipse.jface.viewers.ViewerComparator; import org.eclipse.jface.window.Window; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.layout.RowLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Link; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.MenuItem; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import org.eclipse.ui.dialogs.ListDialog; import ch.elexis.core.constants.Preferences; import ch.elexis.core.constants.StringConstants; import ch.elexis.core.services.holder.ConfigServiceHolder; import ch.elexis.core.services.holder.StockCommissioningServiceHolder; import ch.elexis.core.ui.UiDesk; import ch.elexis.core.ui.dialogs.KontaktSelektor; import ch.elexis.core.ui.icons.Images; import ch.elexis.core.ui.preferences.ConfigServicePreferenceStore.Scope; import ch.elexis.data.Kontakt; import ch.elexis.data.Mandant; import ch.elexis.data.Query; import ch.elexis.data.Stock; public class StockManagementPreferencePage extends PreferencePage implements IWorkbenchPreferencePage { private DataBindingContext m_bindingContext; private Table tableStocks; private Text txtCode; private Text txtDescription; private Text txtLocation; private Text txtPrio; private Label lblOwnerText; private Label lblResponsibleText; private Button btnChkStoreInvalidNumbers; private Button btnIgnoreOrderedArticlesOnNextOrder; private WritableValue<Stock> stockDetail = new WritableValue<Stock>(null, Stock.class); private TableViewer tableViewer; private Text txtMachineConfig; private Label lblMachineuuid; private Label lblDefaultArticleProvider; private Button btnMachineOutlayPartialPackages; private Button btnStoreBelow; private Button btnStoreAtMin; /** * Create the preference page. */ public StockManagementPreferencePage(){ setTitle(Messages.LagerverwaltungPrefs_storageManagement); } /** * Create contents of the preference page. * * @param parent */ @Override public Control createContents(Composite parent){ Composite container = new Composite(parent, SWT.NULL); container.setLayout(new GridLayout(1, false)); Group group = new Group(container, SWT.NONE); group.setLayout(new GridLayout(1, false)); group.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); group.setText(Messages.StockManagementPreferencePage_group_text); Composite composite = new Composite(group, SWT.NONE); GridData gd_composite = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1); gd_composite.heightHint = 150; composite.setLayoutData(gd_composite); TableColumnLayout tcl_composite = new TableColumnLayout(); composite.setLayout(tcl_composite); tableViewer = new TableViewer(composite, SWT.BORDER | SWT.FULL_SELECTION); tableViewer.setContentProvider(ArrayContentProvider.getInstance()); tableViewer.setComparator(new ViewerComparator() { @Override public int compare(Viewer viewer, Object e1, Object e2){ Stock s1 = (Stock) e1; int s1I = (s1.getPriority() != null) ? s1.getPriority() : Integer.MAX_VALUE; Stock s2 = (Stock) e2; int s2I = (s2.getPriority() != null) ? s2.getPriority() : Integer.MAX_VALUE; return Integer.compare(s1I, s2I); } }); tableViewer.addSelectionChangedListener(e -> { StructuredSelection ss = (StructuredSelection) e.getSelection(); if (ss.isEmpty()) { stockDetail.setValue(null); } else { stockDetail.setValue((Stock) ss.getFirstElement()); } }); tableStocks = tableViewer.getTable(); tableStocks.setHeaderVisible(true); tableStocks.setLinesVisible(true); Menu menu = new Menu(tableStocks); tableStocks.setMenu(menu); MenuItem mntmAddStock = new MenuItem(menu, SWT.NONE); mntmAddStock.setText(Messages.StockManagementPreferencePage_mntmNewItem_text); mntmAddStock.setImage(Images.IMG_NEW.getImage()); mntmAddStock.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e){ Stock stock = new Stock("", Integer.MAX_VALUE); tableViewer.add(stock); tableViewer.setSelection(new StructuredSelection(stock)); } }); MenuItem mntmRemoveStock = new MenuItem(menu, SWT.NONE); mntmRemoveStock.setText(Messages.StockManagementPreferencePage_mntmNewItem_text_1); mntmRemoveStock.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e){ Stock stock = (Stock) stockDetail.getValue(); if (stock != null) { boolean ret = MessageDialog.openQuestion(UiDesk.getTopShell(), "Lager löschen", "Das Löschen dieses Lagers löscht alle darauf verzeichneten Lagerbestände. Sind Sie sicher?"); if (ret) { stock.removeFromDatabase(); tableViewer.remove(stock); } } } }); TableViewerColumn tvcPriority = new TableViewerColumn(tableViewer, SWT.NONE); TableColumn tblclmPriority = tvcPriority.getColumn(); tcl_composite.setColumnData(tblclmPriority, new ColumnPixelData(30, true, true)); tblclmPriority.setText(Messages.StockManagementPreferencePage_tblclmnNewColumn_text); tvcPriority.setLabelProvider(new CellLabelProvider() { @Override public void update(ViewerCell cell){ Stock s = (Stock) cell.getElement(); if (s == null) return; cell.setText(Integer.toString(s.getPriority())); } }); TableViewerColumn tvcCode = new TableViewerColumn(tableViewer, SWT.NONE); TableColumn tblclmnCode = tvcCode.getColumn(); tcl_composite.setColumnData(tblclmnCode, new ColumnPixelData(40)); tblclmnCode.setText(Messages.StockManagementPreferencePage_tblclmnNewColumn_text_1); tvcCode.setLabelProvider(new CellLabelProvider() { @Override public void update(ViewerCell cell){ Stock s = (Stock) cell.getElement(); if (s == null) return; cell.setText(s.getCode()); } }); TableViewerColumn tvcDescription = new TableViewerColumn(tableViewer, SWT.NONE); TableColumn tblclmnDescription = tvcDescription.getColumn(); tcl_composite.setColumnData(tblclmnDescription, new ColumnWeightData(50)); tblclmnDescription.setText(Messages.StockManagementPreferencePage_tblclmnNewColumn_text_3); tvcDescription.setLabelProvider(new CellLabelProvider() { @Override public void update(ViewerCell cell){ Stock s = (Stock) cell.getElement(); if (s == null) return; cell.setText(s.getDescription()); } }); TableViewerColumn tvcOwner = new TableViewerColumn(tableViewer, SWT.NONE); TableColumn tblclmnOwner = tvcOwner.getColumn(); tcl_composite.setColumnData(tblclmnOwner, new ColumnWeightData(40)); tblclmnOwner.setText(Messages.StockManagementPreferencePage_tblclmnNewColumn_text_2); tvcOwner.setLabelProvider(new CellLabelProvider() { @Override public void update(ViewerCell cell){ Stock s = (Stock) cell.getElement(); if (s != null) { Mandant owner = s.getOwner(); if (owner != null) { cell.setText(owner.getLabel()); } } } }); Composite compositeDetail = new Composite(group, SWT.NONE); compositeDetail.setLayout(new GridLayout(4, false)); compositeDetail.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true, 1, 1)); Label lblPrio = new Label(compositeDetail, SWT.NONE); lblPrio.setText(Messages.StockManagementPreferencePage_lblPrio_text); txtPrio = new Text(compositeDetail, SWT.BORDER); GridData gd_txtPrio = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1); gd_txtPrio.widthHint = 150; txtPrio.setLayoutData(gd_txtPrio); Label lblCode = new Label(compositeDetail, SWT.NONE); lblCode.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); lblCode.setToolTipText(Messages.StockManagementPreferencePage_lblCode_toolTipText); lblCode.setText(Messages.StockManagementPreferencePage_lblCode_text); txtCode = new Text(compositeDetail, SWT.BORDER); GridData gd_txtCode = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1); gd_txtCode.widthHint = 100; txtCode.setLayoutData(gd_txtCode); txtCode.setTextLimit(3); Label lblDescription = new Label(compositeDetail, SWT.NONE); lblDescription.setText(Messages.StockManagementPreferencePage_lblDescription_text); txtDescription = new Text(compositeDetail, SWT.BORDER); txtDescription.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); Label lblLocation = new Label(compositeDetail, SWT.NONE); lblLocation.setToolTipText(Messages.StockManagementPreferencePage_lblLocation_toolTipText); lblLocation.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); lblLocation.setText(Messages.StockManagementPreferencePage_lblLocation_text); txtLocation = new Text(compositeDetail, SWT.BORDER); txtLocation.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); Link lblOwner = new Link(compositeDetail, SWT.NONE); lblOwner.setToolTipText(Messages.StockManagementPreferencePage_lblOwner_toolTipText); lblOwner.setText(Messages.StockManagementPreferencePage_lblOwner_text); lblOwner.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e){ Stock s = (Stock) stockDetail.getValue(); if (s == null) return; KontaktSelektor ks = new KontaktSelektor(UiDesk.getTopShell(), Mandant.class, "Mandant auswählen", "Bitte selektieren Sie den Eigentümer", new String[] {}); int ret = ks.open(); if (ret == Window.OK) { Mandant p = (Mandant) ks.getSelection(); s.setOwner(p); String label = (p != null) ? p.getLabel() : ""; lblOwnerText.setText(label); } else { s.setOwner(null); lblOwnerText.setText(StringConstants.EMPTY); } tableViewer.update(s, null); } }); lblOwnerText = new Label(compositeDetail, SWT.NONE); lblOwnerText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1)); Link lblResponsible = new Link(compositeDetail, SWT.NONE); lblResponsible .setToolTipText(Messages.StockManagementPreferencePage_lblResponsible_toolTipText); lblResponsible.setText(Messages.StockManagementPreferencePage_lblResonsible_text); lblResponsible.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e){ Stock s = (Stock) stockDetail.getValue(); if (s == null) return; KontaktSelektor ks = new KontaktSelektor(UiDesk.getTopShell(), Kontakt.class, "Lagerverantwortlichen auswählen", "Bitte selektieren Sie den Lagerverantwortlichen", new String[] {}); int ret = ks.open(); if (ret == Window.OK) { Kontakt p = (Kontakt) ks.getSelection(); s.setResponsible(p); String label = (p != null) ? p.getLabel() : ""; lblResponsibleText.setText(label); } else { s.setResponsible(null); lblResponsibleText.setText(""); } } }); lblResponsibleText = new Label(compositeDetail, SWT.NONE); lblResponsibleText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1)); Label lblNewLabel = new Label(compositeDetail, SWT.SEPARATOR | SWT.HORIZONTAL); lblNewLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 4, 1)); lblNewLabel.setText(Messages.StockManagementPreferencePage_lblNewLabel_text); Link lblMachine = new Link(compositeDetail, SWT.NONE); lblMachine.setToolTipText(Messages.StockManagementPreferencePage_lblMachine_toolTipText); lblMachine.setText(Messages.StockManagementPreferencePage_lblMachine_text); lblMachine.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e){ Stock s = (Stock) stockDetail.getValue(); if (s == null) { return; } List<UUID> allDrivers = StockCommissioningServiceHolder.get().listAllAvailableDrivers(); if (allDrivers.size() == 0) { MessageDialog.openInformation(UiDesk.getTopShell(), "No drivers found", "There are no stock commissioning system drivers available."); return; } ListDialog ld = new ListDialog(UiDesk.getTopShell()); ld.setTitle("Driver selection"); ld.setMessage("Please select a commissioning system driver"); ld.setContentProvider(ArrayContentProvider.getInstance()); ld.setAddCancelButton(true); ld.setLabelProvider(new LabelProvider() { @Override public String getText(Object element){ return StockCommissioningServiceHolder.get() .getInfoStringForDriver((UUID) element, true); } }); ld.setInput(allDrivers); ld.setWidthInChars(80); ld.setHeightInChars(5); int retVal = ld.open(); UUID ics = null; if (Dialog.OK == retVal) { Object[] result = ld.getResult(); if (result.length > 0) { ics = (UUID) result[0]; } } else if (Dialog.CANCEL == retVal) { ics = null; } if (ics != null) { s.setDriverUuid(ics.toString()); lblMachineuuid.setText(StockCommissioningServiceHolder.get() .getInfoStringForDriver(ics, false)); } else { s.setDriverUuid(null); lblMachineuuid.setText(StringConstants.EMPTY); } } }); lblMachineuuid = new Label(compositeDetail, SWT.NONE); lblMachineuuid.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1)); Label lblMachineConfig = new Label(compositeDetail, SWT.NONE); lblMachineConfig.setText(Messages.StockManagementPreferencePage_lblMachineConfig_text); txtMachineConfig = new Text(compositeDetail, SWT.BORDER); txtMachineConfig.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1)); btnMachineOutlayPartialPackages = new Button(compositeDetail, SWT.CHECK); btnMachineOutlayPartialPackages .setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 4, 1)); btnMachineOutlayPartialPackages .setText(Messages.StockManagementPreferencePage_btnMachineOutlayPartialPackages_text); boolean outlayPartialPackages = ConfigServiceHolder.getGlobal(Preferences.INVENTORY_MACHINE_OUTLAY_PARTIAL_PACKAGES, Preferences.INVENTORY_MACHINE_OUTLAY_PARTIAL_PACKAGES_DEFAULT); btnMachineOutlayPartialPackages.setSelection(outlayPartialPackages); btnIgnoreOrderedArticlesOnNextOrder = new Button(container, SWT.CHECK); btnIgnoreOrderedArticlesOnNextOrder .setText(Messages.LagerverwaltungPrefs_ignoreOrderedArticleOnNextOrder); btnIgnoreOrderedArticlesOnNextOrder.setSelection(getPreferenceStore() .getBoolean(Preferences.INVENTORY_ORDER_EXCLUDE_ALREADY_ORDERED_ITEMS_ON_NEXT_ORDER)); btnChkStoreInvalidNumbers = new Button(container, SWT.CHECK); btnChkStoreInvalidNumbers.setText(Messages.LagerverwaltungPrefs_checkForInvalid); btnChkStoreInvalidNumbers.setSelection( getPreferenceStore().getBoolean(Preferences.INVENTORY_CHECK_ILLEGAL_VALUES)); Group group1 = new Group(container, SWT.SHADOW_IN); group1.setText(Messages.LagerverwaltungPrefs_orderCriteria); group1.setLayout(new RowLayout(SWT.VERTICAL)); btnStoreBelow = new Button(group1, SWT.RADIO); btnStoreBelow.setText(Messages.LagerverwaltungPrefs_orderWhenBelowMi); btnStoreAtMin = new Button(group1, SWT.RADIO); btnStoreAtMin.setText(Messages.LagerverwaltungPrefs_orderWhenAtMin); int valInventoryOrderTrigger = ConfigServiceHolder.getGlobal(Preferences.INVENTORY_ORDER_TRIGGER, Preferences.INVENTORY_ORDER_TRIGGER_DEFAULT); boolean isInventoryOrderEqualValue = Preferences.INVENTORY_ORDER_TRIGGER_EQUAL == valInventoryOrderTrigger; btnStoreAtMin.setSelection(isInventoryOrderEqualValue); btnStoreBelow.setSelection(!isInventoryOrderEqualValue); Composite compDefaultProvider = new Composite(container, SWT.NONE); compDefaultProvider.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1)); GridLayout gl_compDefaultProvider = new GridLayout(3, false); gl_compDefaultProvider.marginWidth = 0; gl_compDefaultProvider.marginHeight = 0; compDefaultProvider.setLayout(gl_compDefaultProvider); Link linkDefaultArticleProvider = new Link(compDefaultProvider, SWT.NONE); linkDefaultArticleProvider.setToolTipText( Messages.StockManagementPreferencePage_linkDefaultArticleProvider_toolTipText); linkDefaultArticleProvider .setText(Messages.StockManagementPreferencePage_linkDefaultArticleProvider_text); linkDefaultArticleProvider.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e){ KontaktSelektor ks = new KontaktSelektor(UiDesk.getTopShell(), Kontakt.class, "Standard-Lieferant auswählen", "Bitte selektieren Sie den Standard-Lieferanten", new String[] {}); int ret = ks.open(); if (ret == Window.OK) { Kontakt p = (Kontakt) ks.getSelection(); if (p != null) { ConfigServiceHolder.setGlobal(Preferences.INVENTORY_DEFAULT_ARTICLE_PROVIDER, p.getId()); lblDefaultArticleProvider.setText(p.getLabel()); } } else { ConfigServiceHolder.setGlobal(Preferences.INVENTORY_DEFAULT_ARTICLE_PROVIDER, null); lblDefaultArticleProvider.setText(""); } } }); lblDefaultArticleProvider = new Label(compDefaultProvider, SWT.NONE); lblDefaultArticleProvider .setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); String id = ConfigServiceHolder.getGlobal(Preferences.INVENTORY_DEFAULT_ARTICLE_PROVIDER, null); lblDefaultArticleProvider.setText(""); new Label(compDefaultProvider, SWT.NONE); if (id != null) { Kontakt load = Kontakt.load(id); if (load.exists()) { lblDefaultArticleProvider.setText(load.getLabel()); } } tableViewer.setInput(new Query<Stock>(Stock.class).execute()); m_bindingContext = initDataBindings(); stockDetail.addChangeListener(e -> { Stock stock = (Stock) stockDetail.getValue(); if (stock != null) { Mandant owner = stock.getOwner(); if (owner != null) { lblOwnerText.setText(owner.getLabel()); } else { lblOwnerText.setText(""); } Kontakt responsible = stock.getResponsible(); if (responsible != null) { lblResponsibleText.setText(responsible.getLabel()); } else { lblResponsibleText.setText(""); } String machineUuid = stock.getDriverUuid(); if (machineUuid != null && !machineUuid.isEmpty()) { String info = StockCommissioningServiceHolder.get() .getInfoStringForDriver(UUID.fromString(machineUuid), false); lblMachineuuid.setText(info); } else { lblMachineuuid.setText(""); } } else { lblOwnerText.setText(""); lblResponsibleText.setText(""); } }); return container; } /** * Initialize the preference page. */ public void init(IWorkbench workbench){ setPreferenceStore(new ConfigServicePreferenceStore(Scope.GLOBAL)); getPreferenceStore().setDefault(Preferences.INVENTORY_CHECK_ILLEGAL_VALUES, Preferences.INVENTORY_CHECK_ILLEGAL_VALUES_DEFAULT); getPreferenceStore().setDefault( Preferences.INVENTORY_ORDER_EXCLUDE_ALREADY_ORDERED_ITEMS_ON_NEXT_ORDER, Preferences.INVENTORY_ORDER_EXCLUDE_ALREADY_ORDERED_ITEMS_ON_NEXT_ORDER_DEFAULT); } @Override protected void performApply(){ tableViewer.setInput(new Query<Stock>(Stock.class).execute()); setErrorMessage(null); super.performApply(); } @Override public boolean performOk(){ getPreferenceStore().setValue(Preferences.INVENTORY_CHECK_ILLEGAL_VALUES, btnChkStoreInvalidNumbers.getSelection()); getPreferenceStore().setValue( Preferences.INVENTORY_ORDER_EXCLUDE_ALREADY_ORDERED_ITEMS_ON_NEXT_ORDER, btnIgnoreOrderedArticlesOnNextOrder.getSelection()); getPreferenceStore().setValue(Preferences.INVENTORY_MACHINE_OUTLAY_PARTIAL_PACKAGES, btnMachineOutlayPartialPackages.getSelection()); getPreferenceStore().setValue(Preferences.INVENTORY_ORDER_TRIGGER, btnStoreBelow.getSelection() ? Preferences.INVENTORY_ORDER_TRIGGER_BELOW : Preferences.INVENTORY_ORDER_TRIGGER_EQUAL); ((SettingsPreferenceStore) getPreferenceStore()).flush(); return super.performOk(); } protected DataBindingContext initDataBindings(){ DataBindingContext bindingContext = new DataBindingContext(); // IObservableValue observeTextTxtCodeObserveWidget = WidgetProperties.text(SWT.Modify).observe(txtCode); IObservableValue stockDetailCodeObserveDetailValue = PojoProperties.value(Stock.class, "code", String.class).observeDetail(stockDetail); bindingContext.bindValue(observeTextTxtCodeObserveWidget, stockDetailCodeObserveDetailValue, null, null); // IObservableValue observeTextTxtDescriptionObserveWidget = WidgetProperties.text(SWT.Modify).observe(txtDescription); IObservableValue stockDetailDescriptionObserveDetailValue = PojoProperties .value(Stock.class, "description", String.class).observeDetail(stockDetail); bindingContext.bindValue(observeTextTxtDescriptionObserveWidget, stockDetailDescriptionObserveDetailValue, null, null); // IObservableValue observeTextTxtLocationObserveWidget = WidgetProperties.text(SWT.Modify).observe(txtLocation); IObservableValue stockDetailLocationObserveDetailValue = PojoProperties.value(Stock.class, "location", String.class).observeDetail(stockDetail); bindingContext.bindValue(observeTextTxtLocationObserveWidget, stockDetailLocationObserveDetailValue, null, null); // IObservableValue observeTextTxtPrioObserveWidget = WidgetProperties.text(SWT.Modify).observe(txtPrio); IObservableValue stockDetailGlobalPreferenceObserveDetailValue = PojoProperties.value(Stock.class, "priority", Integer.class).observeDetail(stockDetail); bindingContext.bindValue(observeTextTxtPrioObserveWidget, stockDetailGlobalPreferenceObserveDetailValue, null, null); // IObservableValue observeTextTxtMachineConfigObserveWidget = WidgetProperties.text(SWT.Modify).observe(txtMachineConfig); IObservableValue stockDetailMachineConfigObserveDetailValue = PojoProperties .value(Stock.class, "driverConfig", String.class).observeDetail(stockDetail); bindingContext.bindValue(observeTextTxtMachineConfigObserveWidget, stockDetailMachineConfigObserveDetailValue, null, null); // return bindingContext; } }
[20852] do not flush ConfigServicePreferenceStore on stock pref page
bundles/ch.elexis.core.ui/src/ch/elexis/core/ui/preferences/StockManagementPreferencePage.java
[20852] do not flush ConfigServicePreferenceStore on stock pref page
Java
mpl-2.0
50c59ad9f307d16bc312d9b87b9fcfda1ea8f44c
0
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: java_environment.java,v $ * $Revision: 1.17 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ package com.sun.star.lib.uno.environments.java; import com.sun.star.uno.IEnvironment; import com.sun.star.uno.Type; import com.sun.star.uno.UnoRuntime; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import java.util.HashMap; import java.util.Iterator; /** * The java_environment is the environment where objects and * interfaces are registered, which are mapped out of java or * into java. * * <p>The java_environment implements the <code>IEnvironment</code> interface * defined in the uno runtime.</p> * * @see com.sun.star.uno.UnoRuntime * @see com.sun.star.uno.IEnvironment * @since UDK1.0 */ public final class java_environment implements IEnvironment { public java_environment(Object context) { this.context = context; } // @see com.sun.star.uno.IEnvironment#getContext public Object getContext() { return context; } // @see com.sun.star.uno.IEnvironment#getName public String getName() { return "java"; } // @see com.sun.star.uno.IEnvironment#registerInterface public Object registerInterface(Object object, String[] oid, Type type) { if (oid[0] == null) { oid[0] = UnoRuntime.generateOid(object); } return (isProxy(object) ? proxies : localObjects).register( object, oid[0], type); } /** * You have to revoke ANY interface that has been registered via this * method. * * @param oid object id of interface to be revoked * @param type the type description of the interface * @see com.sun.star.uno.IEnvironment#revokeInterface */ public void revokeInterface(String oid, Type type) { if (!proxies.revoke(oid, type)) { localObjects.revoke(oid, type); } } /** * Retrieves an interface identified by its object id and type from this * environment. * * @param oid object id of interface to be retrieved * @param type the type description of the interface to be retrieved * @see com.sun.star.uno.IEnvironment#getRegisteredInterface */ public Object getRegisteredInterface(String oid, Type type) { Object o = proxies.get(oid, type); if (o == null) { o = localObjects.get(oid, type); } return o; } /** * Retrieves the object identifier for a registered interface from this * environment. * * @param object a registered interface * @see com.sun.star.uno.IEnvironment#getRegisteredObjectIdentifier */ public String getRegisteredObjectIdentifier(Object object) { return UnoRuntime.generateOid(object); } // @see com.sun.star.uno.IEnvironment#list public void list() { // TODO??? // synchronized (proxies) { // System.err.println("##### " + getClass().getName() + ".list: " // + getName() + ", " + getContext()); // for (Iterator it = proxies.values().iterator(); it.hasNext();) { // System.err.println("#### entry: " + it.next()); // } // } } /** * Revokes all registered proxy interfaces. * * <p>This method should be part of <code>IEnvironment</code>. It is called * from <code>com.sun.star.lib.uno.bridges.java_remote.<!-- * -->java_remote_bridge.dispose</code>.</p> */ public void revokeAllProxies() { proxies.clear(); } // TODO What's this??? java.lang.Object#equals requires reflexivity... // // Maybe this was hacked in so that different bridges use different // instances of java_environment. That is desirable for the following // reason: An OID is bridged in over bridge A, a proxy is created on the // Java side, and recorded in the java_environment. The same OID is then // bridged in over another bridge B. If there were only one // java_environment shared by both bridges, the proxy from bridge A would be // reused. If now bridge A is taken down programatically (e.g., because // some controlling code somehow deduced that no objects are mapped over // that bridge any longer), but the proxy is still used by bridge B, using // the proxy would now result in errors. The explicit API to control // bridges forbids to transparently share proxies between bridges, and using // different java_environment instances for different bridges is the way to // enforce this. public boolean equals(Object obj) { return false; } private static final class Registry { public synchronized Object register( Object object, String oid, Type type) { cleanUp(); Level1Entry l1 = level1map.get(oid); if (l1 != null) { Level2Entry l2 = l1.level2map.get(type); if (l2 != null) { Object o = l2.get(); if (o != null) { l2.acquire(); return o; } } } // TODO If a holder references an unreachable object, but still has // a positive count, it is replaced with a new holder (referencing a // reachable object, and with a count of 1). Any later calls to // revoke that should decrement the count of the previous holder // would now decrement the count of the new holder, removing it // prematurely. This is a design flaw that will be fixed when // IEnvironment.revokeInterface is changed to no longer use // counting. (And this problem is harmless, as currently a holder // either references a strongly held object and uses register/revoke // to control it, or references a weakly held proxy and never // revokes it.) if (l1 == null) { l1 = new Level1Entry(); level1map.put(oid, l1); } l1.level2map.put(type, new Level2Entry(oid, type, object, queue)); return object; } public synchronized boolean revoke(String oid, Type type) { Level1Entry l1 = level1map.get(oid); Level2Entry l2 = null; if (l1 != null) { l2 = l1.level2map.get(type); if (l2 != null && l2.release()) { removeLevel2Entry(l1, oid, type); } } cleanUp(); return l2 != null; } public synchronized Object get(String oid, Type type) { Level1Entry l1 = level1map.get(oid); return l1 == null ? null : l1.find(type); } public synchronized void clear() { level1map.clear(); cleanUp(); } // must only be called while synchronized on this Registry: private void cleanUp() { for (;;) { Level2Entry l2 = (Level2Entry) queue.poll(); if (l2 == null) { break; } // It is possible that a Level2Entry e1 for the OID/type pair // (o,t) becomes weakly reachable, then another Level2Entry e2 // is registered for the same pair (o,t) (a new Level2Entry is // created since now e1.get() == null), and only then e1 is // enqueued. To not erroneously remove the new e2 in that case, // check whether the map still contains e1: Level1Entry l1 = level1map.get(l2.oid); if (l1 != null && l1.level2map.get(l2.type) == l2) { removeLevel2Entry(l1, l2.oid, l2.type); } } } // must only be called while synchronized on this Registry: private void removeLevel2Entry(Level1Entry l1, String oid, Type type) { l1.level2map.remove(type); if (l1.level2map.isEmpty()) { level1map.remove(oid); } } private static final class Level1Entry { // must only be called while synchronized on enclosing Registry: public Object find(Type type) { // First, look for an exactly matching entry; then, look for an // arbitrary entry for a subtype of the request type: Level2Entry l2 = level2map.get(type); if (l2 != null) { Object o = l2.get(); if (o != null) { return o; } } for (Iterator<Level2Entry> i = level2map.values().iterator(); i.hasNext();) { l2 = i.next(); if (type.isSupertypeOf(l2.type)) { Object o = l2.get(); if (o != null) { return o; } } } return null; } public final HashMap<Type, Level2Entry> level2map = new HashMap<Type, Level2Entry>(); } private static final class Level2Entry extends WeakReference<Object> { public Level2Entry( String oid, Type type, Object object, ReferenceQueue queue) { super(object, queue); this.oid = oid; this.type = type; } // must only be called while synchronized on enclosing Registry: public void acquire() { ++count; } // must only be called while synchronized on enclosing Registry: public boolean release() { return --count == 0; } public final String oid; public final Type type; private int count = 1; } private final HashMap<String, Level1Entry> level1map = new HashMap<String, Level1Entry>(); private final ReferenceQueue queue = new ReferenceQueue(); } private boolean isProxy(Object object) { return object instanceof com.sun.star.lib.uno.Proxy; } private static final Registry localObjects = new Registry(); private final Object context; private final Registry proxies = new Registry(); }
jurt/com/sun/star/lib/uno/environments/java/java_environment.java
/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: java_environment.java,v $ * $Revision: 1.17 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ package com.sun.star.lib.uno.environments.java; import com.sun.star.uno.IEnvironment; import com.sun.star.uno.Type; import com.sun.star.uno.UnoRuntime; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; /** * The java_environment is the environment where objects and * interfaces are registered, which are mapped out of java or * into java. * * <p>The java_environment implements the <code>IEnvironment</code> interface * defined in the uno runtime.</p> * * @see com.sun.star.uno.UnoRuntime * @see com.sun.star.uno.IEnvironment * @since UDK1.0 */ public final class java_environment implements IEnvironment { public java_environment(Object context) { this.context = context; } // @see com.sun.star.uno.IEnvironment#getContext public Object getContext() { return context; } // @see com.sun.star.uno.IEnvironment#getName public String getName() { return "java"; } // @see com.sun.star.uno.IEnvironment#registerInterface public Object registerInterface(Object object, String[] oid, Type type) { if (oid[0] == null) { oid[0] = UnoRuntime.generateOid(object); } return (isProxy(object) ? proxies : localObjects).register( object, oid[0], type); } /** * You have to revoke ANY interface that has been registered via this * method. * * @param oid object id of interface to be revoked * @param type the type description of the interface * @see com.sun.star.uno.IEnvironment#revokeInterface */ public void revokeInterface(String oid, Type type) { if (!proxies.revoke(oid, type)) { localObjects.revoke(oid, type); } } /** * Retrieves an interface identified by its object id and type from this * environment. * * @param oid object id of interface to be retrieved * @param type the type description of the interface to be retrieved * @see com.sun.star.uno.IEnvironment#getRegisteredInterface */ public Object getRegisteredInterface(String oid, Type type) { Object o = proxies.get(oid, type); if (o == null) { o = localObjects.get(oid, type); } return o; } /** * Retrieves the object identifier for a registered interface from this * environment. * * @param object a registered interface * @see com.sun.star.uno.IEnvironment#getRegisteredObjectIdentifier */ public String getRegisteredObjectIdentifier(Object object) { return UnoRuntime.generateOid(object); } // @see com.sun.star.uno.IEnvironment#list public void list() { // TODO??? // synchronized (proxies) { // System.err.println("##### " + getClass().getName() + ".list: " // + getName() + ", " + getContext()); // for (Iterator it = proxies.values().iterator(); it.hasNext();) { // System.err.println("#### entry: " + it.next()); // } // } } /** * Revokes all registered proxy interfaces. * * <p>This method should be part of <code>IEnvironment</code>. It is called * from <code>com.sun.star.lib.uno.bridges.java_remote.<!-- * -->java_remote_bridge.dispose</code>.</p> */ public void revokeAllProxies() { proxies.clear(); } // TODO What's this??? java.lang.Object#equals requires reflexivity... // // Maybe this was hacked in so that different bridges use different // instances of java_environment. That is desirable for the following // reason: An OID is bridged in over bridge A, a proxy is created on the // Java side, and recorded in the java_environment. The same OID is then // bridged in over another bridge B. If there were only one // java_environment shared by both bridges, the proxy from bridge A would be // reused. If now bridge A is taken down programatically (e.g., because // some controlling code somehow deduced that no objects are mapped over // that bridge any longer), but the proxy is still used by bridge B, using // the proxy would now result in errors. The explicit API to control // bridges forbids to transparently share proxies between bridges, and using // different java_environment instances for different bridges is the way to // enforce this. public boolean equals(Object obj) { return false; } private static final class Registry { public Object register(Object object, String oid, Type type) { synchronized (map) { cleanUp(); Level1Entry l1 = getLevel1Entry(oid); if (l1 != null) { Level2Entry l2 = l1.get(type); if (l2 != null) { Object o = l2.get(); if (o != null) { l2.acquire(); return o; } } } // TODO If a holder references an unreachable object, but still // has a positive count, it is replaced with a new holder // (referencing a reachable object, and with a count of 1). Any // later calls to revoke that should decrement the count of the // previous holder would now decrement the count of the new // holder, removing it prematurely. This is a design flaw that // will be fixed when IEnvironment.revokeInterface is changed to // no longer use counting. (And this problem is harmless, as // currently a holder either references a strongly held object // and uses register/revoke to control it, or references a // weakly held proxy and never revokes it.) if (l1 == null) { l1 = new Level1Entry(); map.put(oid, l1); } l1.add(new Level2Entry(oid, type, object, queue)); } return object; } public boolean revoke(String oid, Type type) { synchronized (map) { Level1Entry l1 = getLevel1Entry(oid); Level2Entry l2 = null; if (l1 != null) { l2 = l1.get(type); if (l2 != null && l2.release()) { removeLevel2Entry(oid, l1, l2); } } cleanUp(); return l2 != null; } } public Object get(String oid, Type type) { synchronized (map) { Level1Entry l1 = getLevel1Entry(oid); return l1 == null ? null : l1.find(type); } } public void clear() { synchronized (map) { map.clear(); cleanUp(); } } // must only be called while synchronized on map: private void cleanUp() { for (;;) { Level2Entry l2 = (Level2Entry) queue.poll(); if (l2 == null) { break; } // It is possible that a Level2Entry e1 for the OID/type pair // (o,t) becomes weakly reachable, then another Level2Entry e2 // is registered for the same pair (o,t) (a new Level2Entry is // created since now e1.get() == null), and only then e1 is // enqueued. To not erroneously remove the new e2 in that case, // check whether the map still contains e1: String oid = l2.getOid(); Level1Entry l1 = getLevel1Entry(oid); if (l1 != null && l1.get(l2.getType()) == l2) { removeLevel2Entry(oid, l1, l2); } } } // must only be called while synchronized on map: private Level1Entry getLevel1Entry(String oid) { return (Level1Entry) map.get(oid); } // must only be called while synchronized on map: private void removeLevel2Entry(String oid, Level1Entry l1, Level2Entry l2) { if (l1.remove(l2)) { map.remove(oid); } } private static final class Level1Entry { // must only be called while synchronized on map: public Level2Entry get(Type type) { for (Iterator i = list.iterator(); i.hasNext();) { Level2Entry l2 = (Level2Entry) i.next(); if (l2.getType().equals(type)) { return l2; } } return null; } // must only be called while synchronized on map: public Object find(Type type) { // First, look for an exactly matching entry; then, look for an // arbitrary entry for a subtype of the request type: for (Iterator i = list.iterator(); i.hasNext();) { Level2Entry l2 = (Level2Entry) i.next(); if (l2.getType().equals(type)) { Object o = l2.get(); if (o != null) { return o; } } } for (Iterator i = list.iterator(); i.hasNext();) { Level2Entry l2 = (Level2Entry) i.next(); if (type.isSupertypeOf(l2.getType())) { Object o = l2.get(); if (o != null) { return o; } } } return null; } // must only be called while synchronized on map: public void add(Level2Entry l2) { list.add(l2); } // must only be called while synchronized on map: public boolean remove(Level2Entry l2) { list.remove(l2); return list.isEmpty(); } private final LinkedList list = new LinkedList(); // of Level2Entry } private static final class Level2Entry extends WeakReference { public Level2Entry(String oid, Type type, Object object, ReferenceQueue queue) { super(object, queue); this.oid = oid; this.type = type; } public String getOid() { return oid; } public Type getType() { return type; } // must only be called while synchronized on map: public void acquire() { ++count; } // must only be called while synchronized on map: public boolean release() { return --count == 0; } private final String oid; private final Type type; private int count = 1; } private final HashMap map = new HashMap(); // from OID (String) to Level1Entry private final ReferenceQueue queue = new ReferenceQueue(); } private boolean isProxy(Object object) { return object instanceof com.sun.star.lib.uno.Proxy; } private static final Registry localObjects = new Registry(); private final Object context; private final Registry proxies = new Registry(); }
sb116: #i107157# redesigned java_environment.Registry to avoid memory leaks (and simplified code)
jurt/com/sun/star/lib/uno/environments/java/java_environment.java
sb116: #i107157# redesigned java_environment.Registry to avoid memory leaks (and simplified code)
Java
agpl-3.0
af8445806351d231d19736a1fd2ebed6cdbe5722
0
jwillia/kc-old1,geothomasp/kcmit,geothomasp/kcmit,geothomasp/kcmit,kuali/kc,iu-uits-es/kc,ColostateResearchServices/kc,ColostateResearchServices/kc,ColostateResearchServices/kc,iu-uits-es/kc,geothomasp/kcmit,mukadder/kc,UniversityOfHawaiiORS/kc,kuali/kc,jwillia/kc-old1,kuali/kc,jwillia/kc-old1,UniversityOfHawaiiORS/kc,UniversityOfHawaiiORS/kc,jwillia/kc-old1,geothomasp/kcmit,mukadder/kc,iu-uits-es/kc,mukadder/kc
/* * Copyright 2007 The Kuali Foundation. * * Licensed under the Educational Community License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.kra.budget.bo; import java.sql.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import org.apache.ojb.broker.PersistenceBroker; import org.apache.ojb.broker.PersistenceBrokerException; import org.kuali.core.bo.DocumentHeader; import org.kuali.core.service.BusinessObjectService; import org.kuali.core.util.KualiDecimal; import org.kuali.kra.bo.KraPersistableBusinessObjectBase; import org.kuali.kra.infrastructure.KraServiceLocator; /** * Class representation of a Budget Overview Business Object. This BO maps to * the BudgetDocument table but excludes most references. * * @author [email protected] */ public class BudgetVersionOverview extends KraPersistableBusinessObjectBase implements Comparable<BudgetVersionOverview> { private String proposalNumber; private Integer budgetVersionNumber; private String documentNumber; private String documentDescription; private KualiDecimal costSharingAmount; private Date endDate; private Date startDate; private boolean finalVersionFlag; private String ohRateTypeCode; private KualiDecimal residualFunds; private KualiDecimal totalCost; private KualiDecimal totalDirectCost; private KualiDecimal totalIndirectCost; private KualiDecimal totalCostLimit; private KualiDecimal underrecoveryAmount; private String comments; private String name; private String budgetStatus; public Integer getBudgetVersionNumber() { return budgetVersionNumber; } public void setBudgetVersionNumber(Integer budgetVersionNumber) { this.budgetVersionNumber = budgetVersionNumber; } public KualiDecimal getCostSharingAmount() { return costSharingAmount; } public void setCostSharingAmount(KualiDecimal costSharingAmount) { this.costSharingAmount = costSharingAmount; } public boolean isFinalVersionFlag() { return finalVersionFlag; } public void setFinalVersionFlag(boolean finalVersionFlag) { this.finalVersionFlag = finalVersionFlag; } public String getOhRateTypeCode() { return ohRateTypeCode; } public void setOhRateTypeCode(String ohRateTypeCode) { this.ohRateTypeCode = ohRateTypeCode; } public String getProposalNumber() { return proposalNumber; } public void setProposalNumber(String proposalNumber) { this.proposalNumber = proposalNumber; } public String getDocumentNumber() { return documentNumber; } public void setDocumentNumber(String documentNumber) { this.documentNumber = documentNumber; } public KualiDecimal getResidualFunds() { return residualFunds; } public void setResidualFunds(KualiDecimal residualFunds) { this.residualFunds = residualFunds; } public KualiDecimal getTotalCost() { return totalCost; } public void setTotalCost(KualiDecimal totalCost) { this.totalCost = totalCost; } public KualiDecimal getTotalDirectCost() { return totalDirectCost; } public void setTotalDirectCost(KualiDecimal totalDirectCost) { this.totalDirectCost = totalDirectCost; } public KualiDecimal getTotalIndirectCost() { return totalIndirectCost; } public void setTotalIndirectCost(KualiDecimal totalIndirectCost) { this.totalIndirectCost = totalIndirectCost; } public KualiDecimal getUnderrecoveryAmount() { return underrecoveryAmount; } public void setUnderrecoveryAmount(KualiDecimal underrecoveryAmount) { this.underrecoveryAmount = underrecoveryAmount; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getBudgetStatus() { return budgetStatus; } public void setBudgetStatus(String budgetStatus) { this.budgetStatus = budgetStatus; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public KualiDecimal getTotalCostLimit() { return totalCostLimit; } public void setTotalCostLimit(KualiDecimal totalCostLimit) { this.totalCostLimit = totalCostLimit; } public String getDocumentDescription() { return documentDescription; } public void setDocumentDescription(String documentDescription) { this.documentDescription = documentDescription; } public String getComments() { return comments; } public void setComments(String comments) { this.comments = comments; } /** * @see org.kuali.core.bo.PersistableBusinessObjectBase#afterLookup() */ @Override public void afterLookup(PersistenceBroker persistenceBroker) throws PersistenceBrokerException { // The purpose of this lookup is to get the document description from the doc header, // without mapping the enire doc header (which can be large) in ojb. super.afterLookup(persistenceBroker); BusinessObjectService boService = KraServiceLocator.getService(BusinessObjectService.class); Map<String, Object> keyMap = new HashMap<String, Object>(); keyMap.put("documentNumber", this.documentNumber); DocumentHeader docHeader = (DocumentHeader) boService.findByPrimaryKey(DocumentHeader.class, keyMap); if (docHeader != null) { this.documentDescription = docHeader.getFinancialDocumentDescription(); } } /** * @see org.kuali.core.bo.BusinessObject#toStringMapper() */ @Override protected LinkedHashMap toStringMapper() { LinkedHashMap<String, Object> propMap = new LinkedHashMap<String, Object>(); propMap.put("proposalNumber", this.getProposalNumber()); propMap.put("budgetVersionNumber", this.getBudgetVersionNumber()); propMap.put("updateTimestamp", this.getUpdateTimestamp()); propMap.put("updateUser", this.getUpdateUser()); return propMap; } /** * * @see java.lang.Comparable */ public int compareTo(BudgetVersionOverview otherVersion) { return this.budgetVersionNumber.compareTo(otherVersion.getBudgetVersionNumber()); } }
src/main/java/org/kuali/kra/budget/bo/BudgetVersionOverview.java
/* * Copyright 2007 The Kuali Foundation. * * Licensed under the Educational Community License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.kra.budget.bo; import java.sql.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import org.apache.ojb.broker.PersistenceBroker; import org.apache.ojb.broker.PersistenceBrokerException; import org.kuali.core.bo.DocumentHeader; import org.kuali.core.service.BusinessObjectService; import org.kuali.core.util.KualiDecimal; import org.kuali.kra.bo.KraPersistableBusinessObjectBase; import org.kuali.kra.infrastructure.KraServiceLocator; /** * Class representation of a Budget Overview Business Object. This BO maps to * the BudgetDocument table but excludes most references. * * @author [email protected] */ public class BudgetVersionOverview extends KraPersistableBusinessObjectBase implements Comparable<BudgetVersionOverview> { private String proposalNumber; private Integer budgetVersionNumber; private String documentNumber; private String documentDescription; private KualiDecimal costSharingAmount; private Date endDate; private Date startDate; private boolean finalVersionFlag; private String ohRateTypeCode; private KualiDecimal residualFunds; private KualiDecimal totalCost; private KualiDecimal totalDirectCost; private KualiDecimal totalIndirectCost; private KualiDecimal totalCostLimit; private KualiDecimal underrecoveryAmount; private String comments; private String name; private String budgetStatus; public Integer getBudgetVersionNumber() { return budgetVersionNumber; } public void setBudgetVersionNumber(Integer budgetVersionNumber) { this.budgetVersionNumber = budgetVersionNumber; } public KualiDecimal getCostSharingAmount() { return costSharingAmount; } public void setCostSharingAmount(KualiDecimal costSharingAmount) { this.costSharingAmount = costSharingAmount; } public boolean isFinalVersionFlag() { return finalVersionFlag; } public void setFinalVersionFlag(boolean finalVersionFlag) { this.finalVersionFlag = finalVersionFlag; } public String getOhRateTypeCode() { return ohRateTypeCode; } public void setOhRateTypeCode(String ohRateTypeCode) { this.ohRateTypeCode = ohRateTypeCode; } public String getProposalNumber() { return proposalNumber; } public void setProposalNumber(String proposalNumber) { this.proposalNumber = proposalNumber; } public String getDocumentNumber() { return documentNumber; } public void setDocumentNumber(String documentNumber) { this.documentNumber = documentNumber; } public KualiDecimal getResidualFunds() { return residualFunds; } public void setResidualFunds(KualiDecimal residualFunds) { this.residualFunds = residualFunds; } public KualiDecimal getTotalCost() { return totalCost; } public void setTotalCost(KualiDecimal totalCost) { this.totalCost = totalCost; } public KualiDecimal getTotalDirectCost() { return totalDirectCost; } public void setTotalDirectCost(KualiDecimal totalDirectCost) { this.totalDirectCost = totalDirectCost; } public KualiDecimal getTotalIndirectCost() { return totalIndirectCost; } public void setTotalIndirectCost(KualiDecimal totalIndirectCost) { this.totalIndirectCost = totalIndirectCost; } public KualiDecimal getUnderrecoveryAmount() { return underrecoveryAmount; } public void setUnderrecoveryAmount(KualiDecimal underrecoveryAmount) { this.underrecoveryAmount = underrecoveryAmount; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getBudgetStatus() { return budgetStatus; } public void setBudgetStatus(String budgetStatus) { this.budgetStatus = budgetStatus; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public KualiDecimal getTotalCostLimit() { return totalCostLimit; } public void setTotalCostLimit(KualiDecimal totalCostLimit) { this.totalCostLimit = totalCostLimit; } public String getDocumentDescription() { return documentDescription; } public void setDocumentDescription(String documentDescription) { this.documentDescription = documentDescription; } public String getComments() { return comments; } public void setComments(String comments) { this.comments = comments; } /** * @see org.kuali.core.bo.PersistableBusinessObjectBase#afterLookup() */ @Override public void afterLookup(PersistenceBroker persistenceBroker) throws PersistenceBrokerException { // The purpose of this lookup is to get the document description from the doc header, // without mapping the enire doc header (which can be large) in ojb. super.afterLookup(persistenceBroker); BusinessObjectService boService = KraServiceLocator.getService(BusinessObjectService.class); Map<String, Object> keyMap = new HashMap<String, Object>(); keyMap.put("documentNumber", this.documentNumber); DocumentHeader docHeader = (DocumentHeader) boService.findByPrimaryKey(DocumentHeader.class, keyMap); this.documentDescription = docHeader.getFinancialDocumentDescription(); } /** * @see org.kuali.core.bo.BusinessObject#toStringMapper() */ @Override protected LinkedHashMap toStringMapper() { LinkedHashMap<String, Object> propMap = new LinkedHashMap<String, Object>(); propMap.put("proposalNumber", this.getProposalNumber()); propMap.put("budgetVersionNumber", this.getBudgetVersionNumber()); propMap.put("updateTimestamp", this.getUpdateTimestamp()); propMap.put("updateUser", this.getUpdateUser()); return propMap; } /** * * @see java.lang.Comparable */ public int compareTo(BudgetVersionOverview otherVersion) { return this.budgetVersionNumber.compareTo(otherVersion.getBudgetVersionNumber()); } }
fix test
src/main/java/org/kuali/kra/budget/bo/BudgetVersionOverview.java
fix test
Java
agpl-3.0
3b09ed60384d2b3667e432630186b182ba1406c3
0
ubicity-devs/ubicity-flickr
package at.ac.ait.ubicity.ubicity.flickrplugin.dto; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; import com.google.gson.Gson; import com.google.gson.annotations.SerializedName; public class FlickrDTO { private static Gson gson = new Gson(); private static SimpleDateFormat df = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ssZZ"); { df.setTimeZone(TimeZone.getTimeZone("UTC")); } private final String id; private final String url; private final String title; @SerializedName("geo_point") private float[] geoPoint; @SerializedName("created_at") private String createdAt; public FlickrDTO(String id, String url, String title, float longitude, float latitude, Date createdAt) { this(id, url, title, createdAt); this.geoPoint = new float[] { longitude, latitude }; } public FlickrDTO(String id, String url, String title, Date createdAt) { this.id = id; this.url = url; this.title = title; if (createdAt != null) { this.createdAt = df.format(createdAt); } } public String getId() { return this.id; } public String getUrl() { return this.url; } public String getTitle() { return this.title; } public float[] getGeoPoint() { return this.geoPoint; } public String getCreatedAt() { return this.createdAt; } public String toJson() { return gson.toJson(this); } }
src/main/java/at/ac/ait/ubicity/ubicity/flickrplugin/dto/FlickrDTO.java
package at.ac.ait.ubicity.ubicity.flickrplugin.dto; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; import com.google.gson.Gson; import com.google.gson.annotations.SerializedName; public class FlickrDTO { private static Gson gson = new Gson(); private static SimpleDateFormat df = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ssZZ"); { df.setTimeZone(TimeZone.getTimeZone("UTC")); } private final String id; private final String url; private final String title; @SerializedName("geo_point") private float[] geoPoint; @SerializedName("created_at") private String createdAt; public FlickrDTO(String id, String url, String title, float longitude, float latitude, Date createdAt) { this(id, url, title, createdAt); this.geoPoint = new float[] { latitude, longitude }; } public FlickrDTO(String id, String url, String title, Date createdAt) { this.id = id; this.url = url; this.title = title; if (createdAt != null) { this.createdAt = df.format(createdAt); } } public String getId() { return this.id; } public String getUrl() { return this.url; } public String getTitle() { return this.title; } public float[] getGeoPoint() { return this.geoPoint; } public String getCreatedAt() { return this.createdAt; } public String toJson() { return gson.toJson(this); } }
Changed latlong to longLat
src/main/java/at/ac/ait/ubicity/ubicity/flickrplugin/dto/FlickrDTO.java
Changed latlong to longLat
Java
lgpl-2.1
6fd482826ff28dbac543283aeb18b4e744daa442
0
levants/lightmare
package org.lightmare.ejb.embeddable; import java.io.IOException; import java.util.Map; import javax.ejb.embeddable.EJBContainer; import javax.naming.Context; import org.apache.log4j.Logger; import org.lightmare.deploy.MetaCreator; import org.lightmare.jndi.JndiManager; import org.lightmare.utils.CollectionUtils; import org.lightmare.utils.ObjectUtils; /** * Implementation for {@link javax.ejb.embeddable.EJBContainer} class for * "Lightmare" EJB container * * @author levan * */ public class EJBContainerImpl extends EJBContainer { private MetaCreator creator; private static final Logger LOG = Logger.getLogger(EJBContainerImpl.class); protected EJBContainerImpl() { try { this.creator = new MetaCreator.Builder().build(); this.creator.scanForBeans(); } catch (IOException ex) { LOG.error("Could not initialize EJBContainer", ex); } } protected EJBContainerImpl(Map<?, ?> properties) { try { MetaCreator.Builder builder; if (CollectionUtils.available(properties)) { Map<Object, Object> configuration = ObjectUtils .cast(properties); builder = new MetaCreator.Builder(configuration); } else { builder = new MetaCreator.Builder(); } this.creator = builder.build(); this.creator.scanForBeans(); } catch (IOException ex) { LOG.error("Could not initialize EJBContainer", ex); } } @Override public Context getContext() { Context context = null; try { JndiManager utils = new JndiManager(); context = utils.getContext(); } catch (IOException ex) { LOG.error("Could not initialize Context", ex); } return context; } @Override public void close() { try { if (ObjectUtils.notNull(creator)) { creator.clear(); } MetaCreator.close(); } catch (IOException ex) { LOG.fatal(ex.getMessage(), ex); } } }
src/main/java/org/lightmare/ejb/embeddable/EJBContainerImpl.java
package org.lightmare.ejb.embeddable; import java.io.IOException; import java.util.Map; import javax.ejb.embeddable.EJBContainer; import javax.naming.Context; import org.apache.log4j.Logger; import org.lightmare.deploy.MetaCreator; import org.lightmare.jndi.JndiManager; import org.lightmare.utils.ObjectUtils; /** * Implementation for {@link javax.ejb.embeddable.EJBContainer} class for * "Lightmare" EJB container * * @author levan * */ public class EJBContainerImpl extends EJBContainer { private MetaCreator creator; private static final Logger LOG = Logger.getLogger(EJBContainerImpl.class); protected EJBContainerImpl() { try { this.creator = new MetaCreator.Builder().build(); this.creator.scanForBeans(); } catch (IOException ex) { LOG.error("Could not initialize EJBContainer", ex); } } protected EJBContainerImpl(Map<?, ?> properties) { try { MetaCreator.Builder builder; if (ObjectUtils.available(properties)) { Map<Object, Object> configuration = ObjectUtils .cast(properties); builder = new MetaCreator.Builder(configuration); } else { builder = new MetaCreator.Builder(); } this.creator = builder.build(); this.creator.scanForBeans(); } catch (IOException ex) { LOG.error("Could not initialize EJBContainer", ex); } } @Override public Context getContext() { Context context = null; try { JndiManager utils = new JndiManager(); context = utils.getContext(); } catch (IOException ex) { LOG.error("Could not initialize Context", ex); } return context; } @Override public void close() { try { if (ObjectUtils.notNull(creator)) { creator.clear(); } MetaCreator.close(); } catch (IOException ex) { LOG.fatal(ex.getMessage(), ex); } } }
improvements in ObjectUtils and CollectionUtils classes and all dependent classes
src/main/java/org/lightmare/ejb/embeddable/EJBContainerImpl.java
improvements in ObjectUtils and CollectionUtils classes and all dependent classes
Java
lgpl-2.1
cb941c655c00c234421e9391e878f9707353c329
0
luck3y/wildfly-core,jamezp/wildfly-core,ivassile/wildfly-core,yersan/wildfly-core,jamezp/wildfly-core,aloubyansky/wildfly-core,JiriOndrusek/wildfly-core,aloubyansky/wildfly-core,jfdenise/wildfly-core,luck3y/wildfly-core,ivassile/wildfly-core,darranl/wildfly-core,jfdenise/wildfly-core,JiriOndrusek/wildfly-core,ivassile/wildfly-core,yersan/wildfly-core,soul2zimate/wildfly-core,jamezp/wildfly-core,bstansberry/wildfly-core,aloubyansky/wildfly-core,bstansberry/wildfly-core,jfdenise/wildfly-core,bstansberry/wildfly-core,soul2zimate/wildfly-core,luck3y/wildfly-core,JiriOndrusek/wildfly-core,yersan/wildfly-core,darranl/wildfly-core,darranl/wildfly-core,soul2zimate/wildfly-core
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; 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. */ package org.jboss.as.controller; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.jboss.dmr.Property; /** * A path address for an operation. * * @author Brian Stansberry * @author <a href="mailto:[email protected]">David M. Lloyd</a> */ public class PathAddress implements Iterable<PathElement> { /** * An empty address. */ public static final PathAddress EMPTY_ADDRESS = new PathAddress(Collections.<PathElement>emptyList()); /** * Creates a PathAddress from the given ModelNode address. The given node is expected * to be an address node. * * @param node the node (cannot be {@code null}) * * @return the update identifier */ public static PathAddress pathAddress(final ModelNode node) { final Map<String, PathElement> pathMap; if (node.isDefined()) { // final List<Property> props = node.asPropertyList(); // Following bit is crap TODO; uncomment above and delete below // when bug is fixed final List<Property> props = new ArrayList<Property>(); String key = null; for (ModelNode element : node.asList()) { Property prop = null; if (element.getType() == ModelType.PROPERTY) { prop = element.asProperty(); } else if (key == null) { key = element.asString(); } else { prop = new Property(key, element); } if (prop != null) { props.add(prop); key = null; } } if (props.size() == 0) { return EMPTY_ADDRESS; } else { pathMap = new LinkedHashMap<String, PathElement>(); for (final Property prop : props) { final String name = prop.getName(); if (pathMap.put(name, new PathElement(name, prop.getValue().asString())) != null) { throw duplicateElement(name); } } } } else { return EMPTY_ADDRESS; } return new PathAddress(Collections.unmodifiableList(new ArrayList<PathElement>(pathMap.values()))); } public static PathAddress pathAddress(List<PathElement> elements) { if (elements.size() == 0) { return EMPTY_ADDRESS; } final ArrayList<PathElement> newList = new ArrayList<PathElement>(elements.size()); final Set<String> seen = new HashSet<String>(); for (PathElement element : elements) { final String name = element.getKey(); if (seen.add(name)) { newList.add(element); } else { throw duplicateElement(name); } } return new PathAddress(Collections.unmodifiableList(newList)); } public static PathAddress pathAddress(PathElement... elements) { return pathAddress(Arrays.<PathElement>asList(elements)); } private static IllegalArgumentException duplicateElement(final String name) { return new IllegalArgumentException("Duplicate path element \"" + name + "\" found"); } private final List<PathElement> pathAddressList; PathAddress(final List<PathElement> pathAddressList) { assert pathAddressList != null : "pathAddressList is null"; this.pathAddressList = pathAddressList; } /** * Gets the element at the given index. * * @param index the index * @return the element * * @throws IndexOutOfBoundsException if the index is out of range * (<tt>index &lt; 0 || index &gt;= size()</tt>) */ public PathElement getElement(int index) { final List<PathElement> list = pathAddressList; return list.get(index); } /** * Gets the last element in the address. * * @return the element, or {@code null} if {@link #size()} is zero. */ public PathElement getLastElement() { final List<PathElement> list = pathAddressList; return list.size() == 0 ? null : list.get(list.size() - 1); } /** * Get a portion of this address using segments starting at {@code start} (inclusive). * * @param start the start index * @return the partial address */ public PathAddress subAddress(int start) { final List<PathElement> list = pathAddressList; return new PathAddress(list.subList(start, list.size())); } /** * Get a portion of this address using segments between {@code start} (inclusive) and {@code end} (exclusive). * * @param start the start index * @param end the end index * @return the partial address */ public PathAddress subAddress(int start, int end) { return new PathAddress(pathAddressList.subList(start, end)); } /** * Create a new path address by appending more elements to the end of this address. * * @param additionalElements the elements to append * @return the new path address */ public PathAddress append(List<PathElement> additionalElements) { final ArrayList<PathElement> newList = new ArrayList<PathElement>(pathAddressList.size() + additionalElements.size()); newList.addAll(pathAddressList); newList.addAll(additionalElements); return pathAddress(newList); } /** * Create a new path address by appending more elements to the end of this address. * * @param additionalElements the elements to append * @return the new path address */ public PathAddress append(PathElement... additionalElements) { return append(Arrays.asList(additionalElements)); } /** * Navigate to this address in the given model node. * * @param model the model node * @param create {@code true} to create the last part of the node if it does not exist * @return the submodel * @throws NoSuchElementException if the model contains no such element */ public ModelNode navigate(ModelNode model, boolean create) throws NoSuchElementException { final Iterator<PathElement> i = pathAddressList.iterator(); while (i.hasNext()) { final PathElement element = i.next(); if (create && ! i.hasNext()) { model = model.require(element.getKey()).get(element.getValue()); } else { model = model.require(element.getKey()).require(element.getValue()); } } return model; } /** * Navigate to, and remove, this address in the given model node. * * @param model the model node * @return the submodel * @throws NoSuchElementException if the model contains no such element */ public ModelNode remove(ModelNode model) throws NoSuchElementException { final Iterator<PathElement> i = pathAddressList.iterator(); while (i.hasNext()) { final PathElement element = i.next(); if (i.hasNext()) { model = model.require(element.getKey()).require(element.getValue()); } else { final ModelNode parent = model.require(element.getKey()); // TODO: remove() model = parent.get(element.getValue()).clone(); parent.get(element.getValue()).clear(); } } return model; } /** * Convert this path address to its model node representation. * * @return the model node list of properties */ public ModelNode toModelNode() { final ModelNode node = new ModelNode().setEmptyList(); for (PathElement element : pathAddressList) { node.add(element.getKey(), element.getValue()); } return node; } /** * Get the size of this path, in elements. * * @return the size */ public int size() { return pathAddressList.size(); } /** * Iterate over the elements of this path address. * * @return the iterator */ @Override public ListIterator<PathElement> iterator() { return pathAddressList.listIterator(); } @Override public int hashCode() { return pathAddressList.hashCode(); } /** * Determine whether this object is equal to another. * * @param other the other object * @return {@code true} if they are equal, {@code false} otherwise */ @Override public boolean equals(Object other) { return other instanceof PathAddress && equals((PathAddress)other); } /** * Determine whether this object is equal to another. * * @param other the other object * @return {@code true} if they are equal, {@code false} otherwise */ public boolean equals(PathAddress other) { return this == other || other != null && pathAddressList.equals(other.pathAddressList); } @Override public String toString() { return toModelNode().toString(); } }
controller/src/main/java/org/jboss/as/controller/PathAddress.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; 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. */ package org.jboss.as.controller; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import org.jboss.dmr.ModelNode; import org.jboss.dmr.Property; /** * A path address for an operation. * * @author Brian Stansberry * @author <a href="mailto:[email protected]">David M. Lloyd</a> */ public class PathAddress implements Iterable<PathElement> { /** * An empty address. */ public static final PathAddress EMPTY_ADDRESS = new PathAddress(Collections.<PathElement>emptyList()); /** * Creates an UpdateIdentifier from the given ModelNode address. The given node is expected * to be an address node. * * @param node the node (cannot be {@code null}) * * @return the update identifier */ public static PathAddress pathAddress(final ModelNode node) { final Map<String, PathElement> pathMap; if (node.isDefined()) { final List<Property> props = node.asPropertyList(); if (props.size() == 0) { return EMPTY_ADDRESS; } else { pathMap = new LinkedHashMap<String, PathElement>(); for (final Property prop : props) { final String name = prop.getName(); if (pathMap.put(name, new PathElement(name, prop.getValue().asString())) != null) { throw duplicateElement(name); } } } } else { return EMPTY_ADDRESS; } return new PathAddress(Collections.unmodifiableList(new ArrayList<PathElement>(pathMap.values()))); } public static PathAddress pathAddress(List<PathElement> elements) { if (elements.size() == 0) { return EMPTY_ADDRESS; } final ArrayList<PathElement> newList = new ArrayList<PathElement>(elements.size()); final Set<String> seen = new HashSet<String>(); for (PathElement element : elements) { final String name = element.getKey(); if (seen.add(name)) { newList.add(element); } else { throw duplicateElement(name); } } return new PathAddress(Collections.unmodifiableList(newList)); } public static PathAddress pathAddress(PathElement... elements) { return pathAddress(Arrays.<PathElement>asList(elements)); } private static IllegalArgumentException duplicateElement(final String name) { return new IllegalArgumentException("Duplicate path element \"" + name + "\" found"); } private final List<PathElement> pathAddressList; PathAddress(final List<PathElement> pathAddressList) { assert pathAddressList != null : "pathAddressList is null"; this.pathAddressList = pathAddressList; } /** * Get a portion of this address using segments starting at {@code start} (inclusive). * * @param start the start index * @return the partial address */ public PathAddress subAddress(int start) { final List<PathElement> list = pathAddressList; return new PathAddress(list.subList(start, list.size())); } /** * Get a portion of this address using segments between {@code start} (inclusive) and {@code end} (exclusive). * * @param start the start index * @param end the end index * @return the partial address */ public PathAddress subAddress(int start, int end) { return new PathAddress(pathAddressList.subList(start, end)); } /** * Create a new path address by appending more elements to the end of this address. * * @param additionalElements the elements to append * @return the new path address */ public PathAddress append(List<PathElement> additionalElements) { final ArrayList<PathElement> newList = new ArrayList<PathElement>(pathAddressList.size() + additionalElements.size()); newList.addAll(pathAddressList); newList.addAll(additionalElements); return pathAddress(newList); } /** * Create a new path address by appending more elements to the end of this address. * * @param additionalElements the elements to append * @return the new path address */ public PathAddress append(PathElement... additionalElements) { return append(Arrays.asList(additionalElements)); } /** * Navigate to this address in the given model node. * * @param model the model node * @param create {@code true} to create the last part of the node if it does not exist * @return the submodel * @throws NoSuchElementException if the model contains no such element */ public ModelNode navigate(ModelNode model, boolean create) throws NoSuchElementException { final Iterator<PathElement> i = pathAddressList.iterator(); while (i.hasNext()) { final PathElement element = i.next(); if (create && ! i.hasNext()) { model = model.require(element.getKey()).get(element.getValue()); } else { model = model.require(element.getKey()).require(element.getValue()); } } return model; } /** * Navigate to, and remove, this address in the given model node. * * @param model the model node * @return the submodel * @throws NoSuchElementException if the model contains no such element */ public ModelNode remove(ModelNode model) throws NoSuchElementException { final Iterator<PathElement> i = pathAddressList.iterator(); while (i.hasNext()) { final PathElement element = i.next(); if (i.hasNext()) { model = model.require(element.getKey()).require(element.getValue()); } else { final ModelNode parent = model.require(element.getKey()); // TODO: remove() model = parent.get(element.getValue()).clone(); parent.get(element.getValue()).clear(); } } return model; } /** * Convert this path address to its model node representation. * * @return the model node list of properties */ public ModelNode toModelNode() { final ModelNode node = new ModelNode(); for (PathElement element : pathAddressList) { node.add(element.getKey(), element.getValue()); } return node; } /** * Get the size of this path, in elements. * * @return the size */ public int size() { return pathAddressList.size(); } /** * Iterate over the elements of this path address. * * @return the iterator */ public ListIterator<PathElement> iterator() { return pathAddressList.listIterator(); } @Override public int hashCode() { return pathAddressList.hashCode(); } /** * Determine whether this object is equal to another. * * @param other the other object * @return {@code true} if they are equal, {@code false} otherwise */ @Override public boolean equals(Object other) { return other instanceof PathAddress && equals((PathAddress)other); } /** * Determine whether this object is equal to another. * * @param other the other object * @return {@code true} if they are equal, {@code false} otherwise */ public boolean equals(PathAddress other) { return this == other || other != null && pathAddressList.equals(other.pathAddressList); } }
Work around bug in ModelNode.asPropertyList(); add a toString() was: 5596b153eec4d3be9db6f44b763260a45bd5d302
controller/src/main/java/org/jboss/as/controller/PathAddress.java
Work around bug in ModelNode.asPropertyList(); add a toString()
Java
apache-2.0
3027d453b01caeffc1bb4ec0713d91cbeeb99be5
0
mumer92/libgdx,toa5/libgdx,jsjolund/libgdx,lordjone/libgdx,tell10glu/libgdx,collinsmith/libgdx,sarkanyi/libgdx,kagehak/libgdx,yangweigbh/libgdx,revo09/libgdx,MathieuDuponchelle/gdx,anserran/libgdx,cypherdare/libgdx,Xhanim/libgdx,yangweigbh/libgdx,BlueRiverInteractive/libgdx,katiepino/libgdx,srwonka/libGdx,gf11speed/libgdx,cypherdare/libgdx,stickyd/libgdx,haedri/libgdx-1,gouessej/libgdx,ninoalma/libgdx,BlueRiverInteractive/libgdx,FredGithub/libgdx,alex-dorokhov/libgdx,PedroRomanoBarbosa/libgdx,mumer92/libgdx,ryoenji/libgdx,ricardorigodon/libgdx,jsjolund/libgdx,Deftwun/libgdx,ya7lelkom/libgdx,KrisLee/libgdx,Heart2009/libgdx,anserran/libgdx,Senth/libgdx,djom20/libgdx,GreenLightning/libgdx,TheAks999/libgdx,xpenatan/libgdx-LWJGL3,hyvas/libgdx,anserran/libgdx,sarkanyi/libgdx,alex-dorokhov/libgdx,samskivert/libgdx,Badazdz/libgdx,josephknight/libgdx,nave966/libgdx,1yvT0s/libgdx,JFixby/libgdx,nudelchef/libgdx,MikkelTAndersen/libgdx,curtiszimmerman/libgdx,toa5/libgdx,ya7lelkom/libgdx,katiepino/libgdx,hyvas/libgdx,Deftwun/libgdx,Dzamir/libgdx,yangweigbh/libgdx,309746069/libgdx,revo09/libgdx,ya7lelkom/libgdx,azakhary/libgdx,MikkelTAndersen/libgdx,Arcnor/libgdx,shiweihappy/libgdx,andyvand/libgdx,js78/libgdx,djom20/libgdx,EsikAntony/libgdx,luischavez/libgdx,flaiker/libgdx,JFixby/libgdx,jsjolund/libgdx,Deftwun/libgdx,alireza-hosseini/libgdx,Xhanim/libgdx,junkdog/libgdx,flaiker/libgdx,flaiker/libgdx,FredGithub/libgdx,JFixby/libgdx,TheAks999/libgdx,stinsonga/libgdx,tommycli/libgdx,saltares/libgdx,curtiszimmerman/libgdx,MetSystem/libgdx,EsikAntony/libgdx,flaiker/libgdx,alireza-hosseini/libgdx,tommycli/libgdx,EsikAntony/libgdx,jsjolund/libgdx,mumer92/libgdx,Zonglin-Li6565/libgdx,Xhanim/libgdx,MetSystem/libgdx,js78/libgdx,xpenatan/libgdx-LWJGL3,jberberick/libgdx,katiepino/libgdx,Gliby/libgdx,jberberick/libgdx,jberberick/libgdx,basherone/libgdxcn,azakhary/libgdx,nooone/libgdx,UnluckyNinja/libgdx,TheAks999/libgdx,FredGithub/libgdx,xpenatan/libgdx-LWJGL3,1yvT0s/libgdx,fwolff/libgdx,xoppa/libgdx,tommycli/libgdx,davebaol/libgdx,1yvT0s/libgdx,samskivert/libgdx,petugez/libgdx,copystudy/libgdx,designcrumble/libgdx,JFixby/libgdx,tommyettinger/libgdx,nelsonsilva/libgdx,PedroRomanoBarbosa/libgdx,samskivert/libgdx,nave966/libgdx,ztv/libgdx,revo09/libgdx,saltares/libgdx,nudelchef/libgdx,xranby/libgdx,MathieuDuponchelle/gdx,gouessej/libgdx,codepoke/libgdx,thepullman/libgdx,Heart2009/libgdx,srwonka/libGdx,ThiagoGarciaAlves/libgdx,EsikAntony/libgdx,gdos/libgdx,ttencate/libgdx,titovmaxim/libgdx,firefly2442/libgdx,saqsun/libgdx,JDReutt/libgdx,gf11speed/libgdx,UnluckyNinja/libgdx,revo09/libgdx,jsjolund/libgdx,toloudis/libgdx,titovmaxim/libgdx,bladecoder/libgdx,fwolff/libgdx,alex-dorokhov/libgdx,ztv/libgdx,nelsonsilva/libgdx,TheAks999/libgdx,kzganesan/libgdx,firefly2442/libgdx,anserran/libgdx,copystudy/libgdx,Badazdz/libgdx,ricardorigodon/libgdx,shiweihappy/libgdx,zommuter/libgdx,toa5/libgdx,lordjone/libgdx,petugez/libgdx,PedroRomanoBarbosa/libgdx,nrallakis/libgdx,sjosegarcia/libgdx,FredGithub/libgdx,ttencate/libgdx,snovak/libgdx,Deftwun/libgdx,yangweigbh/libgdx,saltares/libgdx,noelsison2/libgdx,toloudis/libgdx,jasonwee/libgdx,youprofit/libgdx,FyiurAmron/libgdx,basherone/libgdxcn,kagehak/libgdx,kagehak/libgdx,stinsonga/libgdx,hyvas/libgdx,gdos/libgdx,josephknight/libgdx,UnluckyNinja/libgdx,Gliby/libgdx,realitix/libgdx,Wisienkas/libgdx,ztv/libgdx,jasonwee/libgdx,libgdx/libgdx,MadcowD/libgdx,GreenLightning/libgdx,ThiagoGarciaAlves/libgdx,309746069/libgdx,snovak/libgdx,nave966/libgdx,ninoalma/libgdx,bgroenks96/libgdx,jberberick/libgdx,PedroRomanoBarbosa/libgdx,tell10glu/libgdx,toloudis/libgdx,ThiagoGarciaAlves/libgdx,Senth/libgdx,firefly2442/libgdx,toa5/libgdx,nudelchef/libgdx,ya7lelkom/libgdx,fiesensee/libgdx,sinistersnare/libgdx,Zonglin-Li6565/libgdx,fwolff/libgdx,stickyd/libgdx,basherone/libgdxcn,kotcrab/libgdx,sarkanyi/libgdx,Deftwun/libgdx,Gliby/libgdx,Thotep/libgdx,JFixby/libgdx,collinsmith/libgdx,Wisienkas/libgdx,czyzby/libgdx,NathanSweet/libgdx,ryoenji/libgdx,xoppa/libgdx,nooone/libgdx,bsmr-java/libgdx,saltares/libgdx,luischavez/libgdx,nooone/libgdx,lordjone/libgdx,gf11speed/libgdx,GreenLightning/libgdx,nudelchef/libgdx,Badazdz/libgdx,1yvT0s/libgdx,nave966/libgdx,sjosegarcia/libgdx,Heart2009/libgdx,del-sol/libgdx,sarkanyi/libgdx,libgdx/libgdx,toloudis/libgdx,yangweigbh/libgdx,djom20/libgdx,toloudis/libgdx,andyvand/libgdx,Senth/libgdx,EsikAntony/libgdx,ricardorigodon/libgdx,js78/libgdx,SidneyXu/libgdx,ya7lelkom/libgdx,bsmr-java/libgdx,sjosegarcia/libgdx,Heart2009/libgdx,titovmaxim/libgdx,SidneyXu/libgdx,shiweihappy/libgdx,TheAks999/libgdx,309746069/libgdx,TheAks999/libgdx,tommyettinger/libgdx,shiweihappy/libgdx,KrisLee/libgdx,katiepino/libgdx,309746069/libgdx,collinsmith/libgdx,designcrumble/libgdx,bsmr-java/libgdx,noelsison2/libgdx,MovingBlocks/libgdx,sinistersnare/libgdx,kagehak/libgdx,azakhary/libgdx,Dzamir/libgdx,zommuter/libgdx,josephknight/libgdx,nave966/libgdx,revo09/libgdx,ya7lelkom/libgdx,xoppa/libgdx,SidneyXu/libgdx,Deftwun/libgdx,davebaol/libgdx,hyvas/libgdx,stinsonga/libgdx,zhimaijoy/libgdx,NathanSweet/libgdx,KrisLee/libgdx,codepoke/libgdx,del-sol/libgdx,KrisLee/libgdx,youprofit/libgdx,xoppa/libgdx,KrisLee/libgdx,youprofit/libgdx,bladecoder/libgdx,ztv/libgdx,luischavez/libgdx,Zomby2D/libgdx,Gliby/libgdx,fiesensee/libgdx,andyvand/libgdx,yangweigbh/libgdx,Zomby2D/libgdx,MetSystem/libgdx,nudelchef/libgdx,gdos/libgdx,Badazdz/libgdx,gf11speed/libgdx,petugez/libgdx,MikkelTAndersen/libgdx,czyzby/libgdx,kagehak/libgdx,realitix/libgdx,bgroenks96/libgdx,antag99/libgdx,thepullman/libgdx,jasonwee/libgdx,Xhanim/libgdx,ya7lelkom/libgdx,sjosegarcia/libgdx,xranby/libgdx,hyvas/libgdx,1yvT0s/libgdx,FyiurAmron/libgdx,JFixby/libgdx,MikkelTAndersen/libgdx,sarkanyi/libgdx,Zonglin-Li6565/libgdx,nudelchef/libgdx,FredGithub/libgdx,309746069/libgdx,saqsun/libgdx,firefly2442/libgdx,snovak/libgdx,Thotep/libgdx,js78/libgdx,gouessej/libgdx,MathieuDuponchelle/gdx,MadcowD/libgdx,saltares/libgdx,antag99/libgdx,srwonka/libGdx,basherone/libgdxcn,fwolff/libgdx,ricardorigodon/libgdx,codepoke/libgdx,tell10glu/libgdx,nelsonsilva/libgdx,stickyd/libgdx,JFixby/libgdx,designcrumble/libgdx,ttencate/libgdx,tommycli/libgdx,nelsonsilva/libgdx,xoppa/libgdx,andyvand/libgdx,ThiagoGarciaAlves/libgdx,srwonka/libGdx,toloudis/libgdx,flaiker/libgdx,Arcnor/libgdx,Zonglin-Li6565/libgdx,bgroenks96/libgdx,bsmr-java/libgdx,srwonka/libGdx,thepullman/libgdx,mumer92/libgdx,PedroRomanoBarbosa/libgdx,ztv/libgdx,gf11speed/libgdx,Thotep/libgdx,libgdx/libgdx,ttencate/libgdx,tommyettinger/libgdx,MetSystem/libgdx,sinistersnare/libgdx,Wisienkas/libgdx,kagehak/libgdx,jsjolund/libgdx,curtiszimmerman/libgdx,stickyd/libgdx,GreenLightning/libgdx,junkdog/libgdx,hyvas/libgdx,luischavez/libgdx,Wisienkas/libgdx,tell10glu/libgdx,MovingBlocks/libgdx,ricardorigodon/libgdx,gouessej/libgdx,MetSystem/libgdx,del-sol/libgdx,czyzby/libgdx,del-sol/libgdx,Wisienkas/libgdx,saltares/libgdx,MadcowD/libgdx,nelsonsilva/libgdx,zhimaijoy/libgdx,revo09/libgdx,billgame/libgdx,KrisLee/libgdx,petugez/libgdx,antag99/libgdx,youprofit/libgdx,stickyd/libgdx,titovmaxim/libgdx,gdos/libgdx,UnluckyNinja/libgdx,luischavez/libgdx,luischavez/libgdx,czyzby/libgdx,noelsison2/libgdx,kagehak/libgdx,jasonwee/libgdx,Wisienkas/libgdx,ricardorigodon/libgdx,kotcrab/libgdx,NathanSweet/libgdx,zommuter/libgdx,JDReutt/libgdx,UnluckyNinja/libgdx,kzganesan/libgdx,ttencate/libgdx,noelsison2/libgdx,junkdog/libgdx,FyiurAmron/libgdx,FredGithub/libgdx,FyiurAmron/libgdx,EsikAntony/libgdx,samskivert/libgdx,junkdog/libgdx,saltares/libgdx,FyiurAmron/libgdx,youprofit/libgdx,gdos/libgdx,ThiagoGarciaAlves/libgdx,Gliby/libgdx,czyzby/libgdx,ninoalma/libgdx,snovak/libgdx,MovingBlocks/libgdx,jberberick/libgdx,junkdog/libgdx,ThiagoGarciaAlves/libgdx,Xhanim/libgdx,PedroRomanoBarbosa/libgdx,bsmr-java/libgdx,snovak/libgdx,xoppa/libgdx,youprofit/libgdx,MovingBlocks/libgdx,bgroenks96/libgdx,lordjone/libgdx,ninoalma/libgdx,alex-dorokhov/libgdx,UnluckyNinja/libgdx,alireza-hosseini/libgdx,saqsun/libgdx,lordjone/libgdx,MadcowD/libgdx,xpenatan/libgdx-LWJGL3,kotcrab/libgdx,andyvand/libgdx,saqsun/libgdx,SidneyXu/libgdx,BlueRiverInteractive/libgdx,MathieuDuponchelle/gdx,toloudis/libgdx,ryoenji/libgdx,alireza-hosseini/libgdx,firefly2442/libgdx,Gliby/libgdx,fwolff/libgdx,billgame/libgdx,cypherdare/libgdx,nrallakis/libgdx,kotcrab/libgdx,Dzamir/libgdx,MathieuDuponchelle/gdx,alireza-hosseini/libgdx,Arcnor/libgdx,jsjolund/libgdx,nrallakis/libgdx,MathieuDuponchelle/gdx,xpenatan/libgdx-LWJGL3,MathieuDuponchelle/gdx,jasonwee/libgdx,davebaol/libgdx,alex-dorokhov/libgdx,petugez/libgdx,mumer92/libgdx,ztv/libgdx,xranby/libgdx,josephknight/libgdx,designcrumble/libgdx,katiepino/libgdx,noelsison2/libgdx,sarkanyi/libgdx,codepoke/libgdx,Zonglin-Li6565/libgdx,xranby/libgdx,codepoke/libgdx,anserran/libgdx,Deftwun/libgdx,MikkelTAndersen/libgdx,stinsonga/libgdx,Senth/libgdx,KrisLee/libgdx,ya7lelkom/libgdx,TheAks999/libgdx,jasonwee/libgdx,JDReutt/libgdx,MathieuDuponchelle/gdx,djom20/libgdx,designcrumble/libgdx,billgame/libgdx,sjosegarcia/libgdx,ThiagoGarciaAlves/libgdx,FyiurAmron/libgdx,TheAks999/libgdx,srwonka/libGdx,snovak/libgdx,Zomby2D/libgdx,realitix/libgdx,junkdog/libgdx,shiweihappy/libgdx,KrisLee/libgdx,zhimaijoy/libgdx,tommycli/libgdx,saqsun/libgdx,copystudy/libgdx,shiweihappy/libgdx,js78/libgdx,josephknight/libgdx,Thotep/libgdx,anserran/libgdx,revo09/libgdx,toa5/libgdx,kzganesan/libgdx,zhimaijoy/libgdx,MathieuDuponchelle/gdx,SidneyXu/libgdx,ricardorigodon/libgdx,collinsmith/libgdx,ninoalma/libgdx,EsikAntony/libgdx,MadcowD/libgdx,tommycli/libgdx,katiepino/libgdx,lordjone/libgdx,firefly2442/libgdx,lordjone/libgdx,Thotep/libgdx,gf11speed/libgdx,alireza-hosseini/libgdx,hyvas/libgdx,fiesensee/libgdx,PedroRomanoBarbosa/libgdx,realitix/libgdx,ttencate/libgdx,jsjolund/libgdx,sjosegarcia/libgdx,josephknight/libgdx,Arcnor/libgdx,MetSystem/libgdx,Thotep/libgdx,youprofit/libgdx,stickyd/libgdx,codepoke/libgdx,katiepino/libgdx,samskivert/libgdx,Gliby/libgdx,czyzby/libgdx,1yvT0s/libgdx,tommyettinger/libgdx,codepoke/libgdx,shiweihappy/libgdx,Dzamir/libgdx,toa5/libgdx,del-sol/libgdx,sjosegarcia/libgdx,1yvT0s/libgdx,Xhanim/libgdx,PedroRomanoBarbosa/libgdx,josephknight/libgdx,xranby/libgdx,luischavez/libgdx,junkdog/libgdx,toa5/libgdx,samskivert/libgdx,fiesensee/libgdx,ttencate/libgdx,petugez/libgdx,bladecoder/libgdx,Senth/libgdx,SidneyXu/libgdx,nooone/libgdx,xranby/libgdx,saltares/libgdx,JDReutt/libgdx,MetSystem/libgdx,andyvand/libgdx,xranby/libgdx,jberberick/libgdx,titovmaxim/libgdx,Badazdz/libgdx,nudelchef/libgdx,309746069/libgdx,ztv/libgdx,JDReutt/libgdx,davebaol/libgdx,tommycli/libgdx,gf11speed/libgdx,Zomby2D/libgdx,thepullman/libgdx,libgdx/libgdx,jberberick/libgdx,lordjone/libgdx,zhimaijoy/libgdx,fiesensee/libgdx,kotcrab/libgdx,antag99/libgdx,alex-dorokhov/libgdx,azakhary/libgdx,libgdx/libgdx,mumer92/libgdx,Heart2009/libgdx,haedri/libgdx-1,nrallakis/libgdx,ninoalma/libgdx,Dzamir/libgdx,titovmaxim/libgdx,Arcnor/libgdx,kzganesan/libgdx,sarkanyi/libgdx,Badazdz/libgdx,Heart2009/libgdx,revo09/libgdx,curtiszimmerman/libgdx,firefly2442/libgdx,xpenatan/libgdx-LWJGL3,ryoenji/libgdx,copystudy/libgdx,billgame/libgdx,saqsun/libgdx,thepullman/libgdx,stickyd/libgdx,FredGithub/libgdx,MikkelTAndersen/libgdx,Badazdz/libgdx,snovak/libgdx,yangweigbh/libgdx,Arcnor/libgdx,xoppa/libgdx,bladecoder/libgdx,nudelchef/libgdx,gouessej/libgdx,zommuter/libgdx,titovmaxim/libgdx,Senth/libgdx,realitix/libgdx,sinistersnare/libgdx,NathanSweet/libgdx,fiesensee/libgdx,BlueRiverInteractive/libgdx,thepullman/libgdx,Senth/libgdx,BlueRiverInteractive/libgdx,cypherdare/libgdx,bladecoder/libgdx,Wisienkas/libgdx,Dzamir/libgdx,GreenLightning/libgdx,samskivert/libgdx,codepoke/libgdx,MetSystem/libgdx,billgame/libgdx,bgroenks96/libgdx,js78/libgdx,ninoalma/libgdx,MovingBlocks/libgdx,junkdog/libgdx,petugez/libgdx,Dzamir/libgdx,noelsison2/libgdx,antag99/libgdx,bsmr-java/libgdx,curtiszimmerman/libgdx,gdos/libgdx,mumer92/libgdx,nave966/libgdx,MadcowD/libgdx,firefly2442/libgdx,Xhanim/libgdx,zommuter/libgdx,Badazdz/libgdx,billgame/libgdx,nelsonsilva/libgdx,xranby/libgdx,haedri/libgdx-1,jasonwee/libgdx,MadcowD/libgdx,saqsun/libgdx,alireza-hosseini/libgdx,designcrumble/libgdx,MadcowD/libgdx,GreenLightning/libgdx,flaiker/libgdx,basherone/libgdxcn,anserran/libgdx,JDReutt/libgdx,noelsison2/libgdx,gdos/libgdx,fwolff/libgdx,Zonglin-Li6565/libgdx,fwolff/libgdx,sinistersnare/libgdx,Senth/libgdx,Heart2009/libgdx,andyvand/libgdx,ttencate/libgdx,kotcrab/libgdx,tommyettinger/libgdx,GreenLightning/libgdx,fwolff/libgdx,czyzby/libgdx,ThiagoGarciaAlves/libgdx,Wisienkas/libgdx,haedri/libgdx-1,antag99/libgdx,toa5/libgdx,noelsison2/libgdx,bgroenks96/libgdx,samskivert/libgdx,snovak/libgdx,fiesensee/libgdx,stickyd/libgdx,alex-dorokhov/libgdx,bgroenks96/libgdx,basherone/libgdxcn,1yvT0s/libgdx,Zomby2D/libgdx,Zonglin-Li6565/libgdx,309746069/libgdx,collinsmith/libgdx,gouessej/libgdx,stinsonga/libgdx,realitix/libgdx,designcrumble/libgdx,Thotep/libgdx,JDReutt/libgdx,toloudis/libgdx,bgroenks96/libgdx,nrallakis/libgdx,tell10glu/libgdx,haedri/libgdx-1,nrallakis/libgdx,antag99/libgdx,copystudy/libgdx,alex-dorokhov/libgdx,djom20/libgdx,fiesensee/libgdx,del-sol/libgdx,Deftwun/libgdx,titovmaxim/libgdx,jasonwee/libgdx,ztv/libgdx,Gliby/libgdx,MovingBlocks/libgdx,gf11speed/libgdx,nave966/libgdx,EsikAntony/libgdx,js78/libgdx,Thotep/libgdx,Xhanim/libgdx,collinsmith/libgdx,nooone/libgdx,djom20/libgdx,cypherdare/libgdx,nrallakis/libgdx,Heart2009/libgdx,realitix/libgdx,tell10glu/libgdx,sjosegarcia/libgdx,ricardorigodon/libgdx,tommycli/libgdx,NathanSweet/libgdx,copystudy/libgdx,zommuter/libgdx,del-sol/libgdx,JFixby/libgdx,curtiszimmerman/libgdx,UnluckyNinja/libgdx,tell10glu/libgdx,BlueRiverInteractive/libgdx,nrallakis/libgdx,ninoalma/libgdx,davebaol/libgdx,MikkelTAndersen/libgdx,shiweihappy/libgdx,designcrumble/libgdx,gouessej/libgdx,xoppa/libgdx,curtiszimmerman/libgdx,ryoenji/libgdx,kagehak/libgdx,antag99/libgdx,yangweigbh/libgdx,kotcrab/libgdx,BlueRiverInteractive/libgdx,copystudy/libgdx,billgame/libgdx,kotcrab/libgdx,alireza-hosseini/libgdx,FredGithub/libgdx,MovingBlocks/libgdx,curtiszimmerman/libgdx,ryoenji/libgdx,realitix/libgdx,jberberick/libgdx,kzganesan/libgdx,ryoenji/libgdx,GreenLightning/libgdx,srwonka/libGdx,zhimaijoy/libgdx,collinsmith/libgdx,bsmr-java/libgdx,katiepino/libgdx,saqsun/libgdx,zommuter/libgdx,mumer92/libgdx,azakhary/libgdx,srwonka/libGdx,xpenatan/libgdx-LWJGL3,gdos/libgdx,kzganesan/libgdx,sarkanyi/libgdx,petugez/libgdx,nave966/libgdx,MikkelTAndersen/libgdx,zhimaijoy/libgdx,Dzamir/libgdx,del-sol/libgdx,FyiurAmron/libgdx,haedri/libgdx-1,copystudy/libgdx,tell10glu/libgdx,anserran/libgdx,zhimaijoy/libgdx,FyiurAmron/libgdx,UnluckyNinja/libgdx,SidneyXu/libgdx,zommuter/libgdx,js78/libgdx,sinistersnare/libgdx,czyzby/libgdx,djom20/libgdx,gouessej/libgdx,billgame/libgdx,andyvand/libgdx,collinsmith/libgdx,thepullman/libgdx,flaiker/libgdx,djom20/libgdx,kzganesan/libgdx,davebaol/libgdx,hyvas/libgdx,bsmr-java/libgdx,josephknight/libgdx,xpenatan/libgdx-LWJGL3,309746069/libgdx,haedri/libgdx-1,flaiker/libgdx,luischavez/libgdx,thepullman/libgdx,Zonglin-Li6565/libgdx,youprofit/libgdx,nooone/libgdx,MovingBlocks/libgdx,JDReutt/libgdx,SidneyXu/libgdx,haedri/libgdx-1,BlueRiverInteractive/libgdx,azakhary/libgdx
package com.badlogic.gdx.graphics.g3d; import com.badlogic.gdx.graphics.g3d.materials.Material; import com.badlogic.gdx.graphics.g3d.model.Animation; import com.badlogic.gdx.graphics.g3d.model.MeshPart; import com.badlogic.gdx.graphics.g3d.model.MeshPartMaterial; import com.badlogic.gdx.graphics.g3d.model.Node; import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.Disposable; import com.badlogic.gdx.utils.GdxRuntimeException; import com.badlogic.gdx.utils.Pool; /** * An instance of a {@link Model}, allows to specify global transform and modify the materials, as it * has a copy of the model's materials. Multiple instances can be created from the same Model, * all sharing the meshes and textures of the Model. The Model owns the meshes and textures, to * dispose of these, the Model has to be disposed.</p> * * The ModelInstance creates a full copy of all materials and nodes. * @author badlogic * */ public class ModelInstance implements RenderableProvider { /** the {@link Model} this instances derives from **/ public final Model model; /** the world transform **/ public final Matrix4 transform = new Matrix4(); /** a copy of the materials of the original model **/ public final Array<Material> materials = new Array<Material>(); /** a copy of the nodes of the original model, referencing the copied materials in their {@link MeshPartMaterial} instances **/ public final Array<Node> nodes = new Array<Node>(); /** a copy of the animations of the original model **/ public final Array<Animation> animations = new Array<Animation>(); /** Constructs a new ModelInstance with all nodes and materials of the given model. */ public ModelInstance(Model model) { this(model, (String[])null); } /** Constructs a new ModelInstance with only the specified nodes and materials of the given model. */ public ModelInstance(Model model, final String... rootNodeIds) { this.model = model; if (rootNodeIds == null) copyNodes(model.nodes); else copyNodes(model.nodes, rootNodeIds); calculateTransforms(); } /** Constructs a new ModelInstance with only the specified nodes and materials of the given model. */ public ModelInstance(Model model, final Array<String> rootNodeIds) { this.model = model; copyNodes(model.nodes, rootNodeIds); calculateTransforms(); } /** Constructs a new ModelInstance at the specified position. */ public ModelInstance(Model model, Vector3 position) { this(model); this.transform.setToTranslation(position); } /** Constructs a new ModelInstance at the specified position. */ public ModelInstance(Model model, float x, float y, float z) { this(model); this.transform.setToTranslation(x, y, z); } /** Constructs a new ModelInstance with the specified transform. */ public ModelInstance(Model model, Matrix4 transform) { this(model); this.transform.set(transform); } /** Constructs a new ModelInstance which is an copy of the specified ModelInstance. */ public ModelInstance(ModelInstance copyFrom) { this(copyFrom, copyFrom.transform); } /** Constructs a new ModelInstance which is an copy of the specified ModelInstance. */ public ModelInstance(ModelInstance copyFrom, final Matrix4 transform) { this.model = copyFrom.model; if (transform != null) this.transform.set(transform); copyNodes(copyFrom.nodes); calculateTransforms(); } /** @return A newly created ModelInstance which is a copy of this ModelInstance */ public ModelInstance copy() { return new ModelInstance(this); } private void copyNodes (Array<Node> nodes) { for(Node node: nodes) { this.nodes.add(copyNode(null, node)); } } private void copyNodes (Array<Node> nodes, final String... nodeIds) { for(Node node: nodes) { for (final String nodeId : nodeIds) { if (nodeId.equals(node.id)) { this.nodes.add(copyNode(null, node)); break; } } } } private void copyNodes (Array<Node> nodes, final Array<String> nodeIds) { for(Node node: nodes) { for (final String nodeId : nodeIds) { if (nodeId.equals(node.id)) { this.nodes.add(copyNode(null, node)); break; } } } } private Node copyNode(Node parent, Node node) { Node copy = new Node(); copy.id = node.id; copy.boneId = node.boneId; copy.parent = parent; copy.translation.set(node.translation); copy.rotation.set(node.rotation); copy.scale.set(node.scale); copy.localTransform.set(node.localTransform); copy.worldTransform.set(node.worldTransform); for(MeshPartMaterial meshPart: node.meshPartMaterials) { copy.meshPartMaterials.add(copyMeshPart(meshPart)); } for(Node child: node.children) { copy.children.add(copyNode(copy, child)); } return copy; } private MeshPartMaterial copyMeshPart (MeshPartMaterial meshPart) { MeshPartMaterial copy = new MeshPartMaterial(); copy.meshPart = new MeshPart(); copy.meshPart.id = meshPart.meshPart.id; copy.meshPart.indexOffset = meshPart.meshPart.indexOffset; copy.meshPart.numVertices = meshPart.meshPart.numVertices; copy.meshPart.primitiveType = meshPart.meshPart.primitiveType; copy.meshPart.mesh = meshPart.meshPart.mesh; final int index = materials.indexOf(meshPart.material, false); if (index < 0) materials.add(copy.material = meshPart.material.copy()); else copy.material = materials.get(index); return copy; } /** * Calculates the local and world transform of all {@link Node} instances in this model, recursively. * First each {@link Node#localTransform} transform is calculated based on the translation, rotation and * scale of each Node. Then each {@link Node#calculateWorldTransform()} * is calculated, based on the parent's world transform and the local transform of each Node.</p> * * This method can be used to recalculate all transforms if any of the Node's local properties (translation, rotation, scale) * was modified. */ public void calculateTransforms() { for(Node node: nodes) { node.calculateTransforms(true); } } /** * Traverses the Node hierarchy and collects {@link Renderable} instances for every * node with a graphical representation. Renderables are obtained from the provided * pool. The resulting array can be rendered via a {@link ModelBatch}. * * @param renderables the output array * @param pool the pool to obtain Renderables from */ public void getRenderables(Array<Renderable> renderables, Pool<Renderable> pool) { for(Node node: nodes) { getRenderables(node, renderables, pool); } } private void getRenderables(Node node, Array<Renderable> renderables, Pool<Renderable> pool) { if(node.meshPartMaterials.size > 0) { for(MeshPartMaterial meshPart: node.meshPartMaterials) { Renderable renderable = pool.obtain(); renderable.material = meshPart.material; renderable.mesh = meshPart.meshPart.mesh; renderable.meshPartOffset = meshPart.meshPart.indexOffset; renderable.meshPartSize = meshPart.meshPart.numVertices; renderable.primitiveType = meshPart.meshPart.primitiveType; renderable.transform.set(transform).mul(node.worldTransform); renderables.add(renderable); } } for(Node child: node.children) { getRenderables(child, renderables, pool); } } }
gdx/src/com/badlogic/gdx/graphics/g3d/ModelInstance.java
package com.badlogic.gdx.graphics.g3d; import com.badlogic.gdx.graphics.g3d.materials.Material; import com.badlogic.gdx.graphics.g3d.model.Animation; import com.badlogic.gdx.graphics.g3d.model.MeshPart; import com.badlogic.gdx.graphics.g3d.model.MeshPartMaterial; import com.badlogic.gdx.graphics.g3d.model.Node; import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.Disposable; import com.badlogic.gdx.utils.GdxRuntimeException; import com.badlogic.gdx.utils.Pool; /** * An instance of a {@link Model}, allows to specify global transform and modify the materials, as it * has a copy of the model's materials. Multiple instances can be created from the same Model, * all sharing the meshes and textures of the Model. The Model owns the meshes and textures, to * dispose of these, the Model has to be disposed.</p> * * The ModelInstance creates a full copy of all materials and nodes. * @author badlogic * */ public class ModelInstance implements RenderableProvider { /** the {@link Model} this instances derives from **/ public final Model model; /** the world transform **/ public final Matrix4 transform = new Matrix4(); /** a copy of the materials of the original model **/ public final Array<Material> materials = new Array<Material>(); /** a copy of the nodes of the original model, referencing the copied materials in their {@link MeshPartMaterial} instances **/ public final Array<Node> nodes = new Array<Node>(); /** a copy of the animations of the original model **/ public final Array<Animation> animations = new Array<Animation>(); /** Constructs a new ModelInstance with all nodes and materials of the given model. */ public ModelInstance(Model model) { this(model, (String[])null); } /** Constructs a new ModelInstance with only the specified nodes and materials of the given model. */ public ModelInstance(Model model, final String... rootNodeIds) { this.model = model; if (rootNodeIds == null) copyNodes(model.nodes); else copyNodes(model.nodes, rootNodeIds); calculateTransforms(); } /** Constructs a new ModelInstance with only the specified nodes and materials of the given model. */ public ModelInstance(Model model, final Array<String> rootNodeIds) { this.model = model; copyNodes(model.nodes, rootNodeIds); calculateTransforms(); } /** Constructs a new ModelInstance at the specified position. */ public ModelInstance(Model model, Vector3 position) { this(model); this.transform.setToTranslation(position); } /** Constructs a new ModelInstance at the specified position. */ public ModelInstance(Model model, float x, float y, float z) { this(model); this.transform.setToTranslation(x, y, z); } /** Constructs a new ModelInstance with the specified transform. */ public ModelInstance(Model model, Matrix4 transform) { this(model); this.transform.set(transform); } /** Constructs a new ModelInstance which is an copy of the specified ModelInstance. */ public ModelInstance(ModelInstance copyFrom) { this(copyFrom, null); } /** Constructs a new ModelInstance which is an copy of the specified ModelInstance. */ public ModelInstance(ModelInstance copyFrom, Matrix4 transform) { this.model = copyFrom.model; this.transform.set(transform == null ? copyFrom.transform: transform); copyNodes(copyFrom.nodes); calculateTransforms(); } /** @return A newly created ModelInstance which is a copy of this ModelInstance */ public ModelInstance copy() { return new ModelInstance(this); } private void copyNodes (Array<Node> nodes) { for(Node node: nodes) { this.nodes.add(copyNode(null, node)); } } private void copyNodes (Array<Node> nodes, final String... nodeIds) { for(Node node: nodes) { for (final String nodeId : nodeIds) { if (nodeId.equals(node.id)) { this.nodes.add(copyNode(null, node)); break; } } } } private void copyNodes (Array<Node> nodes, final Array<String> nodeIds) { for(Node node: nodes) { for (final String nodeId : nodeIds) { if (nodeId.equals(node.id)) { this.nodes.add(copyNode(null, node)); break; } } } } private Node copyNode(Node parent, Node node) { Node copy = new Node(); copy.id = node.id; copy.boneId = node.boneId; copy.parent = parent; copy.translation.set(node.translation); copy.rotation.set(node.rotation); copy.scale.set(node.scale); copy.localTransform.set(node.localTransform); copy.worldTransform.set(node.worldTransform); for(MeshPartMaterial meshPart: node.meshPartMaterials) { copy.meshPartMaterials.add(copyMeshPart(meshPart)); } for(Node child: node.children) { copy.children.add(copyNode(copy, child)); } return copy; } private MeshPartMaterial copyMeshPart (MeshPartMaterial meshPart) { MeshPartMaterial copy = new MeshPartMaterial(); copy.meshPart = new MeshPart(); copy.meshPart.id = meshPart.meshPart.id; copy.meshPart.indexOffset = meshPart.meshPart.indexOffset; copy.meshPart.numVertices = meshPart.meshPart.numVertices; copy.meshPart.primitiveType = meshPart.meshPart.primitiveType; copy.meshPart.mesh = meshPart.meshPart.mesh; final int index = materials.indexOf(meshPart.material, false); if (index < 0) materials.add(copy.material = meshPart.material.copy()); else copy.material = materials.get(index); return copy; } /** * Calculates the local and world transform of all {@link Node} instances in this model, recursively. * First each {@link Node#localTransform} transform is calculated based on the translation, rotation and * scale of each Node. Then each {@link Node#calculateWorldTransform()} * is calculated, based on the parent's world transform and the local transform of each Node.</p> * * This method can be used to recalculate all transforms if any of the Node's local properties (translation, rotation, scale) * was modified. */ public void calculateTransforms() { for(Node node: nodes) { node.calculateTransforms(true); } } /** * Traverses the Node hierarchy and collects {@link Renderable} instances for every * node with a graphical representation. Renderables are obtained from the provided * pool. The resulting array can be rendered via a {@link ModelBatch}. * * @param renderables the output array * @param pool the pool to obtain Renderables from */ public void getRenderables(Array<Renderable> renderables, Pool<Renderable> pool) { for(Node node: nodes) { getRenderables(node, renderables, pool); } } private void getRenderables(Node node, Array<Renderable> renderables, Pool<Renderable> pool) { if(node.meshPartMaterials.size > 0) { for(MeshPartMaterial meshPart: node.meshPartMaterials) { Renderable renderable = pool.obtain(); renderable.material = meshPart.material; renderable.mesh = meshPart.meshPart.mesh; renderable.meshPartOffset = meshPart.meshPart.indexOffset; renderable.meshPartSize = meshPart.meshPart.numVertices; renderable.primitiveType = meshPart.meshPart.primitiveType; renderable.transform.set(transform).mul(node.worldTransform); renderables.add(renderable); } } for(Node child: node.children) { getRenderables(child, renderables, pool); } } }
ModelInstance: only set transform if it's not null
gdx/src/com/badlogic/gdx/graphics/g3d/ModelInstance.java
ModelInstance: only set transform if it's not null
Java
apache-2.0
2ab53547e0b7e2f4a4bbb7aa09631e94d730b325
0
bozimmerman/CoffeeMud,bozimmerman/CoffeeMud,bozimmerman/CoffeeMud,bozimmerman/CoffeeMud
package com.planet_ink.coffee_mud.Areas; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.Area.CompleteRoomEnumerator; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.TimeClock.TimePeriod; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.Basic.StdItem; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Libraries.interfaces.GenericBuilder; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.util.*; /* Copyright 2002-2019 Bo Zimmerman Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ public class StdArea implements Area { @Override public String ID() { return "StdArea"; } protected String name = "the area"; protected String description = ""; protected String miscText = ""; protected String archPath = ""; protected String imageName = ""; protected int playerLevel = 0; protected int theme = Area.THEME_INHERIT; protected int atmosphere = Room.ATMOSPHERE_INHERIT; protected int derivedTheme = Area.THEME_INHERIT; protected int derivedAtmo = Places.ATMOSPHERE_INHERIT; protected int climask = Area.CLIMASK_NORMAL; protected int derivedClimate = Places.CLIMASK_INHERIT; protected int tickStatus = Tickable.STATUS_NOT; protected long expirationDate = 0; protected long passiveLapseMs = DEFAULT_TIME_PASSIVE_LAPSE; protected long lastPlayerTime = System.currentTimeMillis() + (passiveLapseMs - 30000); protected State flag = State.ACTIVE; protected String[] xtraValues = null; protected String author = ""; protected String currency = ""; protected double[] devalueRate = null; protected String budget = ""; protected String ignoreMask = ""; protected String prejudiceFactors= ""; protected int invResetRate = 0; protected boolean amDestroyed = false; protected PhyStats phyStats = (PhyStats)CMClass.getCommon("DefaultPhyStats"); protected PhyStats basePhyStats = (PhyStats)CMClass.getCommon("DefaultPhyStats"); protected STreeMap<String,String> blurbFlags = new STreeMap<String,String>(); protected STreeMap<String, Room> properRooms = new STreeMap<String, Room>(new RoomIDComparator()); protected RoomnumberSet properRoomIDSet= null; protected RoomnumberSet metroRoomIDSet = null; protected SLinkedList<Area> children = new SLinkedList<Area>(); protected SLinkedList<Area> parents = new SLinkedList<Area>(); protected SVector<Ability> affects = new SVector<Ability>(1); protected SVector<Behavior> behaviors = new SVector<Behavior>(1); protected SVector<String> subOps = new SVector<String>(1); protected SVector<ScriptingEngine>scripts = new SVector<ScriptingEngine>(1); protected Area me = this; protected TimeClock myClock = null; protected Climate climateObj = (Climate)CMClass.getCommon("DefaultClimate"); protected String[] itemPricingAdjustments = new String[0]; protected final static int[] emptyStats = new int[Area.Stats.values().length]; protected final static String[] empty = new String[0]; protected static volatile Area lastComplainer = null; @Override public void initializeClass() { } @Override public long flags() { return 0; } @Override public void setAuthorID(final String authorID) { author = authorID; } @Override public String getAuthorID() { return author; } @Override public void setCurrency(final String newCurrency) { if(currency.length()>0) { CMLib.beanCounter().unloadCurrencySet(currency); currency=newCurrency; for(final Enumeration<Area> e=CMLib.map().areas();e.hasMoreElements();) CMLib.beanCounter().getCurrencySet(e.nextElement().getCurrency()); } else { currency=newCurrency; CMLib.beanCounter().getCurrencySet(currency); } } @Override public String getCurrency() { return currency; } @Override public int getAtmosphereCode() { return atmosphere; } @Override public void setAtmosphere(final int resourceCode) { atmosphere=resourceCode; derivedAtmo=ATMOSPHERE_INHERIT; } @Override public int getAtmosphere() { if(derivedAtmo!=ATMOSPHERE_INHERIT) return derivedAtmo; final Stack<Area> areasToDo=new Stack<Area>(); areasToDo.push(this); while(areasToDo.size()>0) { final Area A=areasToDo.pop(); derivedAtmo=A.getAtmosphereCode(); if(derivedAtmo!=ATMOSPHERE_INHERIT) return derivedAtmo; for(final Enumeration<Area> a=A.getParents();a.hasMoreElements();) areasToDo.push(a.nextElement()); } derivedAtmo=RawMaterial.RESOURCE_AIR; return derivedAtmo; } @Override public String getBlurbFlag(final String flag) { if((flag==null)||(flag.trim().length()==0)) return null; return blurbFlags.get(flag.toUpperCase().trim()); } @Override public int numBlurbFlags() { return blurbFlags.size(); } @Override public int numAllBlurbFlags() { int num=numBlurbFlags(); for(final Iterator<Area> i=getParentsIterator();i.hasNext();) num += i.next().numAllBlurbFlags(); return num; } @Override public Enumeration<String> areaBlurbFlags() { return new IteratorEnumeration<String>(blurbFlags.keySet().iterator()); } @Override public void addBlurbFlag(String flagPlusDesc) { if(flagPlusDesc==null) return; flagPlusDesc=flagPlusDesc.trim(); if(flagPlusDesc.length()==0) return; final int x=flagPlusDesc.indexOf(' '); String flag=null; if(x>=0) { flag=flagPlusDesc.substring(0,x).toUpperCase(); flagPlusDesc=flagPlusDesc.substring(x).trim(); } else { flag=flagPlusDesc.toUpperCase().trim(); flagPlusDesc=""; } if(getBlurbFlag(flag)==null) blurbFlags.put(flag,flagPlusDesc); } @Override public void delBlurbFlag(String flagOnly) { if(flagOnly==null) return; flagOnly=flagOnly.toUpperCase().trim(); if(flagOnly.length()==0) return; blurbFlags.remove(flagOnly); } @Override public long expirationDate() { return expirationDate; } @Override public void setExpirationDate(final long time) { expirationDate = time; } @Override public void setClimateObj(final Climate obj) { if(obj != null) climateObj = obj; } @Override public Climate getClimateObj() { if(climateObj == null) climateObj = (Climate)CMClass.getCommon("DefaultClimate"); return climateObj; } @Override public void setTimeObj(final TimeClock obj) { if(obj != null) { myClock = obj; for(final Iterator<Area> i=getChildrenIterator(); i.hasNext();) { final Area A=i.next(); A.setTimeObj(obj); } } } @Override public TimeClock getTimeObj() { if(myClock==null) { if((this.parents != null)&&(this.parents.size()>0)) myClock=this.parents.iterator().next().getTimeObj(); else myClock=CMLib.time().globalClock(); } return myClock; } public StdArea() { super(); //CMClass.bumpCounter(this,CMClass.CMObjectType.AREA);//removed for mem & perf xtraValues=CMProps.getExtraStatCodesHolder(this); } /* protected void finalize() { CMClass.unbumpCounter(this, CMClass.CMObjectType.AREA); }// removed for mem & perf */ @Override public void destroy() { CMLib.map().registerWorldObjectDestroyed(this,null,this); phyStats=(PhyStats)CMClass.getCommon("DefaultPhyStats"); basePhyStats=phyStats; amDestroyed=true; miscText=null; imageName=null; affects=new SVector<Ability>(1); behaviors=new SVector<Behavior>(1); scripts=new SVector<ScriptingEngine>(1); author=null; currency=null; children=new SLinkedList<Area>(); parents=new SLinkedList<Area>(); blurbFlags=new STreeMap<String,String>(); subOps=new SVector<String>(1); properRooms=new STreeMap<String, Room>(); //metroRooms=null; myClock=null; climateObj=null; properRoomIDSet=null; metroRoomIDSet=null; author=""; currency=""; devalueRate=null; budget=""; ignoreMask=""; prejudiceFactors=""; derivedClimate=CLIMASK_INHERIT; derivedAtmo=ATMOSPHERE_INHERIT; derivedTheme=THEME_INHERIT; } @Override public boolean amDestroyed() { return amDestroyed; } @Override public boolean isSavable() { return ((!amDestroyed) && (!CMath.bset(flags(),Area.FLAG_INSTANCE_CHILD)) && (CMLib.flags().isSavable(this))); } @Override public void setSavable(final boolean truefalse) { CMLib.flags().setSavable(this, truefalse); } @Override public String name() { if(phyStats().newName()!=null) return phyStats().newName(); return name; } @Override public synchronized RoomnumberSet getProperRoomnumbers() { if(properRoomIDSet==null) properRoomIDSet=(RoomnumberSet)CMClass.getCommon("DefaultRoomnumberSet"); return properRoomIDSet; } @Override public RoomnumberSet getCachedRoomnumbers() { final RoomnumberSet set=(RoomnumberSet)CMClass.getCommon("DefaultRoomnumberSet"); synchronized(properRooms) { for(final Room R : properRooms.values()) { if(R.roomID().length()>0) set.add(R.roomID()); } } return set; } @Override public void setName(final String newName) { if(newName != null) { name=newName.replace('\'', '`'); CMLib.map().renamedArea(this); } } @Override public String Name() { return name; } @Override public PhyStats phyStats() { return phyStats; } @Override public PhyStats basePhyStats() { return basePhyStats; } @Override public void recoverPhyStats() { basePhyStats.copyInto(phyStats); eachEffect(new EachApplicable<Ability>() { @Override public final void apply(final Ability A) { A.affectPhyStats(me, phyStats); } }); } @Override public void setBasePhyStats(final PhyStats newStats) { basePhyStats=(PhyStats)newStats.copyOf(); } @Override public int getThemeCode() { return theme; } @Override public int getTheme() { if(derivedTheme!=THEME_INHERIT) return derivedTheme; final Stack<Area> areasToDo=new Stack<Area>(); areasToDo.push(this); while(areasToDo.size()>0) { final Area A=areasToDo.pop(); derivedTheme=A.getThemeCode(); if(derivedTheme!=THEME_INHERIT) return derivedTheme; for(final Enumeration<Area> a=A.getParents();a.hasMoreElements();) areasToDo.push(a.nextElement()); } derivedTheme=CMProps.getIntVar(CMProps.Int.MUDTHEME); return derivedTheme; } @Override public void setTheme(final int level) { theme=level; derivedTheme=THEME_INHERIT; } @Override public String getArchivePath() { return archPath; } @Override public void setArchivePath(final String pathFile) { archPath = pathFile; } @Override public String image() { return imageName; } @Override public String rawImage() { return imageName; } @Override public void setImage(final String newImage) { imageName = newImage; } @Override public void setAreaState(final State newState) { if((newState==State.ACTIVE) &&(!CMLib.threads().isTicking(this,Tickable.TICKID_AREA))) { CMLib.threads().startTickDown(this,Tickable.TICKID_AREA,1); if(!CMLib.threads().isTicking(this, Tickable.TICKID_AREA)) Log.errOut("StdArea","Area "+name()+" failed to start ticking."); } flag=newState; derivedClimate=CLIMASK_INHERIT; derivedAtmo=ATMOSPHERE_INHERIT; derivedTheme=THEME_INHERIT; } @Override public State getAreaState() { return flag; } @Override public boolean amISubOp(final String username) { for(int s=subOps.size()-1;s>=0;s--) { if(subOps.elementAt(s).equalsIgnoreCase(username)) return true; } return false; } @Override public String getSubOpList() { final StringBuffer list=new StringBuffer(""); for(int s=subOps.size()-1;s>=0;s--) { final String str=subOps.elementAt(s); list.append(str); list.append(";"); } return list.toString(); } @Override public void setSubOpList(final String list) { subOps.clear(); subOps.addAll(CMParms.parseSemicolons(list,true)); } @Override public void addSubOp(final String username) { subOps.addElement(username); } @Override public void delSubOp(final String username) { for(int s=subOps.size()-1;s>=0;s--) { if(subOps.elementAt(s).equalsIgnoreCase(username)) subOps.removeElementAt(s); } } @Override public String getNewRoomID(final Room startRoom, final int direction) { int highest=Integer.MIN_VALUE; int lowest=Integer.MAX_VALUE; final LongSet set=new LongSet(); try { String roomID=null; int newnum=0; final String name=Name().toUpperCase(); for(final Enumeration<String> i=CMLib.map().roomIDs();i.hasMoreElements();) { roomID=i.nextElement(); if((roomID.length()>0)&&(roomID.startsWith(name+"#"))) { roomID=roomID.substring(name.length()+1); if(CMath.isInteger(roomID)) { newnum=CMath.s_int(roomID); if(newnum>=0) { if(newnum>=highest) highest=newnum; if(newnum<=lowest) lowest=newnum; set.add(Long.valueOf(newnum)); } } } } } catch (final NoSuchElementException e) { } if(highest<0) { for(int i=0;i<Integer.MAX_VALUE;i++) { if(((CMLib.map().getRoom(Name()+"#"+i))==null) &&(getRoom(Name()+"#"+i)==null)) return Name()+"#"+i; } } if(lowest>highest) { lowest=highest+1; } for(int i=lowest;i<=highest+1000;i++) { if((!set.contains(i)) &&(CMLib.map().getRoom(Name()+"#"+i)==null) &&(getRoom(Name()+"#"+i)==null)) return Name()+"#"+i; } return Name()+"#"+(int)Math.round(Math.random()*Integer.MAX_VALUE); } @Override public CMObject newInstance() { if(CMSecurity.isDisabled(CMSecurity.DisFlag.FATAREAS) &&(ID().equals("StdArea"))) { final Area A=CMClass.getAreaType("StdThinArea"); if(A!=null) return A; } try { return this.getClass().newInstance(); } catch(final Exception e) { Log.errOut(ID(),e); } return new StdArea(); } @Override public boolean isGeneric() { return false; } protected void cloneFix(final StdArea areaA) { me=this; basePhyStats=(PhyStats)areaA.basePhyStats().copyOf(); phyStats=(PhyStats)areaA.phyStats().copyOf(); properRooms =new STreeMap<String, Room>(new RoomIDComparator()); properRoomIDSet=null; metroRoomIDSet =null; parents=areaA.parents.copyOf(); children=areaA.children.copyOf(); if(areaA.blurbFlags!=null) blurbFlags=areaA.blurbFlags.copyOf(); affects=new SVector<Ability>(1); behaviors=new SVector<Behavior>(1); scripts=new SVector<ScriptingEngine>(1); derivedClimate=CLIMASK_INHERIT; derivedTheme=THEME_INHERIT; derivedAtmo=ATMOSPHERE_INHERIT; for(final Enumeration<Behavior> e=areaA.behaviors();e.hasMoreElements();) { final Behavior B=e.nextElement(); if(B!=null) behaviors.addElement((Behavior)B.copyOf()); } for(final Enumeration<Ability> a=areaA.effects();a.hasMoreElements();) { final Ability A=a.nextElement(); if(A!=null) affects.addElement((Ability)A.copyOf()); } ScriptingEngine SE=null; for(final Enumeration<ScriptingEngine> e=areaA.scripts();e.hasMoreElements();) { SE=e.nextElement(); if(SE!=null) addScript((ScriptingEngine)SE.copyOf()); } setSubOpList(areaA.getSubOpList()); } @Override public CMObject copyOf() { try { final StdArea E=(StdArea)this.clone(); //CMClass.bumpCounter(this,CMClass.CMObjectType.AREA);//removed for mem & perf E.xtraValues=(xtraValues==null)?null:(String[])xtraValues.clone(); E.cloneFix(this); return E; } catch(final CloneNotSupportedException e) { return this.newInstance(); } } @Override public String displayText() { return ""; } @Override public void setDisplayText(final String newDisplayText) { } @Override public String displayText(final MOB viewerMob) { return displayText(); } @Override public String name(final MOB viewerMob) { return name(); } @Override public String finalPrejudiceFactors() { final String s=finalPrejudiceFactors(this); if(s.length()>0) return s; return CMProps.getVar(CMProps.Str.IGNOREMASK); } protected String finalPrejudiceFactors(final Area A) { if(A.prejudiceFactors().length()>0) return A.prejudiceFactors(); for(final Enumeration<Area> i=A.getParents();i.hasMoreElements();) { final String s=finalPrejudiceFactors(i.nextElement()); if(s.length()!=0) return s; } return ""; } @Override public String prejudiceFactors() { return prejudiceFactors; } @Override public void setPrejudiceFactors(final String factors) { prejudiceFactors = factors; } @Override public String[] finalItemPricingAdjustments() { final String[] s=finalItemPricingAdjustments(this); if(s.length>0) return s; return CMLib.coffeeShops().parseItemPricingAdjustments(CMProps.getVar(CMProps.Str.PRICEFACTORS).trim()); } protected String[] finalItemPricingAdjustments(final Area A) { if(A.itemPricingAdjustments().length>0) return A.itemPricingAdjustments(); for(final Enumeration<Area> i=A.getParents();i.hasMoreElements();) { final String[] s=finalItemPricingAdjustments(i.nextElement()); if(s.length!=0) return s; } return empty; } @Override public String[] itemPricingAdjustments() { return itemPricingAdjustments; } @Override public void setItemPricingAdjustments(final String[] factors) { itemPricingAdjustments = factors; } @Override public String finalIgnoreMask() { final String s=finalIgnoreMask(this); if(s.length()>0) return s; return CMProps.getVar(CMProps.Str.IGNOREMASK); } protected String finalIgnoreMask(final Area A) { if(A.ignoreMask().length()>0) return A.ignoreMask(); for(final Enumeration<Area> i=A.getParents();i.hasMoreElements();) { final String s=finalIgnoreMask(i.nextElement()); if(s.length()!=0) return s; } return ""; } @Override public String ignoreMask() { return ignoreMask; } @Override public void setIgnoreMask(final String factors) { ignoreMask = factors; } @Override public Pair<Long, TimePeriod> finalBudget() { final Pair<Long, TimePeriod> budget=finalAreaBudget(this); if(budget != null) return budget; return CMLib.coffeeShops().parseBudget(CMProps.getVar(CMProps.Str.BUDGET)); } protected Pair<Long, TimePeriod> finalAreaBudget(final Area A) { if(A.budget().length()>0) return CMLib.coffeeShops().parseBudget(A.budget()); for(final Enumeration<Area> i=A.getParents();i.hasMoreElements();) { final Pair<Long, TimePeriod> budget=finalAreaBudget(i.nextElement()); if(budget != null) return budget; } return null; } @Override public String budget() { return budget; } @Override public void setBudget(final String factors) { budget = factors; } @Override public double[] finalDevalueRate() { final double[] rate=finalAreaDevalueRate(this); if(rate != null) return rate; return CMLib.coffeeShops().parseDevalueRate(CMProps.getVar(CMProps.Str.DEVALUERATE)); } protected double[] finalAreaDevalueRate(final Area A) { if(A.devalueRate().length()>0) return CMLib.coffeeShops().parseDevalueRate(A.devalueRate()); for(final Enumeration<Area> i=A.getParents();i.hasMoreElements();) { final double[] rate=finalAreaDevalueRate(i.nextElement()); if(rate != null) return rate; } return null; } @Override public String devalueRate() { return (devalueRate == null) ? "" : (devalueRate[0] + " " + devalueRate[1]); } @Override public void setDevalueRate(final String factors) { devalueRate = CMLib.coffeeShops().parseDevalueRate(factors); } @Override public int invResetRate() { return invResetRate; } @Override public void setInvResetRate(final int ticks) { invResetRate = ticks; } @Override public int finalInvResetRate() { final int x=finalInvResetRate(this); if(x!=0) return x; return CMath.s_int(CMProps.getVar(CMProps.Str.INVRESETRATE)); } protected int finalInvResetRate(final Area A) { if(A.invResetRate()!=0) return A.invResetRate(); for(final Enumeration<Area> i=A.getParents();i.hasMoreElements();) { final int x=finalInvResetRate(i.nextElement()); if(x!=0) return x; } return 0; } @Override public int compareTo(final CMObject o) { return CMClass.classID(this).compareToIgnoreCase(CMClass.classID(o)); } @Override public String miscTextFormat() { return CMParms.FORMAT_UNDEFINED; } @Override public String text() { return CMLib.coffeeMaker().getPropertiesStr(this,true); } @Override public void setMiscText(final String newMiscText) { miscText=""; if(newMiscText.trim().length()>0) CMLib.coffeeMaker().setPropertiesStr(this,newMiscText,true); derivedClimate=CLIMASK_INHERIT; derivedAtmo=ATMOSPHERE_INHERIT; derivedTheme=THEME_INHERIT; } @Override public String description() { return description; } @Override public void setDescription(final String newDescription) { description = newDescription; } @Override public String description(final MOB viewerMob) { return description(); } @Override public int getClimateTypeCode() { return climask; } @Override public void setClimateType(final int newClimateType) { climask=newClimateType; derivedClimate=CLIMASK_INHERIT; } @Override public int getClimateType() { if(derivedClimate!=CLIMASK_INHERIT) return derivedClimate; final Stack<Area> areasToDo=new Stack<Area>(); areasToDo.push(this); while(areasToDo.size()>0) { final Area A=areasToDo.pop(); derivedClimate=A.getClimateTypeCode(); if(derivedClimate!=CLIMASK_INHERIT) return derivedClimate; for(final Enumeration<Area> a=A.getParents();a.hasMoreElements();) areasToDo.push(a.nextElement()); } derivedClimate=Places.CLIMASK_NORMAL; return derivedClimate; } @Override public boolean okMessage(final Environmental myHost, final CMMsg msg) { MsgListener N=null; for(int b=0;b<numBehaviors();b++) { N=fetchBehavior(b); if((N!=null)&&(!N.okMessage(this,msg))) return false; } for(int s=0;s<numScripts();s++) { N=fetchScript(s); if((N!=null)&&(!N.okMessage(this,msg))) return false; } for(final Enumeration<Ability> a=effects();a.hasMoreElements();) { N=a.nextElement(); if((N!=null)&&(!N.okMessage(this,msg))) return false; } if(!msg.source().isMonster()) { lastPlayerTime=System.currentTimeMillis(); if((flag==State.PASSIVE) &&((msg.sourceMinor()==CMMsg.TYP_ENTER) ||(msg.sourceMinor()==CMMsg.TYP_LEAVE) ||(msg.sourceMinor()==CMMsg.TYP_FLEE))) flag=State.ACTIVE; } if((flag==State.FROZEN)||(flag==State.STOPPED)||(!CMLib.flags().allowsMovement(this))) { if((msg.sourceMinor()==CMMsg.TYP_ENTER) ||(msg.sourceMinor()==CMMsg.TYP_LEAVE) ||(msg.sourceMinor()==CMMsg.TYP_FLEE)) return false; } if(parents!=null) { for (final Area area : parents) { if(!area.okMessage(myHost,msg)) return false; } } if((getThemeCode()>0)&&(!CMath.bset(getThemeCode(),Area.THEME_FANTASY))) { if((CMath.bset(msg.sourceMajor(),CMMsg.MASK_MAGIC)) ||(CMath.bset(msg.targetMajor(),CMMsg.MASK_MAGIC)) ||(CMath.bset(msg.othersMajor(),CMMsg.MASK_MAGIC))) { Room room=null; if((msg.target() instanceof MOB) &&(((MOB)msg.target()).location()!=null)) room=((MOB)msg.target()).location(); else if(msg.source().location()!=null) room=msg.source().location(); if(room!=null) { if(room.getArea()==this) room.showHappens(CMMsg.MSG_OK_ACTION,L("Magic doesn't seem to work here.")); else room.showHappens(CMMsg.MSG_OK_ACTION,L("Magic doesn't seem to work there.")); } return false; } } else if((getTheme()>0)&&(!CMath.bset(getTheme(),Area.THEME_TECHNOLOGY))) { switch(msg.sourceMinor()) { case CMMsg.TYP_BUY: case CMMsg.TYP_BID: case CMMsg.TYP_CLOSE: case CMMsg.TYP_DEPOSIT: case CMMsg.TYP_DROP: case CMMsg.TYP_LOOK: case CMMsg.TYP_EXAMINE: case CMMsg.TYP_GET: case CMMsg.TYP_PUSH: case CMMsg.TYP_PULL: case CMMsg.TYP_GIVE: case CMMsg.TYP_OPEN: case CMMsg.TYP_PUT: case CMMsg.TYP_SELL: case CMMsg.TYP_VALUE: case CMMsg.TYP_REMOVE: case CMMsg.TYP_VIEW: case CMMsg.TYP_WITHDRAW: case CMMsg.TYP_BORROW: break; case CMMsg.TYP_POWERCURRENT: return false; default: if(msg.tool() instanceof Electronics) { Room room=null; if((msg.target() instanceof MOB) &&(((MOB)msg.target()).location()!=null)) room=((MOB)msg.target()).location(); else if(msg.source().location()!=null) room=msg.source().location(); if(room!=null) room.showHappens(CMMsg.MSG_OK_VISUAL,L("Technology doesn't seem to work here.")); return false; } break; } } return true; } @Override public void executeMsg(final Environmental myHost, final CMMsg msg) { eachBehavior(new EachApplicable<Behavior>() { @Override public final void apply(final Behavior B) { B.executeMsg(me, msg); } }); eachScript(new EachApplicable<ScriptingEngine>() { @Override public final void apply(final ScriptingEngine S) { S.executeMsg(me, msg); } }); eachEffect(new EachApplicable<Ability>() { @Override public final void apply(final Ability A) { A.executeMsg(me, msg); } }); if((msg.sourceMinor()==CMMsg.TYP_RETIRE) &&(amISubOp(msg.source().Name()))) delSubOp(msg.source().Name()); if(parents!=null) { for (final Area area : parents) area.executeMsg(myHost,msg); } } @Override public int getTickStatus() { return tickStatus; } @Override public boolean tick(final Tickable ticking, final int tickID) { if((flag==State.STOPPED)||(amDestroyed())) return false; tickStatus=Tickable.STATUS_START; if(tickID==Tickable.TICKID_AREA) { if((flag==State.ACTIVE) &&((System.currentTimeMillis()-lastPlayerTime)>passiveLapseMs)) { if(CMSecurity.isDisabled(CMSecurity.DisFlag.PASSIVEAREAS) &&(!CMath.bset(flags(), Area.FLAG_INSTANCE_CHILD))) lastPlayerTime=System.currentTimeMillis(); else flag=State.PASSIVE; } tickStatus=Tickable.STATUS_ALIVE; getClimateObj().tick(this,tickID); tickStatus=Tickable.STATUS_REBIRTH; getTimeObj().tick(this,tickID); tickStatus=Tickable.STATUS_BEHAVIOR; eachBehavior(new EachApplicable<Behavior>() { @Override public final void apply(final Behavior B) { B.tick(ticking,tickID); } }); tickStatus=Tickable.STATUS_SCRIPT; eachScript(new EachApplicable<ScriptingEngine>() { @Override public final void apply(final ScriptingEngine S) { S.tick(ticking,tickID); } }); tickStatus=Tickable.STATUS_AFFECT; eachEffect(new EachApplicable<Ability>() { @Override public final void apply(final Ability A) { if (!A.tick(ticking, tickID)) A.unInvoke(); } }); } tickStatus=Tickable.STATUS_NOT; return true; } @Override public void affectPhyStats(final Physical affected, final PhyStats affectableStats) { final int senses=phyStats.sensesMask()&(~(PhyStats.SENSE_UNLOCATABLE|PhyStats.CAN_NOT_SEE)); if(senses>0) affectableStats.setSensesMask(affectableStats.sensesMask()|senses); int disposition=phyStats().disposition() &((~(PhyStats.IS_SLEEPING|PhyStats.IS_HIDDEN))); if((affected instanceof Room) &&(CMLib.map().hasASky((Room)affected))) { final Climate C=getClimateObj(); if(((C==null) ||(((C.weatherType((Room)affected)==Climate.WEATHER_BLIZZARD) ||(C.weatherType((Room)affected)==Climate.WEATHER_DUSTSTORM)) &&(!CMSecurity.isDisabled(CMSecurity.DisFlag.DARKWEATHER))) ||((getTimeObj().getTODCode()==TimeClock.TimeOfDay.NIGHT)&&(!CMSecurity.isDisabled(CMSecurity.DisFlag.DARKNIGHTS)))) &&((disposition&PhyStats.IS_LIGHTSOURCE)==0)) disposition=disposition|PhyStats.IS_DARK; } if(disposition>0) affectableStats.setDisposition(affectableStats.disposition()|disposition); affectableStats.setWeight(affectableStats.weight()+phyStats().weight()); // well, that's weird eachEffect(new EachApplicable<Ability>() { @Override public final void apply(final Ability A) { if (A.bubbleAffect()) A.affectPhyStats(affected, affectableStats); } }); } @Override public void affectCharStats(final MOB affectedMob, final CharStats affectableStats) { eachEffect(new EachApplicable<Ability>() { @Override public final void apply(final Ability A) { if (A.bubbleAffect()) A.affectCharStats(affectedMob, affectableStats); } }); } @Override public void affectCharState(final MOB affectedMob, final CharState affectableMaxState) { eachEffect(new EachApplicable<Ability>() { @Override public final void apply(final Ability A) { if (A.bubbleAffect()) A.affectCharState(affectedMob, affectableMaxState); } }); } @Override public void addNonUninvokableEffect(final Ability to) { if(to==null) return; if(fetchEffect(to.ID())!=null) return; to.makeNonUninvokable(); to.makeLongLasting(); affects.addElement(to); to.setAffectedOne(this); } @Override public void addEffect(final Ability to) { if(to==null) return; if(fetchEffect(to.ID())!=null) return; affects.addElement(to); to.setAffectedOne(this); } @Override public void delEffect(final Ability to) { final int size=affects.size(); affects.removeElement(to); if(affects.size()<size) to.setAffectedOne(null); } @Override public void eachEffect(final EachApplicable<Ability> applier) { final List<Ability> affects=this.affects; if(affects==null) return; try { for(int a=0;a<affects.size();a++) { final Ability A=affects.get(a); if(A!=null) applier.apply(A); } } catch (final ArrayIndexOutOfBoundsException e) { } } @Override public void delAllEffects(final boolean unInvoke) { for(int a=numEffects()-1;a>=0;a--) { final Ability A=fetchEffect(a); if(A!=null) { if(unInvoke) A.unInvoke(); A.setAffectedOne(null); } } affects.clear(); } @Override public int numEffects() { return (affects==null)?0:affects.size(); } @SuppressWarnings("unchecked") @Override public Enumeration<Ability> effects() { return (affects == null) ? EmptyEnumeration.INSTANCE : affects.elements(); } @Override public Ability fetchEffect(final int index) { try { return affects.elementAt(index); } catch (final java.lang.ArrayIndexOutOfBoundsException x) { } return null; } @Override public Ability fetchEffect(final String ID) { for(final Enumeration<Ability> a=effects();a.hasMoreElements();) { final Ability A=a.nextElement(); if((A!=null)&&(A.ID().equals(ID))) return A; } return null; } @Override public boolean inMyMetroArea(final Area A) { if(A==this) return true; for(final Iterator<Area> i=getChildrenIterator();i.hasNext();) { if(i.next().inMyMetroArea(A)) return true; } return false; } @Override public void fillInAreaRooms() { for(final Enumeration<Room> r=getProperMap();r.hasMoreElements();) { final Room R=r.nextElement(); R.clearSky(); if(R.roomID().length()>0) { if(R instanceof GridLocale) ((GridLocale)R).buildGrid(); } } for(final Enumeration<Room> r=getProperMap();r.hasMoreElements();) { final Room R=r.nextElement(); R.giveASky(0); } } @Override public void fillInAreaRoom(final Room R) { if(R==null) return; R.clearSky(); if(R.roomID().length()>0) { if(R instanceof GridLocale) ((GridLocale)R).buildGrid(); } R.giveASky(0); } /** Manipulation of Behavior objects, which includes * movement, speech, spellcasting, etc, etc.*/ @Override public void addBehavior(final Behavior to) { if(to==null) return; for(final Behavior B : behaviors) { if((B!=null)&&(B.ID().equals(to.ID()))) return; } to.startBehavior(this); behaviors.addElement(to); } @Override public void delBehavior(final Behavior to) { if(behaviors.removeElement(to)) to.endBehavior(this); } @Override public void delAllBehaviors() { behaviors.clear(); } @Override public int numBehaviors() { return behaviors.size(); } @Override public Enumeration<Behavior> behaviors() { return behaviors.elements(); } /** Manipulation of the scripts list */ @Override public void addScript(final ScriptingEngine S) { if(S==null) return; if(!scripts.contains(S)) { ScriptingEngine S2=null; for(int s=0;s<scripts.size();s++) { S2=scripts.elementAt(s); if((S2!=null)&&(S2.getScript().equalsIgnoreCase(S.getScript()))) return; } scripts.addElement(S); } } @Override public void delScript(final ScriptingEngine S) { scripts.removeElement(S); } @Override public int numScripts() { return scripts.size(); } @Override public Enumeration<ScriptingEngine> scripts() { return scripts.elements(); } @Override public ScriptingEngine fetchScript(final int x) { try { return scripts.elementAt(x); } catch (final Exception e) { } return null; } @Override public void delAllScripts() { scripts.clear(); } @Override public void eachScript(final EachApplicable<ScriptingEngine> applier) { final List<ScriptingEngine> scripts=this.scripts; if(scripts!=null) { try { for(int a=0;a<scripts.size();a++) { final ScriptingEngine S=scripts.get(a); if(S!=null) applier.apply(S); } } catch (final ArrayIndexOutOfBoundsException e) { } } } @Override public int maxRange() { return Integer.MAX_VALUE; } @Override public int minRange() { return Integer.MIN_VALUE; } protected void buildAreaIMobStats(final int[] statData, final long[] totalAlignments, final Faction theFaction, final List<Integer> alignRanges, final List<Integer> levelRanges, final MOB mob) { if((mob!=null) &&(mob.isMonster()) &&(!CMLib.flags().isUnattackable(mob))) { final int lvl=mob.basePhyStats().level(); levelRanges.add(Integer.valueOf(lvl)); if((theFaction!=null)&&(mob.fetchFaction(theFaction.factionID())!=Integer.MAX_VALUE)) { alignRanges.add(Integer.valueOf(mob.fetchFaction(theFaction.factionID()))); totalAlignments[0]+=mob.fetchFaction(theFaction.factionID()); } statData[Area.Stats.POPULATION.ordinal()]++; statData[Area.Stats.TOTAL_LEVELS.ordinal()]+=lvl; if(!CMLib.flags().isAnimalIntelligence(mob)) { statData[Area.Stats.TOTAL_INTELLIGENT_LEVELS.ordinal()]+=lvl; statData[Area.Stats.INTELLIGENT_MOBS.ordinal()]++; } else { statData[Area.Stats.ANIMALS.ordinal()]++; } if(lvl<statData[Area.Stats.MIN_LEVEL.ordinal()]) statData[Area.Stats.MIN_LEVEL.ordinal()]=lvl; if(lvl>statData[Area.Stats.MAX_LEVEL.ordinal()]) statData[Area.Stats.MAX_LEVEL.ordinal()]=lvl; /* if(CMLib.factions().isAlignmentLoaded(Faction.Align.GOOD)) { if(CMLib.flags().isGood(mob)) statData[Area.Stats.GOOD_MOBS.ordinal()]++; else if(CMLib.flags().isEvil(mob)) statData[Area.Stats.EVIL_MOBS.ordinal()]++; } if(CMLib.factions().isAlignmentLoaded(Faction.Align.LAWFUL)) { if(CMLib.flags().isLawful(mob)) statData[Area.Stats.LAWFUL_MOBS.ordinal()]++; else if(CMLib.flags().isChaotic(mob)) statData[Area.Stats.CHAOTIC_MOBS.ordinal()]++; } if(mob.fetchEffect("Prop_ShortEffects")!=null) statData[Area.Stats.BOSS_MOBS.ordinal()]++; if(" Humanoid Elf Dwarf Halfling HalfElf ".indexOf(" "+mob.charStats().getMyRace().racialCategory()+" ")>=0) statData[Area.Stats.HUMANOIDS.ordinal()]++; */ } } protected int[] buildAreaIStats() { final List<Integer> levelRanges=new Vector<Integer>(); final List<Integer> alignRanges=new Vector<Integer>(); Faction theFaction=null; for(final Enumeration<Faction> e=CMLib.factions().factions();e.hasMoreElements();) { final Faction F=e.nextElement(); if(F.showInSpecialReported()) theFaction=F; } final int[] statData=new int[Area.Stats.values().length]; statData[Area.Stats.POPULATION.ordinal()]=0; statData[Area.Stats.MIN_LEVEL.ordinal()]=Integer.MAX_VALUE; statData[Area.Stats.MAX_LEVEL.ordinal()]=Integer.MIN_VALUE; statData[Area.Stats.AVG_LEVEL.ordinal()]=0; statData[Area.Stats.MED_LEVEL.ordinal()]=0; statData[Area.Stats.AVG_ALIGNMENT.ordinal()]=0; statData[Area.Stats.TOTAL_LEVELS.ordinal()]=0; statData[Area.Stats.TOTAL_INTELLIGENT_LEVELS.ordinal()]=0; statData[Area.Stats.VISITABLE_ROOMS.ordinal()]=getProperRoomnumbers().roomCountAllAreas(); final long[] totalAlignments=new long[]{0}; for(final Enumeration<Room> r=getProperMap();r.hasMoreElements();) { final Room R=r.nextElement(); final int countable; if(R instanceof GridLocale) { statData[Area.Stats.VISITABLE_ROOMS.ordinal()]--; countable = ((GridLocale)R).getGridSize(); } else countable=1; statData[Area.Stats.COUNTABLE_ROOMS.ordinal()]+=countable; if((R.domainType()&Room.INDOORS)>0) { statData[Area.Stats.INDOOR_ROOMS.ordinal()]+=countable; switch(R.domainType()) { case Room.DOMAIN_INDOORS_CAVE: statData[Area.Stats.CAVE_ROOMS.ordinal()]+=countable; break; case Room.DOMAIN_INDOORS_METAL: case Room.DOMAIN_INDOORS_STONE: case Room.DOMAIN_INDOORS_WOOD: statData[Area.Stats.CITY_ROOMS.ordinal()]+=countable; break; case Room.DOMAIN_INDOORS_UNDERWATER: case Room.DOMAIN_INDOORS_WATERSURFACE: statData[Area.Stats.WATER_ROOMS.ordinal()]+=countable; break; } } else { switch(R.domainType()) { case Room.DOMAIN_OUTDOORS_CITY: statData[Area.Stats.CITY_ROOMS.ordinal()]+=countable; break; case Room.DOMAIN_OUTDOORS_DESERT: statData[Area.Stats.DESERT_ROOMS.ordinal()]+=countable; break; case Room.DOMAIN_OUTDOORS_UNDERWATER: case Room.DOMAIN_OUTDOORS_WATERSURFACE: statData[Area.Stats.WATER_ROOMS.ordinal()]+=countable; break; } } for(int i=0;i<R.numInhabitants();i++) buildAreaIMobStats(statData,totalAlignments,theFaction,alignRanges,levelRanges,R.fetchInhabitant(i)); for(int i=0;i<R.numItems();i++) { final Item I=R.getItem(i); if(I instanceof BoardableShip) { final Area A=((BoardableShip)I).getShipArea(); if(A==null) continue; for(final Enumeration<Room> r2=A.getProperMap();r2.hasMoreElements();) { final Room R2=r2.nextElement(); for(int i2=0;i2<R2.numInhabitants();i2++) buildAreaIMobStats(statData,totalAlignments,theFaction,alignRanges,levelRanges,R2.fetchInhabitant(i2)); } } } } if((statData[Area.Stats.POPULATION.ordinal()]==0)||(levelRanges.size()==0)) { statData[Area.Stats.MIN_LEVEL.ordinal()]=0; statData[Area.Stats.MAX_LEVEL.ordinal()]=0; } else { Collections.sort(levelRanges); Collections.sort(alignRanges); statData[Area.Stats.MED_LEVEL.ordinal()]=levelRanges.get((int)Math.round(Math.floor(CMath.div(levelRanges.size(),2.0)))).intValue(); if(alignRanges.size()>0) { statData[Area.Stats.MED_ALIGNMENT.ordinal()]=alignRanges.get((int)Math.round(Math.floor(CMath.div(alignRanges.size(),2.0)))).intValue(); statData[Area.Stats.MIN_ALIGNMENT.ordinal()]=alignRanges.get(0).intValue(); statData[Area.Stats.MAX_ALIGNMENT.ordinal()]=alignRanges.get(alignRanges.size()-1).intValue(); } statData[Area.Stats.AVG_LEVEL.ordinal()]=(int)Math.round(CMath.div(statData[Area.Stats.TOTAL_LEVELS.ordinal()],statData[Area.Stats.POPULATION.ordinal()])); statData[Area.Stats.AVG_ALIGNMENT.ordinal()]=(int)Math.round(((double)totalAlignments[0])/((double)statData[Area.Stats.POPULATION.ordinal()])); } basePhyStats().setLevel(statData[Area.Stats.MED_LEVEL.ordinal()]); phyStats().setLevel(statData[Area.Stats.MED_LEVEL.ordinal()]); //basePhyStats().setHeight(statData[Area.Stats.POPULATION.ordinal()]); return statData; } @Override public int getPlayerLevel() { return playerLevel; } @Override public void setPlayerLevel(final int level) { playerLevel=level; } @Override public int[] getAreaIStats() { if(!CMProps.getBoolVar(CMProps.Bool.MUDSTARTED)) return emptyStats; int[] statData=(int[])Resources.getResource("STATS_"+Name().toUpperCase()); if(statData!=null) return statData; synchronized(("STATS_"+Name()).intern()) { Resources.removeResource("HELP_"+Name().toUpperCase()); statData=buildAreaIStats(); Resources.submitResource("STATS_"+Name().toUpperCase(),statData); } return statData; } public int getPercentRoomsCached() { return 100; } protected StringBuffer buildAreaStats(final int[] statData) { final StringBuffer s=new StringBuffer("^N"); s.append("Area : ^H"+Name()+"^N\n\r"); s.append(description()+"\n\r"); if(author.length()>0) s.append("Author : ^H"+author+"^N\n\r"); if(statData == emptyStats) { s.append("\n\r^HFurther information about this area is not available at this time.^N\n\r"); return s; } s.append("Number of rooms: ^H"+statData[Area.Stats.VISITABLE_ROOMS.ordinal()]+"^N\n\r"); Faction theFaction=CMLib.factions().getFaction(CMLib.factions().getAlignmentID()); if(theFaction == null) { for(final Enumeration<Faction> e=CMLib.factions().factions();e.hasMoreElements();) { final Faction F=e.nextElement(); if(F.showInSpecialReported()) theFaction=F; } } if(statData[Area.Stats.POPULATION.ordinal()]==0) { if(getProperRoomnumbers().roomCountAllAreas()/2<properRooms.size()) s.append("Population : ^H0^N\n\r"); } else { s.append("Population : ^H"+statData[Area.Stats.POPULATION.ordinal()]+"^N\n\r"); final String currName=CMLib.beanCounter().getCurrency(this); if(currName.length()>0) s.append("Currency : ^H"+CMStrings.capitalizeAndLower(currName)+"^N\n\r"); else s.append("Currency : ^HGold coins (default)^N\n\r"); final LegalBehavior B=CMLib.law().getLegalBehavior(this); if(B!=null) { final String ruler=B.rulingOrganization(); if(ruler.length()>0) { final Clan C=CMLib.clans().getClan(ruler); if(C!=null) s.append("Controlled by : ^H"+C.getGovernmentName()+" "+C.name()+"^N\n\r"); } } s.append("Level range : ^H"+statData[Area.Stats.MIN_LEVEL.ordinal()]+"^N to ^H"+statData[Area.Stats.MAX_LEVEL.ordinal()]+"^N\n\r"); //s.append("Average level : ^H"+statData[Area.Stats.AVG_LEVEL.ordinal()]+"^N\n\r"); if(getPlayerLevel()>0) s.append("Player level : ^H"+getPlayerLevel()+"^N\n\r"); else s.append("Median level : ^H"+statData[Area.Stats.MED_LEVEL.ordinal()]+"^N\n\r"); if(theFaction!=null) s.append("Avg. "+CMStrings.padRight(theFaction.name(),10)+": ^H"+theFaction.fetchRangeName(statData[Area.Stats.AVG_ALIGNMENT.ordinal()])+"^N\n\r"); if(theFaction!=null) s.append("Med. "+CMStrings.padRight(theFaction.name(),10)+": ^H"+theFaction.fetchRangeName(statData[Area.Stats.MED_ALIGNMENT.ordinal()])+"^N\n\r"); } try { boolean blurbed=false; String flag=null; final List<Area> areas=new XVector<Area>(getParentsIterator()); areas.add(this); for(final Iterator<Area> i= areas.iterator(); i.hasNext();) { final Area A=i.next(); for(final Enumeration<String> f= A.areaBlurbFlags();f.hasMoreElements();) { flag=A.getBlurbFlag(f.nextElement()); if((flag!=null) &&((!flag.startsWith("{"))||(!flag.endsWith("}")))) { if (!blurbed) { blurbed = true; s.append("\n\r"); } s.append(flag+"\n\r"); } } } if(blurbed) s.append("\n\r"); } catch(final Exception e) { Log.errOut("StdArea",e); } return s; } @Override public synchronized StringBuffer getAreaStats() { if(!CMProps.getBoolVar(CMProps.Bool.MUDSTARTED)) return new StringBuffer(""); StringBuffer s=(StringBuffer)Resources.getResource("HELP_"+Name().toUpperCase()); if(s!=null) return s; s=buildAreaStats(getAreaIStats()); //Resources.submitResource("HELP_"+Name().toUpperCase(),s); // the STAT_ data is cached instead. return s; } @Override public Behavior fetchBehavior(final int index) { try { return behaviors.elementAt(index); } catch (final java.lang.ArrayIndexOutOfBoundsException x) { } return null; } @Override public Behavior fetchBehavior(final String ID) { for(final Behavior B : behaviors) { if((B!=null)&&(B.ID().equalsIgnoreCase(ID))) return B; } return null; } @Override public void eachBehavior(final EachApplicable<Behavior> applier) { final List<Behavior> behaviors=this.behaviors; if(behaviors!=null) try { for(int a=0;a<behaviors.size();a++) { final Behavior B=behaviors.get(a); if(B!=null) applier.apply(B); } } catch (final ArrayIndexOutOfBoundsException e) { } } @Override public int properSize() { synchronized(properRooms) { return properRooms.size(); } } @Override public void setProperRoomnumbers(final RoomnumberSet set) { properRoomIDSet = set; } @Override public void addProperRoom(final Room R) { if(R==null) return; if(R.getArea()!=this) { R.setArea(this); return; } synchronized(properRooms) { final String roomID=R.roomID(); if(roomID.length()==0) { if((R.getGridParent()!=null) &&(R.getGridParent().roomID().length()>0)) { // for some reason, grid children always get the back of the bus. addProperRoomnumber(R.getGridParent().getGridChildCode(R)); addMetroRoom(R); } return; } if(!properRooms.containsKey(R.roomID())) properRooms.put(R.roomID(),R); addProperRoomnumber(roomID); addMetroRoom(R); } } @Override public void addMetroRoom(final Room R) { if(R!=null) { if(R.roomID().length()==0) { if((R.getGridParent()!=null) &&(R.getGridParent().roomID().length()>0)) addMetroRoomnumber(R.getGridParent().getGridChildCode(R)); } else addMetroRoomnumber(R.roomID()); } } @Override public void delMetroRoom(final Room R) { if(R!=null) { if(R.roomID().length()==0) { if((R.getGridParent()!=null) &&(R.getGridParent().roomID().length()>0)) delMetroRoomnumber(R.getGridParent().getGridChildCode(R)); } else delMetroRoomnumber(R.roomID()); } } @Override public void addProperRoomnumber(final String roomID) { if((roomID!=null) &&(roomID.length()>0)) { getProperRoomnumbers().add(roomID); addMetroRoomnumber(roomID); } } @Override public void delProperRoomnumber(final String roomID) { if((roomID!=null)&&(roomID.length()>0)) { getProperRoomnumbers().remove(roomID); delMetroRoomnumber(roomID); } } @Override public void addMetroRoomnumber(final String roomID) { if(metroRoomIDSet==null) metroRoomIDSet=(RoomnumberSet)getProperRoomnumbers().copyOf(); if((roomID!=null)&&(roomID.length()>0)&&(!metroRoomIDSet.contains(roomID))) { metroRoomIDSet.add(roomID); if(!CMath.bset(flags(),Area.FLAG_INSTANCE_CHILD)) { for(final Iterator<Area> a=getParentsReverseIterator();a.hasNext();) a.next().addMetroRoomnumber(roomID); } } } @Override public void delMetroRoomnumber(final String roomID) { if((metroRoomIDSet!=null) &&(roomID!=null) &&(roomID.length()>0) &&(metroRoomIDSet.contains(roomID))) { metroRoomIDSet.remove(roomID); if(!CMath.bset(flags(),Area.FLAG_INSTANCE_CHILD)) { for(final Iterator<Area> a=getParentsReverseIterator();a.hasNext();) a.next().delMetroRoomnumber(roomID); } } } @Override public boolean isRoom(final Room R) { if(R==null) return false; if(R.roomID().length()>0) return getProperRoomnumbers().contains(R.roomID()); return properRooms.containsValue(R); } @Override public void delProperRoom(final Room R) { if(R==null) return; if(R instanceof GridLocale) ((GridLocale)R).clearGrid(null); synchronized(properRooms) { if(R.roomID().length()==0) { if((R.getGridParent()!=null) &&(R.getGridParent().roomID().length()>0)) { final String id=R.getGridParent().getGridChildCode(R); delProperRoomnumber(id); delMetroRoom(R); } } else if(properRooms.get(R.roomID())==R) { properRooms.remove(R.roomID()); delMetroRoom(R); delProperRoomnumber(R.roomID()); } else if(properRooms.containsValue(R)) { for(final Map.Entry<String,Room> entry : properRooms.entrySet()) { if(entry.getValue()==R) { properRooms.remove(entry.getKey()); delProperRoomnumber(entry.getKey()); } } delProperRoomnumber(R.roomID()); delMetroRoom(R); } } } @Override public Room getRoom(String roomID) { if(properRooms.size()==0) return null; if(roomID.length()==0) return null; synchronized(properRooms) { if((!roomID.startsWith(Name())) &&(roomID.toUpperCase().startsWith(Name().toUpperCase()+"#"))) roomID=Name()+roomID.substring(Name().length()); // for case sensitive situations return properRooms.get(roomID); } } @Override public int metroSize() { int num=properSize(); for(final Iterator<Area> a=getChildrenReverseIterator();a.hasNext();) num+=a.next().metroSize(); return num; } @Override public int numberOfProperIDedRooms() { int num=0; for(final Enumeration<Room> e=getProperMap();e.hasMoreElements();) { final Room R=e.nextElement(); if(R.roomID().length()>0) { if(R instanceof GridLocale) num+=((GridLocale)R).xGridSize()*((GridLocale)R).yGridSize(); else num++; } } return num; } @Override public boolean isProperlyEmpty() { return getProperRoomnumbers().isEmpty(); } @Override public Room getRandomProperRoom() { if(isProperlyEmpty()) return null; String roomID=getProperRoomnumbers().random(); if((roomID!=null) &&(!roomID.startsWith(Name())) &&(roomID.startsWith(Name().toUpperCase()))) roomID=Name()+roomID.substring(Name().length()); // looping back through CMMap is unnecc because the roomID comes directly from getProperRoomnumbers() // which means it will never be a grid sub-room. Room R=getRoom(roomID); if(R==null) { R=CMLib.map().getRoom(roomID); // BUT... it's ok to hit CMLib.map() if you fail. if(R==null) { if(this.properRooms.size()>0) { try { R=this.properRooms.firstEntry().getValue(); } catch(final Exception e) { } if(R!=null) { if(StdArea.lastComplainer != this) { StdArea.lastComplainer=this; Log.errOut("StdArea","Last Resort random-find due to failure on "+roomID+", so I just picked room: "+R.roomID()+" ("+this.amDestroyed+")"); } } else Log.errOut("StdArea","Wow, proper room size = "+this.properRooms.size()+", but no room! ("+this.amDestroyed+")"); } else { if(this.numberOfProperIDedRooms()==0) return null; Log.errOut("StdArea","Wow, proper room size = 0, but numrooms="+this.numberOfProperIDedRooms()+"! ("+this.amDestroyed+")"); } } } if(R instanceof GridLocale) return ((GridLocale)R).getRandomGridChild(); if((R==null)&&(StdArea.lastComplainer != this)) { StdArea.lastComplainer=this; Log.errOut("StdArea","Unable to random-find: "+roomID); Log.errOut(new Exception()); } return R; } @Override public Room getRandomMetroRoom() { /*synchronized(metroRooms) { if(metroSize()==0) return null; Room R=(Room)metroRooms.elementAt(CMLib.dice().roll(1,metroRooms.size(),-1)); if(R instanceof GridLocale) return ((GridLocale)R).getRandomGridChild(); return R; }*/ final RoomnumberSet metroRoomIDSet=this.metroRoomIDSet; if(metroRoomIDSet != null) { String roomID=metroRoomIDSet.random(); if((roomID!=null) &&(!roomID.startsWith(Name())) &&(roomID.startsWith(Name().toUpperCase()))) roomID=Name()+roomID.substring(Name().length()); final Room R=CMLib.map().getRoom(roomID); if(R instanceof GridLocale) return ((GridLocale)R).getRandomGridChild(); if(R==null) Log.errOut("StdArea","Unable to random-metro-find: "+roomID); return R; } return null; } @Override public Enumeration<Room> getProperMap() { return new CompleteRoomEnumerator(new IteratorEnumeration<Room>(properRooms.values().iterator())); } @Override public Enumeration<Room> getFilledProperMap() { final Enumeration<Room> r=getProperMap(); final List<Room> V=new LinkedList<Room>(); for(;r.hasMoreElements();) { final Room R=r.nextElement(); if((R!=null) &&(!V.contains(R))) { V.add(R); for(final Room R2 : R.getSky()) { if(R2 instanceof GridLocale) { for(final Room R3 : ((GridLocale)R2).getAllRoomsFilled()) { if(!V.contains(R3)) V.add(R3); } } else if(!V.contains(R2)) V.add(R2); } } } return new IteratorEnumeration<Room>(V.iterator()); } @Override public Enumeration<Room> getCompleteMap() { return getProperMap(); } @Override public Enumeration<Room> getFilledCompleteMap() { return getFilledProperMap(); } @Override public Enumeration<Room> getMetroMap() { final MultiEnumeration<Room> multiEnumerator = new MultiEnumeration<Room>(new IteratorEnumeration<Room>(properRooms.values().iterator())); for(final Iterator<Area> a=getChildrenReverseIterator();a.hasNext();) multiEnumerator.addEnumeration(a.next().getMetroMap()); return new CompleteRoomEnumerator(multiEnumerator); } @Override public Enumeration<String> subOps() { return subOps.elements(); } public SLinkedList<Area> loadAreas(final Collection<String> loadableSet) { final SLinkedList<Area> finalSet = new SLinkedList<Area>(); for (final String areaName : loadableSet) { final Area A = CMLib.map().getArea(areaName); if (A == null) continue; finalSet.add(A); } return finalSet; } protected final Iterator<Area> getParentsIterator() { return parents.iterator(); } protected final Iterator<Area> getParentsReverseIterator() { return parents.descendingIterator(); } protected final Iterator<Area> getChildrenIterator() { return children.iterator(); } protected final Iterator<Area> getChildrenReverseIterator() { return children.descendingIterator(); } @Override public Enumeration<Area> getChildren() { return new IteratorEnumeration<Area>(getChildrenIterator()); } @Override public Area getChild(final String named) { for(final Iterator<Area> i=getChildrenIterator(); i.hasNext();) { final Area A=i.next(); if((A.name().equalsIgnoreCase(named)) ||(A.Name().equalsIgnoreCase(named))) return A; } return null; } @Override public boolean isChild(final Area area) { for(final Iterator<Area> i=getChildrenIterator(); i.hasNext();) { if(i.next().equals(area)) return true; } return false; } @Override public boolean isChild(final String named) { for(final Iterator<Area> i=getChildrenIterator(); i.hasNext();) { final Area A=i.next(); if((A.name().equalsIgnoreCase(named)) ||(A.Name().equalsIgnoreCase(named))) return true; } return false; } @Override public void addChild(final Area area) { if(!canChild(area)) return; if(area.Name().equalsIgnoreCase(Name())) return; for(final Iterator<Area> i=getChildrenIterator(); i.hasNext();) { final Area A=i.next(); if(A.Name().equalsIgnoreCase(area.Name())) { children.remove(A); break; } } children.add(area); if(getTimeObj()!=CMLib.time().globalClock()) area.setTimeObj(getTimeObj()); } @Override public void removeChild(final Area area) { if(isChild(area)) children.remove(area); } // child based circular reference check @Override public boolean canChild(final Area area) { if(area instanceof BoardableShip) return false; if(parents != null) { for (final Area A : parents) { if(A==area) return false; if(!A.canChild(area)) return false; } } return true; } // Parent @Override public Enumeration<Area> getParents() { return new IteratorEnumeration<Area>(getParentsIterator()); } @Override public List<Area> getParentsRecurse() { final LinkedList<Area> V=new LinkedList<Area>(); for(final Iterator<Area> a=getParentsIterator();a.hasNext();) { final Area A=a.next(); V.add(A); V.addAll(A.getParentsRecurse()); } return V; } @Override public Area getParent(final String named) { for(final Iterator<Area> a=getParentsIterator();a.hasNext();) { final Area A=a.next(); if((A.name().equalsIgnoreCase(named)) ||(A.Name().equalsIgnoreCase(named))) return A; } return null; } @Override public boolean isParent(final Area area) { for(final Iterator<Area> a=getParentsIterator();a.hasNext();) { final Area A=a.next(); if(A == area) return true; } return false; } @Override public boolean isParent(final String named) { for(final Iterator<Area> a=getParentsIterator();a.hasNext();) { final Area A=a.next(); if((A.name().equalsIgnoreCase(named)) ||(A.Name().equalsIgnoreCase(named))) return true; } return false; } @Override public void addParent(final Area area) { derivedClimate=CLIMASK_INHERIT; derivedAtmo=ATMOSPHERE_INHERIT; derivedTheme=THEME_INHERIT; if(!canParent(area)) return; if(area.Name().equalsIgnoreCase(Name())) return; for(final Iterator<Area> i=getParentsIterator(); i.hasNext();) { final Area A=i.next(); if(A.Name().equalsIgnoreCase(area.Name())) { parents.remove(A); break; } } parents.add(area); } @Override public void removeParent(final Area area) { derivedClimate=CLIMASK_INHERIT; derivedAtmo=ATMOSPHERE_INHERIT; derivedTheme=THEME_INHERIT; if(isParent(area)) parents.remove(area); } @Override public boolean canParent(final Area area) { if(this instanceof BoardableShip) return false; if(children != null) { for (final Area A : children) { if(A==area) return false; if(!A.canParent(area)) return false; } } return true; } @Override public String L(final String str, final String... xs) { return CMLib.lang().fullSessionTranslation(str, xs); } @Override public int getSaveStatIndex() { return (xtraValues == null) ? getStatCodes().length : getStatCodes().length - xtraValues.length; } protected static final String[] STDAREACODES={"CLASS", "CLIMATE", "DESCRIPTION", "TEXT", "THEME", "BLURBS", "PREJUDICE", "BUDGET", "DEVALRATE", "INVRESETRATE", "IGNOREMASK", "PRICEMASKS", "ATMOSPHERE", "AUTHOR", "NAME", "PLAYERLEVEL", "PASSIVEMINS" }; private static String[] codes=null; @Override public String[] getStatCodes() { if(codes==null) codes=CMProps.getStatCodesList(STDAREACODES,this); return codes; } @Override public boolean isStat(final String code) { return CMParms.indexOf(getStatCodes(), code.toUpperCase().trim()) >= 0; } protected int getCodeNum(final String code) { return CMParms.indexOf(getStatCodes(), code.toUpperCase()); } @Override public String getStat(final String code) { switch(getCodeNum(code)) { case 0: return ID(); case 1: return "" + getClimateTypeCode(); case 2: return description(); case 3: return text(); case 4: return "" + getThemeCode(); case 5: return "" + CMLib.xml().getXMLList(blurbFlags.toStringVector(" ")); case 6: return prejudiceFactors(); case 7: return budget(); case 8: return devalueRate(); case 9: return "" + invResetRate(); case 10: return ignoreMask(); case 11: return CMParms.toListString(itemPricingAdjustments()); case 12: return "" + getAtmosphereCode(); case 13: return getAuthorID(); case 14: return name(); case 15: return ""+playerLevel; case 16: return Long.toString(this.passiveLapseMs / 60000); default: return CMProps.getStatCodeExtensionValue(getStatCodes(), xtraValues, code); } } @Override public void setStat(final String code, final String val) { switch(getCodeNum(code)) { case 0: return; case 1: setClimateType((CMath.s_int(val) < 0) ? -1 : CMath.s_parseBitIntExpression(Places.CLIMATE_DESCS, val)); break; case 2: setDescription(val); break; case 3: setMiscText(val); break; case 4: setTheme(CMath.s_parseBitIntExpression(Area.THEME_BIT_NAMES, val)); break; case 5: { if(val.startsWith("+")) addBlurbFlag(val.substring(1)); else if(val.startsWith("-")) delBlurbFlag(val.substring(1)); else { blurbFlags=new STreeMap<String,String>(); final List<String> V=CMLib.xml().parseXMLList(val); for(final String s : V) { final int x=s.indexOf(' '); if(x<0) blurbFlags.put(s,""); else blurbFlags.put(s.substring(0,x),s.substring(x+1)); } } break; } case 6: setPrejudiceFactors(val); break; case 7: setBudget(val); break; case 8: setDevalueRate(val); break; case 9: setInvResetRate(CMath.s_parseIntExpression(val)); break; case 10: setIgnoreMask(val); break; case 11: setItemPricingAdjustments((val.trim().length() == 0) ? new String[0] : CMParms.toStringArray(CMParms.parseCommas(val, true))); break; case 12: { if (CMath.isMathExpression(val)) setAtmosphere(CMath.s_parseIntExpression(val)); final int matCode = RawMaterial.CODES.FIND_IgnoreCase(val); if (matCode >= 0) setAtmosphere(matCode); break; } case 13: setAuthorID(val); break; case 14: setName(val); break; case 15: setPlayerLevel((int)Math.round(CMath.parseMathExpression(val))); break; case 16: { long mins=CMath.parseLongExpression(val); if(mins > 0) { if(mins > Integer.MAX_VALUE) mins=Integer.MAX_VALUE; passiveLapseMs = mins * 60 * 1000; } break; } default: CMProps.setStatCodeExtensionValue(getStatCodes(), xtraValues, code, val); break; } } @Override public boolean sameAs(final Environmental E) { if(!(E instanceof StdArea)) return false; final String[] codes=getStatCodes(); for(int i=0;i<codes.length;i++) { if(!E.getStat(codes[i]).equals(getStat(codes[i]))) return false; } return true; } }
com/planet_ink/coffee_mud/Areas/StdArea.java
package com.planet_ink.coffee_mud.Areas; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.Area.CompleteRoomEnumerator; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.TimeClock.TimePeriod; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.Basic.StdItem; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Libraries.interfaces.GenericBuilder; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.util.*; /* Copyright 2002-2019 Bo Zimmerman Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ public class StdArea implements Area { @Override public String ID() { return "StdArea"; } protected String name = "the area"; protected String description = ""; protected String miscText = ""; protected String archPath = ""; protected String imageName = ""; protected int playerLevel = 0; protected int theme = Area.THEME_INHERIT; protected int atmosphere = Room.ATMOSPHERE_INHERIT; protected int derivedTheme = Area.THEME_INHERIT; protected int derivedAtmo = Places.ATMOSPHERE_INHERIT; protected int climask = Area.CLIMASK_NORMAL; protected int derivedClimate = Places.CLIMASK_INHERIT; protected int tickStatus = Tickable.STATUS_NOT; protected long expirationDate = 0; protected long passiveLapseMs = DEFAULT_TIME_PASSIVE_LAPSE; protected long lastPlayerTime = System.currentTimeMillis() + (passiveLapseMs/2); protected State flag = State.ACTIVE; protected String[] xtraValues = null; protected String author = ""; protected String currency = ""; protected double[] devalueRate = null; protected String budget = ""; protected String ignoreMask = ""; protected String prejudiceFactors= ""; protected int invResetRate = 0; protected boolean amDestroyed = false; protected PhyStats phyStats = (PhyStats)CMClass.getCommon("DefaultPhyStats"); protected PhyStats basePhyStats = (PhyStats)CMClass.getCommon("DefaultPhyStats"); protected STreeMap<String,String> blurbFlags = new STreeMap<String,String>(); protected STreeMap<String, Room> properRooms = new STreeMap<String, Room>(new RoomIDComparator()); protected RoomnumberSet properRoomIDSet= null; protected RoomnumberSet metroRoomIDSet = null; protected SLinkedList<Area> children = new SLinkedList<Area>(); protected SLinkedList<Area> parents = new SLinkedList<Area>(); protected SVector<Ability> affects = new SVector<Ability>(1); protected SVector<Behavior> behaviors = new SVector<Behavior>(1); protected SVector<String> subOps = new SVector<String>(1); protected SVector<ScriptingEngine>scripts = new SVector<ScriptingEngine>(1); protected Area me = this; protected TimeClock myClock = null; protected Climate climateObj = (Climate)CMClass.getCommon("DefaultClimate"); protected String[] itemPricingAdjustments = new String[0]; protected final static int[] emptyStats = new int[Area.Stats.values().length]; protected final static String[] empty = new String[0]; protected static volatile Area lastComplainer = null; @Override public void initializeClass() { } @Override public long flags() { return 0; } @Override public void setAuthorID(final String authorID) { author = authorID; } @Override public String getAuthorID() { return author; } @Override public void setCurrency(final String newCurrency) { if(currency.length()>0) { CMLib.beanCounter().unloadCurrencySet(currency); currency=newCurrency; for(final Enumeration<Area> e=CMLib.map().areas();e.hasMoreElements();) CMLib.beanCounter().getCurrencySet(e.nextElement().getCurrency()); } else { currency=newCurrency; CMLib.beanCounter().getCurrencySet(currency); } } @Override public String getCurrency() { return currency; } @Override public int getAtmosphereCode() { return atmosphere; } @Override public void setAtmosphere(final int resourceCode) { atmosphere=resourceCode; derivedAtmo=ATMOSPHERE_INHERIT; } @Override public int getAtmosphere() { if(derivedAtmo!=ATMOSPHERE_INHERIT) return derivedAtmo; final Stack<Area> areasToDo=new Stack<Area>(); areasToDo.push(this); while(areasToDo.size()>0) { final Area A=areasToDo.pop(); derivedAtmo=A.getAtmosphereCode(); if(derivedAtmo!=ATMOSPHERE_INHERIT) return derivedAtmo; for(final Enumeration<Area> a=A.getParents();a.hasMoreElements();) areasToDo.push(a.nextElement()); } derivedAtmo=RawMaterial.RESOURCE_AIR; return derivedAtmo; } @Override public String getBlurbFlag(final String flag) { if((flag==null)||(flag.trim().length()==0)) return null; return blurbFlags.get(flag.toUpperCase().trim()); } @Override public int numBlurbFlags() { return blurbFlags.size(); } @Override public int numAllBlurbFlags() { int num=numBlurbFlags(); for(final Iterator<Area> i=getParentsIterator();i.hasNext();) num += i.next().numAllBlurbFlags(); return num; } @Override public Enumeration<String> areaBlurbFlags() { return new IteratorEnumeration<String>(blurbFlags.keySet().iterator()); } @Override public void addBlurbFlag(String flagPlusDesc) { if(flagPlusDesc==null) return; flagPlusDesc=flagPlusDesc.trim(); if(flagPlusDesc.length()==0) return; final int x=flagPlusDesc.indexOf(' '); String flag=null; if(x>=0) { flag=flagPlusDesc.substring(0,x).toUpperCase(); flagPlusDesc=flagPlusDesc.substring(x).trim(); } else { flag=flagPlusDesc.toUpperCase().trim(); flagPlusDesc=""; } if(getBlurbFlag(flag)==null) blurbFlags.put(flag,flagPlusDesc); } @Override public void delBlurbFlag(String flagOnly) { if(flagOnly==null) return; flagOnly=flagOnly.toUpperCase().trim(); if(flagOnly.length()==0) return; blurbFlags.remove(flagOnly); } @Override public long expirationDate() { return expirationDate; } @Override public void setExpirationDate(final long time) { expirationDate = time; } @Override public void setClimateObj(final Climate obj) { if(obj != null) climateObj = obj; } @Override public Climate getClimateObj() { if(climateObj == null) climateObj = (Climate)CMClass.getCommon("DefaultClimate"); return climateObj; } @Override public void setTimeObj(final TimeClock obj) { if(obj != null) { myClock = obj; for(final Iterator<Area> i=getChildrenIterator(); i.hasNext();) { final Area A=i.next(); A.setTimeObj(obj); } } } @Override public TimeClock getTimeObj() { if(myClock==null) { if((this.parents != null)&&(this.parents.size()>0)) myClock=this.parents.iterator().next().getTimeObj(); else myClock=CMLib.time().globalClock(); } return myClock; } public StdArea() { super(); //CMClass.bumpCounter(this,CMClass.CMObjectType.AREA);//removed for mem & perf xtraValues=CMProps.getExtraStatCodesHolder(this); } /* protected void finalize() { CMClass.unbumpCounter(this, CMClass.CMObjectType.AREA); }// removed for mem & perf */ @Override public void destroy() { CMLib.map().registerWorldObjectDestroyed(this,null,this); phyStats=(PhyStats)CMClass.getCommon("DefaultPhyStats"); basePhyStats=phyStats; amDestroyed=true; miscText=null; imageName=null; affects=new SVector<Ability>(1); behaviors=new SVector<Behavior>(1); scripts=new SVector<ScriptingEngine>(1); author=null; currency=null; children=new SLinkedList<Area>(); parents=new SLinkedList<Area>(); blurbFlags=new STreeMap<String,String>(); subOps=new SVector<String>(1); properRooms=new STreeMap<String, Room>(); //metroRooms=null; myClock=null; climateObj=null; properRoomIDSet=null; metroRoomIDSet=null; author=""; currency=""; devalueRate=null; budget=""; ignoreMask=""; prejudiceFactors=""; derivedClimate=CLIMASK_INHERIT; derivedAtmo=ATMOSPHERE_INHERIT; derivedTheme=THEME_INHERIT; } @Override public boolean amDestroyed() { return amDestroyed; } @Override public boolean isSavable() { return ((!amDestroyed) && (!CMath.bset(flags(),Area.FLAG_INSTANCE_CHILD)) && (CMLib.flags().isSavable(this))); } @Override public void setSavable(final boolean truefalse) { CMLib.flags().setSavable(this, truefalse); } @Override public String name() { if(phyStats().newName()!=null) return phyStats().newName(); return name; } @Override public synchronized RoomnumberSet getProperRoomnumbers() { if(properRoomIDSet==null) properRoomIDSet=(RoomnumberSet)CMClass.getCommon("DefaultRoomnumberSet"); return properRoomIDSet; } @Override public RoomnumberSet getCachedRoomnumbers() { final RoomnumberSet set=(RoomnumberSet)CMClass.getCommon("DefaultRoomnumberSet"); synchronized(properRooms) { for(final Room R : properRooms.values()) { if(R.roomID().length()>0) set.add(R.roomID()); } } return set; } @Override public void setName(final String newName) { if(newName != null) { name=newName.replace('\'', '`'); CMLib.map().renamedArea(this); } } @Override public String Name() { return name; } @Override public PhyStats phyStats() { return phyStats; } @Override public PhyStats basePhyStats() { return basePhyStats; } @Override public void recoverPhyStats() { basePhyStats.copyInto(phyStats); eachEffect(new EachApplicable<Ability>() { @Override public final void apply(final Ability A) { A.affectPhyStats(me, phyStats); } }); } @Override public void setBasePhyStats(final PhyStats newStats) { basePhyStats=(PhyStats)newStats.copyOf(); } @Override public int getThemeCode() { return theme; } @Override public int getTheme() { if(derivedTheme!=THEME_INHERIT) return derivedTheme; final Stack<Area> areasToDo=new Stack<Area>(); areasToDo.push(this); while(areasToDo.size()>0) { final Area A=areasToDo.pop(); derivedTheme=A.getThemeCode(); if(derivedTheme!=THEME_INHERIT) return derivedTheme; for(final Enumeration<Area> a=A.getParents();a.hasMoreElements();) areasToDo.push(a.nextElement()); } derivedTheme=CMProps.getIntVar(CMProps.Int.MUDTHEME); return derivedTheme; } @Override public void setTheme(final int level) { theme=level; derivedTheme=THEME_INHERIT; } @Override public String getArchivePath() { return archPath; } @Override public void setArchivePath(final String pathFile) { archPath = pathFile; } @Override public String image() { return imageName; } @Override public String rawImage() { return imageName; } @Override public void setImage(final String newImage) { imageName = newImage; } @Override public void setAreaState(final State newState) { if((newState==State.ACTIVE) &&(!CMLib.threads().isTicking(this,Tickable.TICKID_AREA))) { CMLib.threads().startTickDown(this,Tickable.TICKID_AREA,1); if(!CMLib.threads().isTicking(this, Tickable.TICKID_AREA)) Log.errOut("StdArea","Area "+name()+" failed to start ticking."); } flag=newState; derivedClimate=CLIMASK_INHERIT; derivedAtmo=ATMOSPHERE_INHERIT; derivedTheme=THEME_INHERIT; } @Override public State getAreaState() { return flag; } @Override public boolean amISubOp(final String username) { for(int s=subOps.size()-1;s>=0;s--) { if(subOps.elementAt(s).equalsIgnoreCase(username)) return true; } return false; } @Override public String getSubOpList() { final StringBuffer list=new StringBuffer(""); for(int s=subOps.size()-1;s>=0;s--) { final String str=subOps.elementAt(s); list.append(str); list.append(";"); } return list.toString(); } @Override public void setSubOpList(final String list) { subOps.clear(); subOps.addAll(CMParms.parseSemicolons(list,true)); } @Override public void addSubOp(final String username) { subOps.addElement(username); } @Override public void delSubOp(final String username) { for(int s=subOps.size()-1;s>=0;s--) { if(subOps.elementAt(s).equalsIgnoreCase(username)) subOps.removeElementAt(s); } } @Override public String getNewRoomID(final Room startRoom, final int direction) { int highest=Integer.MIN_VALUE; int lowest=Integer.MAX_VALUE; final LongSet set=new LongSet(); try { String roomID=null; int newnum=0; final String name=Name().toUpperCase(); for(final Enumeration<String> i=CMLib.map().roomIDs();i.hasMoreElements();) { roomID=i.nextElement(); if((roomID.length()>0)&&(roomID.startsWith(name+"#"))) { roomID=roomID.substring(name.length()+1); if(CMath.isInteger(roomID)) { newnum=CMath.s_int(roomID); if(newnum>=0) { if(newnum>=highest) highest=newnum; if(newnum<=lowest) lowest=newnum; set.add(Long.valueOf(newnum)); } } } } } catch (final NoSuchElementException e) { } if(highest<0) { for(int i=0;i<Integer.MAX_VALUE;i++) { if(((CMLib.map().getRoom(Name()+"#"+i))==null) &&(getRoom(Name()+"#"+i)==null)) return Name()+"#"+i; } } if(lowest>highest) { lowest=highest+1; } for(int i=lowest;i<=highest+1000;i++) { if((!set.contains(i)) &&(CMLib.map().getRoom(Name()+"#"+i)==null) &&(getRoom(Name()+"#"+i)==null)) return Name()+"#"+i; } return Name()+"#"+(int)Math.round(Math.random()*Integer.MAX_VALUE); } @Override public CMObject newInstance() { if(CMSecurity.isDisabled(CMSecurity.DisFlag.FATAREAS) &&(ID().equals("StdArea"))) { final Area A=CMClass.getAreaType("StdThinArea"); if(A!=null) return A; } try { return this.getClass().newInstance(); } catch(final Exception e) { Log.errOut(ID(),e); } return new StdArea(); } @Override public boolean isGeneric() { return false; } protected void cloneFix(final StdArea areaA) { me=this; basePhyStats=(PhyStats)areaA.basePhyStats().copyOf(); phyStats=(PhyStats)areaA.phyStats().copyOf(); properRooms =new STreeMap<String, Room>(new RoomIDComparator()); properRoomIDSet=null; metroRoomIDSet =null; parents=areaA.parents.copyOf(); children=areaA.children.copyOf(); if(areaA.blurbFlags!=null) blurbFlags=areaA.blurbFlags.copyOf(); affects=new SVector<Ability>(1); behaviors=new SVector<Behavior>(1); scripts=new SVector<ScriptingEngine>(1); derivedClimate=CLIMASK_INHERIT; derivedTheme=THEME_INHERIT; derivedAtmo=ATMOSPHERE_INHERIT; for(final Enumeration<Behavior> e=areaA.behaviors();e.hasMoreElements();) { final Behavior B=e.nextElement(); if(B!=null) behaviors.addElement((Behavior)B.copyOf()); } for(final Enumeration<Ability> a=areaA.effects();a.hasMoreElements();) { final Ability A=a.nextElement(); if(A!=null) affects.addElement((Ability)A.copyOf()); } ScriptingEngine SE=null; for(final Enumeration<ScriptingEngine> e=areaA.scripts();e.hasMoreElements();) { SE=e.nextElement(); if(SE!=null) addScript((ScriptingEngine)SE.copyOf()); } setSubOpList(areaA.getSubOpList()); } @Override public CMObject copyOf() { try { final StdArea E=(StdArea)this.clone(); //CMClass.bumpCounter(this,CMClass.CMObjectType.AREA);//removed for mem & perf E.xtraValues=(xtraValues==null)?null:(String[])xtraValues.clone(); E.cloneFix(this); return E; } catch(final CloneNotSupportedException e) { return this.newInstance(); } } @Override public String displayText() { return ""; } @Override public void setDisplayText(final String newDisplayText) { } @Override public String displayText(final MOB viewerMob) { return displayText(); } @Override public String name(final MOB viewerMob) { return name(); } @Override public String finalPrejudiceFactors() { final String s=finalPrejudiceFactors(this); if(s.length()>0) return s; return CMProps.getVar(CMProps.Str.IGNOREMASK); } protected String finalPrejudiceFactors(final Area A) { if(A.prejudiceFactors().length()>0) return A.prejudiceFactors(); for(final Enumeration<Area> i=A.getParents();i.hasMoreElements();) { final String s=finalPrejudiceFactors(i.nextElement()); if(s.length()!=0) return s; } return ""; } @Override public String prejudiceFactors() { return prejudiceFactors; } @Override public void setPrejudiceFactors(final String factors) { prejudiceFactors = factors; } @Override public String[] finalItemPricingAdjustments() { final String[] s=finalItemPricingAdjustments(this); if(s.length>0) return s; return CMLib.coffeeShops().parseItemPricingAdjustments(CMProps.getVar(CMProps.Str.PRICEFACTORS).trim()); } protected String[] finalItemPricingAdjustments(final Area A) { if(A.itemPricingAdjustments().length>0) return A.itemPricingAdjustments(); for(final Enumeration<Area> i=A.getParents();i.hasMoreElements();) { final String[] s=finalItemPricingAdjustments(i.nextElement()); if(s.length!=0) return s; } return empty; } @Override public String[] itemPricingAdjustments() { return itemPricingAdjustments; } @Override public void setItemPricingAdjustments(final String[] factors) { itemPricingAdjustments = factors; } @Override public String finalIgnoreMask() { final String s=finalIgnoreMask(this); if(s.length()>0) return s; return CMProps.getVar(CMProps.Str.IGNOREMASK); } protected String finalIgnoreMask(final Area A) { if(A.ignoreMask().length()>0) return A.ignoreMask(); for(final Enumeration<Area> i=A.getParents();i.hasMoreElements();) { final String s=finalIgnoreMask(i.nextElement()); if(s.length()!=0) return s; } return ""; } @Override public String ignoreMask() { return ignoreMask; } @Override public void setIgnoreMask(final String factors) { ignoreMask = factors; } @Override public Pair<Long, TimePeriod> finalBudget() { final Pair<Long, TimePeriod> budget=finalAreaBudget(this); if(budget != null) return budget; return CMLib.coffeeShops().parseBudget(CMProps.getVar(CMProps.Str.BUDGET)); } protected Pair<Long, TimePeriod> finalAreaBudget(final Area A) { if(A.budget().length()>0) return CMLib.coffeeShops().parseBudget(A.budget()); for(final Enumeration<Area> i=A.getParents();i.hasMoreElements();) { final Pair<Long, TimePeriod> budget=finalAreaBudget(i.nextElement()); if(budget != null) return budget; } return null; } @Override public String budget() { return budget; } @Override public void setBudget(final String factors) { budget = factors; } @Override public double[] finalDevalueRate() { final double[] rate=finalAreaDevalueRate(this); if(rate != null) return rate; return CMLib.coffeeShops().parseDevalueRate(CMProps.getVar(CMProps.Str.DEVALUERATE)); } protected double[] finalAreaDevalueRate(final Area A) { if(A.devalueRate().length()>0) return CMLib.coffeeShops().parseDevalueRate(A.devalueRate()); for(final Enumeration<Area> i=A.getParents();i.hasMoreElements();) { final double[] rate=finalAreaDevalueRate(i.nextElement()); if(rate != null) return rate; } return null; } @Override public String devalueRate() { return (devalueRate == null) ? "" : (devalueRate[0] + " " + devalueRate[1]); } @Override public void setDevalueRate(final String factors) { devalueRate = CMLib.coffeeShops().parseDevalueRate(factors); } @Override public int invResetRate() { return invResetRate; } @Override public void setInvResetRate(final int ticks) { invResetRate = ticks; } @Override public int finalInvResetRate() { final int x=finalInvResetRate(this); if(x!=0) return x; return CMath.s_int(CMProps.getVar(CMProps.Str.INVRESETRATE)); } protected int finalInvResetRate(final Area A) { if(A.invResetRate()!=0) return A.invResetRate(); for(final Enumeration<Area> i=A.getParents();i.hasMoreElements();) { final int x=finalInvResetRate(i.nextElement()); if(x!=0) return x; } return 0; } @Override public int compareTo(final CMObject o) { return CMClass.classID(this).compareToIgnoreCase(CMClass.classID(o)); } @Override public String miscTextFormat() { return CMParms.FORMAT_UNDEFINED; } @Override public String text() { return CMLib.coffeeMaker().getPropertiesStr(this,true); } @Override public void setMiscText(final String newMiscText) { miscText=""; if(newMiscText.trim().length()>0) CMLib.coffeeMaker().setPropertiesStr(this,newMiscText,true); derivedClimate=CLIMASK_INHERIT; derivedAtmo=ATMOSPHERE_INHERIT; derivedTheme=THEME_INHERIT; } @Override public String description() { return description; } @Override public void setDescription(final String newDescription) { description = newDescription; } @Override public String description(final MOB viewerMob) { return description(); } @Override public int getClimateTypeCode() { return climask; } @Override public void setClimateType(final int newClimateType) { climask=newClimateType; derivedClimate=CLIMASK_INHERIT; } @Override public int getClimateType() { if(derivedClimate!=CLIMASK_INHERIT) return derivedClimate; final Stack<Area> areasToDo=new Stack<Area>(); areasToDo.push(this); while(areasToDo.size()>0) { final Area A=areasToDo.pop(); derivedClimate=A.getClimateTypeCode(); if(derivedClimate!=CLIMASK_INHERIT) return derivedClimate; for(final Enumeration<Area> a=A.getParents();a.hasMoreElements();) areasToDo.push(a.nextElement()); } derivedClimate=Places.CLIMASK_NORMAL; return derivedClimate; } @Override public boolean okMessage(final Environmental myHost, final CMMsg msg) { MsgListener N=null; for(int b=0;b<numBehaviors();b++) { N=fetchBehavior(b); if((N!=null)&&(!N.okMessage(this,msg))) return false; } for(int s=0;s<numScripts();s++) { N=fetchScript(s); if((N!=null)&&(!N.okMessage(this,msg))) return false; } for(final Enumeration<Ability> a=effects();a.hasMoreElements();) { N=a.nextElement(); if((N!=null)&&(!N.okMessage(this,msg))) return false; } if(!msg.source().isMonster()) { lastPlayerTime=System.currentTimeMillis(); if((flag==State.PASSIVE) &&((msg.sourceMinor()==CMMsg.TYP_ENTER) ||(msg.sourceMinor()==CMMsg.TYP_LEAVE) ||(msg.sourceMinor()==CMMsg.TYP_FLEE))) flag=State.ACTIVE; } if((flag==State.FROZEN)||(flag==State.STOPPED)||(!CMLib.flags().allowsMovement(this))) { if((msg.sourceMinor()==CMMsg.TYP_ENTER) ||(msg.sourceMinor()==CMMsg.TYP_LEAVE) ||(msg.sourceMinor()==CMMsg.TYP_FLEE)) return false; } if(parents!=null) { for (final Area area : parents) { if(!area.okMessage(myHost,msg)) return false; } } if((getThemeCode()>0)&&(!CMath.bset(getThemeCode(),Area.THEME_FANTASY))) { if((CMath.bset(msg.sourceMajor(),CMMsg.MASK_MAGIC)) ||(CMath.bset(msg.targetMajor(),CMMsg.MASK_MAGIC)) ||(CMath.bset(msg.othersMajor(),CMMsg.MASK_MAGIC))) { Room room=null; if((msg.target() instanceof MOB) &&(((MOB)msg.target()).location()!=null)) room=((MOB)msg.target()).location(); else if(msg.source().location()!=null) room=msg.source().location(); if(room!=null) { if(room.getArea()==this) room.showHappens(CMMsg.MSG_OK_ACTION,L("Magic doesn't seem to work here.")); else room.showHappens(CMMsg.MSG_OK_ACTION,L("Magic doesn't seem to work there.")); } return false; } } else if((getTheme()>0)&&(!CMath.bset(getTheme(),Area.THEME_TECHNOLOGY))) { switch(msg.sourceMinor()) { case CMMsg.TYP_BUY: case CMMsg.TYP_BID: case CMMsg.TYP_CLOSE: case CMMsg.TYP_DEPOSIT: case CMMsg.TYP_DROP: case CMMsg.TYP_LOOK: case CMMsg.TYP_EXAMINE: case CMMsg.TYP_GET: case CMMsg.TYP_PUSH: case CMMsg.TYP_PULL: case CMMsg.TYP_GIVE: case CMMsg.TYP_OPEN: case CMMsg.TYP_PUT: case CMMsg.TYP_SELL: case CMMsg.TYP_VALUE: case CMMsg.TYP_REMOVE: case CMMsg.TYP_VIEW: case CMMsg.TYP_WITHDRAW: case CMMsg.TYP_BORROW: break; case CMMsg.TYP_POWERCURRENT: return false; default: if(msg.tool() instanceof Electronics) { Room room=null; if((msg.target() instanceof MOB) &&(((MOB)msg.target()).location()!=null)) room=((MOB)msg.target()).location(); else if(msg.source().location()!=null) room=msg.source().location(); if(room!=null) room.showHappens(CMMsg.MSG_OK_VISUAL,L("Technology doesn't seem to work here.")); return false; } break; } } return true; } @Override public void executeMsg(final Environmental myHost, final CMMsg msg) { eachBehavior(new EachApplicable<Behavior>() { @Override public final void apply(final Behavior B) { B.executeMsg(me, msg); } }); eachScript(new EachApplicable<ScriptingEngine>() { @Override public final void apply(final ScriptingEngine S) { S.executeMsg(me, msg); } }); eachEffect(new EachApplicable<Ability>() { @Override public final void apply(final Ability A) { A.executeMsg(me, msg); } }); if((msg.sourceMinor()==CMMsg.TYP_RETIRE) &&(amISubOp(msg.source().Name()))) delSubOp(msg.source().Name()); if(parents!=null) { for (final Area area : parents) area.executeMsg(myHost,msg); } } @Override public int getTickStatus() { return tickStatus; } @Override public boolean tick(final Tickable ticking, final int tickID) { if((flag==State.STOPPED)||(amDestroyed())) return false; tickStatus=Tickable.STATUS_START; if(tickID==Tickable.TICKID_AREA) { if((flag==State.ACTIVE) &&((System.currentTimeMillis()-lastPlayerTime)>passiveLapseMs)) { if(CMSecurity.isDisabled(CMSecurity.DisFlag.PASSIVEAREAS) &&(!CMath.bset(flags(), Area.FLAG_INSTANCE_CHILD))) lastPlayerTime=System.currentTimeMillis(); else flag=State.PASSIVE; } tickStatus=Tickable.STATUS_ALIVE; getClimateObj().tick(this,tickID); tickStatus=Tickable.STATUS_REBIRTH; getTimeObj().tick(this,tickID); tickStatus=Tickable.STATUS_BEHAVIOR; eachBehavior(new EachApplicable<Behavior>() { @Override public final void apply(final Behavior B) { B.tick(ticking,tickID); } }); tickStatus=Tickable.STATUS_SCRIPT; eachScript(new EachApplicable<ScriptingEngine>() { @Override public final void apply(final ScriptingEngine S) { S.tick(ticking,tickID); } }); tickStatus=Tickable.STATUS_AFFECT; eachEffect(new EachApplicable<Ability>() { @Override public final void apply(final Ability A) { if (!A.tick(ticking, tickID)) A.unInvoke(); } }); } tickStatus=Tickable.STATUS_NOT; return true; } @Override public void affectPhyStats(final Physical affected, final PhyStats affectableStats) { final int senses=phyStats.sensesMask()&(~(PhyStats.SENSE_UNLOCATABLE|PhyStats.CAN_NOT_SEE)); if(senses>0) affectableStats.setSensesMask(affectableStats.sensesMask()|senses); int disposition=phyStats().disposition() &((~(PhyStats.IS_SLEEPING|PhyStats.IS_HIDDEN))); if((affected instanceof Room) &&(CMLib.map().hasASky((Room)affected))) { final Climate C=getClimateObj(); if(((C==null) ||(((C.weatherType((Room)affected)==Climate.WEATHER_BLIZZARD) ||(C.weatherType((Room)affected)==Climate.WEATHER_DUSTSTORM)) &&(!CMSecurity.isDisabled(CMSecurity.DisFlag.DARKWEATHER))) ||((getTimeObj().getTODCode()==TimeClock.TimeOfDay.NIGHT)&&(!CMSecurity.isDisabled(CMSecurity.DisFlag.DARKNIGHTS)))) &&((disposition&PhyStats.IS_LIGHTSOURCE)==0)) disposition=disposition|PhyStats.IS_DARK; } if(disposition>0) affectableStats.setDisposition(affectableStats.disposition()|disposition); affectableStats.setWeight(affectableStats.weight()+phyStats().weight()); // well, that's weird eachEffect(new EachApplicable<Ability>() { @Override public final void apply(final Ability A) { if (A.bubbleAffect()) A.affectPhyStats(affected, affectableStats); } }); } @Override public void affectCharStats(final MOB affectedMob, final CharStats affectableStats) { eachEffect(new EachApplicable<Ability>() { @Override public final void apply(final Ability A) { if (A.bubbleAffect()) A.affectCharStats(affectedMob, affectableStats); } }); } @Override public void affectCharState(final MOB affectedMob, final CharState affectableMaxState) { eachEffect(new EachApplicable<Ability>() { @Override public final void apply(final Ability A) { if (A.bubbleAffect()) A.affectCharState(affectedMob, affectableMaxState); } }); } @Override public void addNonUninvokableEffect(final Ability to) { if(to==null) return; if(fetchEffect(to.ID())!=null) return; to.makeNonUninvokable(); to.makeLongLasting(); affects.addElement(to); to.setAffectedOne(this); } @Override public void addEffect(final Ability to) { if(to==null) return; if(fetchEffect(to.ID())!=null) return; affects.addElement(to); to.setAffectedOne(this); } @Override public void delEffect(final Ability to) { final int size=affects.size(); affects.removeElement(to); if(affects.size()<size) to.setAffectedOne(null); } @Override public void eachEffect(final EachApplicable<Ability> applier) { final List<Ability> affects=this.affects; if(affects==null) return; try { for(int a=0;a<affects.size();a++) { final Ability A=affects.get(a); if(A!=null) applier.apply(A); } } catch (final ArrayIndexOutOfBoundsException e) { } } @Override public void delAllEffects(final boolean unInvoke) { for(int a=numEffects()-1;a>=0;a--) { final Ability A=fetchEffect(a); if(A!=null) { if(unInvoke) A.unInvoke(); A.setAffectedOne(null); } } affects.clear(); } @Override public int numEffects() { return (affects==null)?0:affects.size(); } @SuppressWarnings("unchecked") @Override public Enumeration<Ability> effects() { return (affects == null) ? EmptyEnumeration.INSTANCE : affects.elements(); } @Override public Ability fetchEffect(final int index) { try { return affects.elementAt(index); } catch (final java.lang.ArrayIndexOutOfBoundsException x) { } return null; } @Override public Ability fetchEffect(final String ID) { for(final Enumeration<Ability> a=effects();a.hasMoreElements();) { final Ability A=a.nextElement(); if((A!=null)&&(A.ID().equals(ID))) return A; } return null; } @Override public boolean inMyMetroArea(final Area A) { if(A==this) return true; for(final Iterator<Area> i=getChildrenIterator();i.hasNext();) { if(i.next().inMyMetroArea(A)) return true; } return false; } @Override public void fillInAreaRooms() { for(final Enumeration<Room> r=getProperMap();r.hasMoreElements();) { final Room R=r.nextElement(); R.clearSky(); if(R.roomID().length()>0) { if(R instanceof GridLocale) ((GridLocale)R).buildGrid(); } } for(final Enumeration<Room> r=getProperMap();r.hasMoreElements();) { final Room R=r.nextElement(); R.giveASky(0); } } @Override public void fillInAreaRoom(final Room R) { if(R==null) return; R.clearSky(); if(R.roomID().length()>0) { if(R instanceof GridLocale) ((GridLocale)R).buildGrid(); } R.giveASky(0); } /** Manipulation of Behavior objects, which includes * movement, speech, spellcasting, etc, etc.*/ @Override public void addBehavior(final Behavior to) { if(to==null) return; for(final Behavior B : behaviors) { if((B!=null)&&(B.ID().equals(to.ID()))) return; } to.startBehavior(this); behaviors.addElement(to); } @Override public void delBehavior(final Behavior to) { if(behaviors.removeElement(to)) to.endBehavior(this); } @Override public void delAllBehaviors() { behaviors.clear(); } @Override public int numBehaviors() { return behaviors.size(); } @Override public Enumeration<Behavior> behaviors() { return behaviors.elements(); } /** Manipulation of the scripts list */ @Override public void addScript(final ScriptingEngine S) { if(S==null) return; if(!scripts.contains(S)) { ScriptingEngine S2=null; for(int s=0;s<scripts.size();s++) { S2=scripts.elementAt(s); if((S2!=null)&&(S2.getScript().equalsIgnoreCase(S.getScript()))) return; } scripts.addElement(S); } } @Override public void delScript(final ScriptingEngine S) { scripts.removeElement(S); } @Override public int numScripts() { return scripts.size(); } @Override public Enumeration<ScriptingEngine> scripts() { return scripts.elements(); } @Override public ScriptingEngine fetchScript(final int x) { try { return scripts.elementAt(x); } catch (final Exception e) { } return null; } @Override public void delAllScripts() { scripts.clear(); } @Override public void eachScript(final EachApplicable<ScriptingEngine> applier) { final List<ScriptingEngine> scripts=this.scripts; if(scripts!=null) { try { for(int a=0;a<scripts.size();a++) { final ScriptingEngine S=scripts.get(a); if(S!=null) applier.apply(S); } } catch (final ArrayIndexOutOfBoundsException e) { } } } @Override public int maxRange() { return Integer.MAX_VALUE; } @Override public int minRange() { return Integer.MIN_VALUE; } protected void buildAreaIMobStats(final int[] statData, final long[] totalAlignments, final Faction theFaction, final List<Integer> alignRanges, final List<Integer> levelRanges, final MOB mob) { if((mob!=null) &&(mob.isMonster()) &&(!CMLib.flags().isUnattackable(mob))) { final int lvl=mob.basePhyStats().level(); levelRanges.add(Integer.valueOf(lvl)); if((theFaction!=null)&&(mob.fetchFaction(theFaction.factionID())!=Integer.MAX_VALUE)) { alignRanges.add(Integer.valueOf(mob.fetchFaction(theFaction.factionID()))); totalAlignments[0]+=mob.fetchFaction(theFaction.factionID()); } statData[Area.Stats.POPULATION.ordinal()]++; statData[Area.Stats.TOTAL_LEVELS.ordinal()]+=lvl; if(!CMLib.flags().isAnimalIntelligence(mob)) { statData[Area.Stats.TOTAL_INTELLIGENT_LEVELS.ordinal()]+=lvl; statData[Area.Stats.INTELLIGENT_MOBS.ordinal()]++; } else { statData[Area.Stats.ANIMALS.ordinal()]++; } if(lvl<statData[Area.Stats.MIN_LEVEL.ordinal()]) statData[Area.Stats.MIN_LEVEL.ordinal()]=lvl; if(lvl>statData[Area.Stats.MAX_LEVEL.ordinal()]) statData[Area.Stats.MAX_LEVEL.ordinal()]=lvl; /* if(CMLib.factions().isAlignmentLoaded(Faction.Align.GOOD)) { if(CMLib.flags().isGood(mob)) statData[Area.Stats.GOOD_MOBS.ordinal()]++; else if(CMLib.flags().isEvil(mob)) statData[Area.Stats.EVIL_MOBS.ordinal()]++; } if(CMLib.factions().isAlignmentLoaded(Faction.Align.LAWFUL)) { if(CMLib.flags().isLawful(mob)) statData[Area.Stats.LAWFUL_MOBS.ordinal()]++; else if(CMLib.flags().isChaotic(mob)) statData[Area.Stats.CHAOTIC_MOBS.ordinal()]++; } if(mob.fetchEffect("Prop_ShortEffects")!=null) statData[Area.Stats.BOSS_MOBS.ordinal()]++; if(" Humanoid Elf Dwarf Halfling HalfElf ".indexOf(" "+mob.charStats().getMyRace().racialCategory()+" ")>=0) statData[Area.Stats.HUMANOIDS.ordinal()]++; */ } } protected int[] buildAreaIStats() { final List<Integer> levelRanges=new Vector<Integer>(); final List<Integer> alignRanges=new Vector<Integer>(); Faction theFaction=null; for(final Enumeration<Faction> e=CMLib.factions().factions();e.hasMoreElements();) { final Faction F=e.nextElement(); if(F.showInSpecialReported()) theFaction=F; } final int[] statData=new int[Area.Stats.values().length]; statData[Area.Stats.POPULATION.ordinal()]=0; statData[Area.Stats.MIN_LEVEL.ordinal()]=Integer.MAX_VALUE; statData[Area.Stats.MAX_LEVEL.ordinal()]=Integer.MIN_VALUE; statData[Area.Stats.AVG_LEVEL.ordinal()]=0; statData[Area.Stats.MED_LEVEL.ordinal()]=0; statData[Area.Stats.AVG_ALIGNMENT.ordinal()]=0; statData[Area.Stats.TOTAL_LEVELS.ordinal()]=0; statData[Area.Stats.TOTAL_INTELLIGENT_LEVELS.ordinal()]=0; statData[Area.Stats.VISITABLE_ROOMS.ordinal()]=getProperRoomnumbers().roomCountAllAreas(); final long[] totalAlignments=new long[]{0}; for(final Enumeration<Room> r=getProperMap();r.hasMoreElements();) { final Room R=r.nextElement(); final int countable; if(R instanceof GridLocale) { statData[Area.Stats.VISITABLE_ROOMS.ordinal()]--; countable = ((GridLocale)R).getGridSize(); } else countable=1; statData[Area.Stats.COUNTABLE_ROOMS.ordinal()]+=countable; if((R.domainType()&Room.INDOORS)>0) { statData[Area.Stats.INDOOR_ROOMS.ordinal()]+=countable; switch(R.domainType()) { case Room.DOMAIN_INDOORS_CAVE: statData[Area.Stats.CAVE_ROOMS.ordinal()]+=countable; break; case Room.DOMAIN_INDOORS_METAL: case Room.DOMAIN_INDOORS_STONE: case Room.DOMAIN_INDOORS_WOOD: statData[Area.Stats.CITY_ROOMS.ordinal()]+=countable; break; case Room.DOMAIN_INDOORS_UNDERWATER: case Room.DOMAIN_INDOORS_WATERSURFACE: statData[Area.Stats.WATER_ROOMS.ordinal()]+=countable; break; } } else { switch(R.domainType()) { case Room.DOMAIN_OUTDOORS_CITY: statData[Area.Stats.CITY_ROOMS.ordinal()]+=countable; break; case Room.DOMAIN_OUTDOORS_DESERT: statData[Area.Stats.DESERT_ROOMS.ordinal()]+=countable; break; case Room.DOMAIN_OUTDOORS_UNDERWATER: case Room.DOMAIN_OUTDOORS_WATERSURFACE: statData[Area.Stats.WATER_ROOMS.ordinal()]+=countable; break; } } for(int i=0;i<R.numInhabitants();i++) buildAreaIMobStats(statData,totalAlignments,theFaction,alignRanges,levelRanges,R.fetchInhabitant(i)); for(int i=0;i<R.numItems();i++) { final Item I=R.getItem(i); if(I instanceof BoardableShip) { final Area A=((BoardableShip)I).getShipArea(); if(A==null) continue; for(final Enumeration<Room> r2=A.getProperMap();r2.hasMoreElements();) { final Room R2=r2.nextElement(); for(int i2=0;i2<R2.numInhabitants();i2++) buildAreaIMobStats(statData,totalAlignments,theFaction,alignRanges,levelRanges,R2.fetchInhabitant(i2)); } } } } if((statData[Area.Stats.POPULATION.ordinal()]==0)||(levelRanges.size()==0)) { statData[Area.Stats.MIN_LEVEL.ordinal()]=0; statData[Area.Stats.MAX_LEVEL.ordinal()]=0; } else { Collections.sort(levelRanges); Collections.sort(alignRanges); statData[Area.Stats.MED_LEVEL.ordinal()]=levelRanges.get((int)Math.round(Math.floor(CMath.div(levelRanges.size(),2.0)))).intValue(); if(alignRanges.size()>0) { statData[Area.Stats.MED_ALIGNMENT.ordinal()]=alignRanges.get((int)Math.round(Math.floor(CMath.div(alignRanges.size(),2.0)))).intValue(); statData[Area.Stats.MIN_ALIGNMENT.ordinal()]=alignRanges.get(0).intValue(); statData[Area.Stats.MAX_ALIGNMENT.ordinal()]=alignRanges.get(alignRanges.size()-1).intValue(); } statData[Area.Stats.AVG_LEVEL.ordinal()]=(int)Math.round(CMath.div(statData[Area.Stats.TOTAL_LEVELS.ordinal()],statData[Area.Stats.POPULATION.ordinal()])); statData[Area.Stats.AVG_ALIGNMENT.ordinal()]=(int)Math.round(((double)totalAlignments[0])/((double)statData[Area.Stats.POPULATION.ordinal()])); } basePhyStats().setLevel(statData[Area.Stats.MED_LEVEL.ordinal()]); phyStats().setLevel(statData[Area.Stats.MED_LEVEL.ordinal()]); //basePhyStats().setHeight(statData[Area.Stats.POPULATION.ordinal()]); return statData; } @Override public int getPlayerLevel() { return playerLevel; } @Override public void setPlayerLevel(final int level) { playerLevel=level; } @Override public int[] getAreaIStats() { if(!CMProps.getBoolVar(CMProps.Bool.MUDSTARTED)) return emptyStats; int[] statData=(int[])Resources.getResource("STATS_"+Name().toUpperCase()); if(statData!=null) return statData; synchronized(("STATS_"+Name()).intern()) { Resources.removeResource("HELP_"+Name().toUpperCase()); statData=buildAreaIStats(); Resources.submitResource("STATS_"+Name().toUpperCase(),statData); } return statData; } public int getPercentRoomsCached() { return 100; } protected StringBuffer buildAreaStats(final int[] statData) { final StringBuffer s=new StringBuffer("^N"); s.append("Area : ^H"+Name()+"^N\n\r"); s.append(description()+"\n\r"); if(author.length()>0) s.append("Author : ^H"+author+"^N\n\r"); if(statData == emptyStats) { s.append("\n\r^HFurther information about this area is not available at this time.^N\n\r"); return s; } s.append("Number of rooms: ^H"+statData[Area.Stats.VISITABLE_ROOMS.ordinal()]+"^N\n\r"); Faction theFaction=CMLib.factions().getFaction(CMLib.factions().getAlignmentID()); if(theFaction == null) { for(final Enumeration<Faction> e=CMLib.factions().factions();e.hasMoreElements();) { final Faction F=e.nextElement(); if(F.showInSpecialReported()) theFaction=F; } } if(statData[Area.Stats.POPULATION.ordinal()]==0) { if(getProperRoomnumbers().roomCountAllAreas()/2<properRooms.size()) s.append("Population : ^H0^N\n\r"); } else { s.append("Population : ^H"+statData[Area.Stats.POPULATION.ordinal()]+"^N\n\r"); final String currName=CMLib.beanCounter().getCurrency(this); if(currName.length()>0) s.append("Currency : ^H"+CMStrings.capitalizeAndLower(currName)+"^N\n\r"); else s.append("Currency : ^HGold coins (default)^N\n\r"); final LegalBehavior B=CMLib.law().getLegalBehavior(this); if(B!=null) { final String ruler=B.rulingOrganization(); if(ruler.length()>0) { final Clan C=CMLib.clans().getClan(ruler); if(C!=null) s.append("Controlled by : ^H"+C.getGovernmentName()+" "+C.name()+"^N\n\r"); } } s.append("Level range : ^H"+statData[Area.Stats.MIN_LEVEL.ordinal()]+"^N to ^H"+statData[Area.Stats.MAX_LEVEL.ordinal()]+"^N\n\r"); //s.append("Average level : ^H"+statData[Area.Stats.AVG_LEVEL.ordinal()]+"^N\n\r"); if(getPlayerLevel()>0) s.append("Player level : ^H"+getPlayerLevel()+"^N\n\r"); else s.append("Median level : ^H"+statData[Area.Stats.MED_LEVEL.ordinal()]+"^N\n\r"); if(theFaction!=null) s.append("Avg. "+CMStrings.padRight(theFaction.name(),10)+": ^H"+theFaction.fetchRangeName(statData[Area.Stats.AVG_ALIGNMENT.ordinal()])+"^N\n\r"); if(theFaction!=null) s.append("Med. "+CMStrings.padRight(theFaction.name(),10)+": ^H"+theFaction.fetchRangeName(statData[Area.Stats.MED_ALIGNMENT.ordinal()])+"^N\n\r"); } try { boolean blurbed=false; String flag=null; final List<Area> areas=new XVector<Area>(getParentsIterator()); areas.add(this); for(final Iterator<Area> i= areas.iterator(); i.hasNext();) { final Area A=i.next(); for(final Enumeration<String> f= A.areaBlurbFlags();f.hasMoreElements();) { flag=A.getBlurbFlag(f.nextElement()); if((flag!=null) &&((!flag.startsWith("{"))||(!flag.endsWith("}")))) { if (!blurbed) { blurbed = true; s.append("\n\r"); } s.append(flag+"\n\r"); } } } if(blurbed) s.append("\n\r"); } catch(final Exception e) { Log.errOut("StdArea",e); } return s; } @Override public synchronized StringBuffer getAreaStats() { if(!CMProps.getBoolVar(CMProps.Bool.MUDSTARTED)) return new StringBuffer(""); StringBuffer s=(StringBuffer)Resources.getResource("HELP_"+Name().toUpperCase()); if(s!=null) return s; s=buildAreaStats(getAreaIStats()); //Resources.submitResource("HELP_"+Name().toUpperCase(),s); // the STAT_ data is cached instead. return s; } @Override public Behavior fetchBehavior(final int index) { try { return behaviors.elementAt(index); } catch (final java.lang.ArrayIndexOutOfBoundsException x) { } return null; } @Override public Behavior fetchBehavior(final String ID) { for(final Behavior B : behaviors) { if((B!=null)&&(B.ID().equalsIgnoreCase(ID))) return B; } return null; } @Override public void eachBehavior(final EachApplicable<Behavior> applier) { final List<Behavior> behaviors=this.behaviors; if(behaviors!=null) try { for(int a=0;a<behaviors.size();a++) { final Behavior B=behaviors.get(a); if(B!=null) applier.apply(B); } } catch (final ArrayIndexOutOfBoundsException e) { } } @Override public int properSize() { synchronized(properRooms) { return properRooms.size(); } } @Override public void setProperRoomnumbers(final RoomnumberSet set) { properRoomIDSet = set; } @Override public void addProperRoom(final Room R) { if(R==null) return; if(R.getArea()!=this) { R.setArea(this); return; } synchronized(properRooms) { final String roomID=R.roomID(); if(roomID.length()==0) { if((R.getGridParent()!=null) &&(R.getGridParent().roomID().length()>0)) { // for some reason, grid children always get the back of the bus. addProperRoomnumber(R.getGridParent().getGridChildCode(R)); addMetroRoom(R); } return; } if(!properRooms.containsKey(R.roomID())) properRooms.put(R.roomID(),R); addProperRoomnumber(roomID); addMetroRoom(R); } } @Override public void addMetroRoom(final Room R) { if(R!=null) { if(R.roomID().length()==0) { if((R.getGridParent()!=null) &&(R.getGridParent().roomID().length()>0)) addMetroRoomnumber(R.getGridParent().getGridChildCode(R)); } else addMetroRoomnumber(R.roomID()); } } @Override public void delMetroRoom(final Room R) { if(R!=null) { if(R.roomID().length()==0) { if((R.getGridParent()!=null) &&(R.getGridParent().roomID().length()>0)) delMetroRoomnumber(R.getGridParent().getGridChildCode(R)); } else delMetroRoomnumber(R.roomID()); } } @Override public void addProperRoomnumber(final String roomID) { if((roomID!=null) &&(roomID.length()>0)) { getProperRoomnumbers().add(roomID); addMetroRoomnumber(roomID); } } @Override public void delProperRoomnumber(final String roomID) { if((roomID!=null)&&(roomID.length()>0)) { getProperRoomnumbers().remove(roomID); delMetroRoomnumber(roomID); } } @Override public void addMetroRoomnumber(final String roomID) { if(metroRoomIDSet==null) metroRoomIDSet=(RoomnumberSet)getProperRoomnumbers().copyOf(); if((roomID!=null)&&(roomID.length()>0)&&(!metroRoomIDSet.contains(roomID))) { metroRoomIDSet.add(roomID); if(!CMath.bset(flags(),Area.FLAG_INSTANCE_CHILD)) { for(final Iterator<Area> a=getParentsReverseIterator();a.hasNext();) a.next().addMetroRoomnumber(roomID); } } } @Override public void delMetroRoomnumber(final String roomID) { if((metroRoomIDSet!=null) &&(roomID!=null) &&(roomID.length()>0) &&(metroRoomIDSet.contains(roomID))) { metroRoomIDSet.remove(roomID); if(!CMath.bset(flags(),Area.FLAG_INSTANCE_CHILD)) { for(final Iterator<Area> a=getParentsReverseIterator();a.hasNext();) a.next().delMetroRoomnumber(roomID); } } } @Override public boolean isRoom(final Room R) { if(R==null) return false; if(R.roomID().length()>0) return getProperRoomnumbers().contains(R.roomID()); return properRooms.containsValue(R); } @Override public void delProperRoom(final Room R) { if(R==null) return; if(R instanceof GridLocale) ((GridLocale)R).clearGrid(null); synchronized(properRooms) { if(R.roomID().length()==0) { if((R.getGridParent()!=null) &&(R.getGridParent().roomID().length()>0)) { final String id=R.getGridParent().getGridChildCode(R); delProperRoomnumber(id); delMetroRoom(R); } } else if(properRooms.get(R.roomID())==R) { properRooms.remove(R.roomID()); delMetroRoom(R); delProperRoomnumber(R.roomID()); } else if(properRooms.containsValue(R)) { for(final Map.Entry<String,Room> entry : properRooms.entrySet()) { if(entry.getValue()==R) { properRooms.remove(entry.getKey()); delProperRoomnumber(entry.getKey()); } } delProperRoomnumber(R.roomID()); delMetroRoom(R); } } } @Override public Room getRoom(String roomID) { if(properRooms.size()==0) return null; if(roomID.length()==0) return null; synchronized(properRooms) { if((!roomID.startsWith(Name())) &&(roomID.toUpperCase().startsWith(Name().toUpperCase()+"#"))) roomID=Name()+roomID.substring(Name().length()); // for case sensitive situations return properRooms.get(roomID); } } @Override public int metroSize() { int num=properSize(); for(final Iterator<Area> a=getChildrenReverseIterator();a.hasNext();) num+=a.next().metroSize(); return num; } @Override public int numberOfProperIDedRooms() { int num=0; for(final Enumeration<Room> e=getProperMap();e.hasMoreElements();) { final Room R=e.nextElement(); if(R.roomID().length()>0) { if(R instanceof GridLocale) num+=((GridLocale)R).xGridSize()*((GridLocale)R).yGridSize(); else num++; } } return num; } @Override public boolean isProperlyEmpty() { return getProperRoomnumbers().isEmpty(); } @Override public Room getRandomProperRoom() { if(isProperlyEmpty()) return null; String roomID=getProperRoomnumbers().random(); if((roomID!=null) &&(!roomID.startsWith(Name())) &&(roomID.startsWith(Name().toUpperCase()))) roomID=Name()+roomID.substring(Name().length()); // looping back through CMMap is unnecc because the roomID comes directly from getProperRoomnumbers() // which means it will never be a grid sub-room. Room R=getRoom(roomID); if(R==null) { R=CMLib.map().getRoom(roomID); // BUT... it's ok to hit CMLib.map() if you fail. if(R==null) { if(this.properRooms.size()>0) { try { R=this.properRooms.firstEntry().getValue(); } catch(final Exception e) { } if(R!=null) { if(StdArea.lastComplainer != this) { StdArea.lastComplainer=this; Log.errOut("StdArea","Last Resort random-find due to failure on "+roomID+", so I just picked room: "+R.roomID()+" ("+this.amDestroyed+")"); } } else Log.errOut("StdArea","Wow, proper room size = "+this.properRooms.size()+", but no room! ("+this.amDestroyed+")"); } else { if(this.numberOfProperIDedRooms()==0) return null; Log.errOut("StdArea","Wow, proper room size = 0, but numrooms="+this.numberOfProperIDedRooms()+"! ("+this.amDestroyed+")"); } } } if(R instanceof GridLocale) return ((GridLocale)R).getRandomGridChild(); if((R==null)&&(StdArea.lastComplainer != this)) { StdArea.lastComplainer=this; Log.errOut("StdArea","Unable to random-find: "+roomID); Log.errOut(new Exception()); } return R; } @Override public Room getRandomMetroRoom() { /*synchronized(metroRooms) { if(metroSize()==0) return null; Room R=(Room)metroRooms.elementAt(CMLib.dice().roll(1,metroRooms.size(),-1)); if(R instanceof GridLocale) return ((GridLocale)R).getRandomGridChild(); return R; }*/ final RoomnumberSet metroRoomIDSet=this.metroRoomIDSet; if(metroRoomIDSet != null) { String roomID=metroRoomIDSet.random(); if((roomID!=null) &&(!roomID.startsWith(Name())) &&(roomID.startsWith(Name().toUpperCase()))) roomID=Name()+roomID.substring(Name().length()); final Room R=CMLib.map().getRoom(roomID); if(R instanceof GridLocale) return ((GridLocale)R).getRandomGridChild(); if(R==null) Log.errOut("StdArea","Unable to random-metro-find: "+roomID); return R; } return null; } @Override public Enumeration<Room> getProperMap() { return new CompleteRoomEnumerator(new IteratorEnumeration<Room>(properRooms.values().iterator())); } @Override public Enumeration<Room> getFilledProperMap() { final Enumeration<Room> r=getProperMap(); final List<Room> V=new LinkedList<Room>(); for(;r.hasMoreElements();) { final Room R=r.nextElement(); if((R!=null) &&(!V.contains(R))) { V.add(R); for(final Room R2 : R.getSky()) { if(R2 instanceof GridLocale) { for(final Room R3 : ((GridLocale)R2).getAllRoomsFilled()) { if(!V.contains(R3)) V.add(R3); } } else if(!V.contains(R2)) V.add(R2); } } } return new IteratorEnumeration<Room>(V.iterator()); } @Override public Enumeration<Room> getCompleteMap() { return getProperMap(); } @Override public Enumeration<Room> getFilledCompleteMap() { return getFilledProperMap(); } @Override public Enumeration<Room> getMetroMap() { final MultiEnumeration<Room> multiEnumerator = new MultiEnumeration<Room>(new IteratorEnumeration<Room>(properRooms.values().iterator())); for(final Iterator<Area> a=getChildrenReverseIterator();a.hasNext();) multiEnumerator.addEnumeration(a.next().getMetroMap()); return new CompleteRoomEnumerator(multiEnumerator); } @Override public Enumeration<String> subOps() { return subOps.elements(); } public SLinkedList<Area> loadAreas(final Collection<String> loadableSet) { final SLinkedList<Area> finalSet = new SLinkedList<Area>(); for (final String areaName : loadableSet) { final Area A = CMLib.map().getArea(areaName); if (A == null) continue; finalSet.add(A); } return finalSet; } protected final Iterator<Area> getParentsIterator() { return parents.iterator(); } protected final Iterator<Area> getParentsReverseIterator() { return parents.descendingIterator(); } protected final Iterator<Area> getChildrenIterator() { return children.iterator(); } protected final Iterator<Area> getChildrenReverseIterator() { return children.descendingIterator(); } @Override public Enumeration<Area> getChildren() { return new IteratorEnumeration<Area>(getChildrenIterator()); } @Override public Area getChild(final String named) { for(final Iterator<Area> i=getChildrenIterator(); i.hasNext();) { final Area A=i.next(); if((A.name().equalsIgnoreCase(named)) ||(A.Name().equalsIgnoreCase(named))) return A; } return null; } @Override public boolean isChild(final Area area) { for(final Iterator<Area> i=getChildrenIterator(); i.hasNext();) { if(i.next().equals(area)) return true; } return false; } @Override public boolean isChild(final String named) { for(final Iterator<Area> i=getChildrenIterator(); i.hasNext();) { final Area A=i.next(); if((A.name().equalsIgnoreCase(named)) ||(A.Name().equalsIgnoreCase(named))) return true; } return false; } @Override public void addChild(final Area area) { if(!canChild(area)) return; if(area.Name().equalsIgnoreCase(Name())) return; for(final Iterator<Area> i=getChildrenIterator(); i.hasNext();) { final Area A=i.next(); if(A.Name().equalsIgnoreCase(area.Name())) { children.remove(A); break; } } children.add(area); if(getTimeObj()!=CMLib.time().globalClock()) area.setTimeObj(getTimeObj()); } @Override public void removeChild(final Area area) { if(isChild(area)) children.remove(area); } // child based circular reference check @Override public boolean canChild(final Area area) { if(area instanceof BoardableShip) return false; if(parents != null) { for (final Area A : parents) { if(A==area) return false; if(!A.canChild(area)) return false; } } return true; } // Parent @Override public Enumeration<Area> getParents() { return new IteratorEnumeration<Area>(getParentsIterator()); } @Override public List<Area> getParentsRecurse() { final LinkedList<Area> V=new LinkedList<Area>(); for(final Iterator<Area> a=getParentsIterator();a.hasNext();) { final Area A=a.next(); V.add(A); V.addAll(A.getParentsRecurse()); } return V; } @Override public Area getParent(final String named) { for(final Iterator<Area> a=getParentsIterator();a.hasNext();) { final Area A=a.next(); if((A.name().equalsIgnoreCase(named)) ||(A.Name().equalsIgnoreCase(named))) return A; } return null; } @Override public boolean isParent(final Area area) { for(final Iterator<Area> a=getParentsIterator();a.hasNext();) { final Area A=a.next(); if(A == area) return true; } return false; } @Override public boolean isParent(final String named) { for(final Iterator<Area> a=getParentsIterator();a.hasNext();) { final Area A=a.next(); if((A.name().equalsIgnoreCase(named)) ||(A.Name().equalsIgnoreCase(named))) return true; } return false; } @Override public void addParent(final Area area) { derivedClimate=CLIMASK_INHERIT; derivedAtmo=ATMOSPHERE_INHERIT; derivedTheme=THEME_INHERIT; if(!canParent(area)) return; if(area.Name().equalsIgnoreCase(Name())) return; for(final Iterator<Area> i=getParentsIterator(); i.hasNext();) { final Area A=i.next(); if(A.Name().equalsIgnoreCase(area.Name())) { parents.remove(A); break; } } parents.add(area); } @Override public void removeParent(final Area area) { derivedClimate=CLIMASK_INHERIT; derivedAtmo=ATMOSPHERE_INHERIT; derivedTheme=THEME_INHERIT; if(isParent(area)) parents.remove(area); } @Override public boolean canParent(final Area area) { if(this instanceof BoardableShip) return false; if(children != null) { for (final Area A : children) { if(A==area) return false; if(!A.canParent(area)) return false; } } return true; } @Override public String L(final String str, final String... xs) { return CMLib.lang().fullSessionTranslation(str, xs); } @Override public int getSaveStatIndex() { return (xtraValues == null) ? getStatCodes().length : getStatCodes().length - xtraValues.length; } protected static final String[] STDAREACODES={"CLASS", "CLIMATE", "DESCRIPTION", "TEXT", "THEME", "BLURBS", "PREJUDICE", "BUDGET", "DEVALRATE", "INVRESETRATE", "IGNOREMASK", "PRICEMASKS", "ATMOSPHERE", "AUTHOR", "NAME", "PLAYERLEVEL", "PASSIVEMINS" }; private static String[] codes=null; @Override public String[] getStatCodes() { if(codes==null) codes=CMProps.getStatCodesList(STDAREACODES,this); return codes; } @Override public boolean isStat(final String code) { return CMParms.indexOf(getStatCodes(), code.toUpperCase().trim()) >= 0; } protected int getCodeNum(final String code) { return CMParms.indexOf(getStatCodes(), code.toUpperCase()); } @Override public String getStat(final String code) { switch(getCodeNum(code)) { case 0: return ID(); case 1: return "" + getClimateTypeCode(); case 2: return description(); case 3: return text(); case 4: return "" + getThemeCode(); case 5: return "" + CMLib.xml().getXMLList(blurbFlags.toStringVector(" ")); case 6: return prejudiceFactors(); case 7: return budget(); case 8: return devalueRate(); case 9: return "" + invResetRate(); case 10: return ignoreMask(); case 11: return CMParms.toListString(itemPricingAdjustments()); case 12: return "" + getAtmosphereCode(); case 13: return getAuthorID(); case 14: return name(); case 15: return ""+playerLevel; case 16: return Long.toString(this.passiveLapseMs / 60000); default: return CMProps.getStatCodeExtensionValue(getStatCodes(), xtraValues, code); } } @Override public void setStat(final String code, final String val) { switch(getCodeNum(code)) { case 0: return; case 1: setClimateType((CMath.s_int(val) < 0) ? -1 : CMath.s_parseBitIntExpression(Places.CLIMATE_DESCS, val)); break; case 2: setDescription(val); break; case 3: setMiscText(val); break; case 4: setTheme(CMath.s_parseBitIntExpression(Area.THEME_BIT_NAMES, val)); break; case 5: { if(val.startsWith("+")) addBlurbFlag(val.substring(1)); else if(val.startsWith("-")) delBlurbFlag(val.substring(1)); else { blurbFlags=new STreeMap<String,String>(); final List<String> V=CMLib.xml().parseXMLList(val); for(final String s : V) { final int x=s.indexOf(' '); if(x<0) blurbFlags.put(s,""); else blurbFlags.put(s.substring(0,x),s.substring(x+1)); } } break; } case 6: setPrejudiceFactors(val); break; case 7: setBudget(val); break; case 8: setDevalueRate(val); break; case 9: setInvResetRate(CMath.s_parseIntExpression(val)); break; case 10: setIgnoreMask(val); break; case 11: setItemPricingAdjustments((val.trim().length() == 0) ? new String[0] : CMParms.toStringArray(CMParms.parseCommas(val, true))); break; case 12: { if (CMath.isMathExpression(val)) setAtmosphere(CMath.s_parseIntExpression(val)); final int matCode = RawMaterial.CODES.FIND_IgnoreCase(val); if (matCode >= 0) setAtmosphere(matCode); break; } case 13: setAuthorID(val); break; case 14: setName(val); break; case 15: setPlayerLevel((int)Math.round(CMath.parseMathExpression(val))); break; case 16: { long mins=CMath.parseLongExpression(val); if(mins > 0) { if(mins > Integer.MAX_VALUE) mins=Integer.MAX_VALUE; passiveLapseMs = mins * 60 * 1000; } break; } default: CMProps.setStatCodeExtensionValue(getStatCodes(), xtraValues, code, val); break; } } @Override public boolean sameAs(final Environmental E) { if(!(E instanceof StdArea)) return false; final String[] codes=getStatCodes(); for(int i=0;i<codes.length;i++) { if(!E.getStat(codes[i]).equals(getStat(codes[i]))) return false; } return true; } }
passive head start git-svn-id: 0cdf8356e41b2d8ccbb41bb76c82068fe80b2514@18803 0d6f1817-ed0e-0410-87c9-987e46238f29
com/planet_ink/coffee_mud/Areas/StdArea.java
passive head start
Java
apache-2.0
662ea83ae8d2469ae088e3bc07f28df420258ca5
0
rajulapatisairam/jamm,SergeBlais/jamm,Unisay/jamm,jbellis/jamm
package org.github.jamm; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.Set; import java.util.concurrent.Callable; public class AlwaysEmptySet<T> implements Set<T> { private AlwaysEmptySet() { } public static <T> Set<T> create() { return Collections.<T>emptySet(); } public static <T> Callable<Set<T>> provider() { return new Callable<Set<T>>() { public Set<T> call() throws Exception { return create(); } }; } public int size() { return 0; } public boolean isEmpty() { return true; } public boolean contains(Object o) { return false; } public Iterator<T> iterator() { return Collections.<T>emptySet().iterator(); } public Object[] toArray() { return new Object[0]; } public <K> K[] toArray(K[] a) { return (K[]) Collections.emptySet().toArray(); } public boolean add(T t) { return false; } public boolean remove(Object o) { return false; } public boolean containsAll(Collection<?> c) { return false; } public boolean addAll(Collection<? extends T> c) { return false; } public boolean retainAll(Collection<?> c) { return false; } public boolean removeAll(Collection<?> c) { return false; } public void clear() { } }
src/org/github/jamm/AlwaysEmptySet.java
package org.github.jamm; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.Set; import java.util.concurrent.Callable; public class AlwaysEmptySet<T> implements Set<T> { public static final Set EMPTY_SET = new AlwaysEmptySet(); private AlwaysEmptySet() { } public static <T> Set<T> create() { return Collections.<T>emptySet(); } public static <T> Callable<Set<T>> provider() { return new Callable<Set<T>>() { public Set<T> call() throws Exception { return create(); } }; } public int size() { return 0; } public boolean isEmpty() { return true; } public boolean contains(Object o) { return false; } public Iterator<T> iterator() { return Collections.<T>emptySet().iterator(); } public Object[] toArray() { return new Object[0]; } public <K> K[] toArray(K[] a) { return (K[]) Collections.emptySet().toArray(); } public boolean add(T t) { return false; } public boolean remove(Object o) { return false; } public boolean containsAll(Collection<?> c) { return false; } public boolean addAll(Collection<? extends T> c) { return false; } public boolean retainAll(Collection<?> c) { return false; } public boolean removeAll(Collection<?> c) { return false; } public void clear() { } }
remove dead field
src/org/github/jamm/AlwaysEmptySet.java
remove dead field
Java
apache-2.0
5665a485920216d7e65c45668f607c8d8d83a6e6
0
HashEngineering/darkcoinj,HashEngineering/darkcoinj,HashEngineering/dashj,HashEngineering/dashj,HashEngineering/dashj,HashEngineering/dashj,HashEngineering/darkcoinj
/* * Copyright 2020 Dash Core Group * * 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.bitcoinj.params; import com.google.common.base.Stopwatch; import org.bitcoinj.core.*; import org.bitcoinj.quorums.LLMQParameters; import org.bitcoinj.store.BlockStore; import org.bitcoinj.store.BlockStoreException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.math.BigInteger; import java.util.HashMap; import java.util.concurrent.TimeUnit; import static com.google.common.base.Preconditions.checkState; import static org.bitcoinj.core.Utils.HEX; /** * Parameters for a named devnet, a separate instance of Dash that has relaxed rules suitable for development * and testing of applications and new Dash versions. The name of the devnet is used to generate the * second block of the blockchain. */ public class DevNetParams extends AbstractBitcoinNetParams { private static final Logger log = LoggerFactory.getLogger(DevNetParams.class); public static final int DEVNET_MAJORITY_DIP0001_WINDOW = 4032; public static final int DEVNET_MAJORITY_DIP0001_THRESHOLD = 3226; private static final BigInteger MAX_TARGET = Utils.decodeCompactBits(0x207fffff); BigInteger maxUint256 = new BigInteger("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 16); private static int DEFAULT_PROTOCOL_VERSION = 70211; private int protocolVersion; public DevNetParams(String devNetName, String sporkAddress, int defaultPort, String [] dnsSeeds) { this(devNetName, sporkAddress, defaultPort, dnsSeeds, false, DEFAULT_PROTOCOL_VERSION); } public DevNetParams(String devNetName, String sporkAddress, int defaultPort, String [] dnsSeeds, boolean supportsEvolution) { this(devNetName, sporkAddress, defaultPort, dnsSeeds, supportsEvolution, DEFAULT_PROTOCOL_VERSION); } public DevNetParams(String devNetName, String sporkAddress, int defaultPort, String [] dnsSeeds, boolean supportsEvolution, int protocolVersion) { super(); this.devNetName = "devnet-" + devNetName; id = ID_DEVNET + "." + devNetName; packetMagic = 0xe2caffce; interval = INTERVAL; targetTimespan = TARGET_TIMESPAN; maxTarget = MAX_TARGET; port = defaultPort; addressHeader = CoinDefinition.testnetAddressHeader; p2shHeader = CoinDefinition.testnetp2shHeader; dumpedPrivateKeyHeader = 239; genesisBlock.setTime(1417713337L); genesisBlock.setDifficultyTarget(0x207fffff); genesisBlock.setNonce(1096447); spendableCoinbaseDepth = 100; subsidyDecreaseBlockCount = 210240; String genesisHash = genesisBlock.getHashAsString(); checkState(genesisHash.equals("000008ca1832a4baf228eb1553c03d3a2c8e02399550dd6ea8d65cec3ef23d2e")); devnetGenesisBlock = findDevnetGenesis(this, this.devNetName, getGenesisBlock(), Coin.valueOf(50, 0)); alertSigningKey = HEX.decode(CoinDefinition.TESTNET_SATOSHI_KEY); this.dnsSeeds = dnsSeeds; checkpoints.put( 1, devnetGenesisBlock.getHash()); addrSeeds = null; bip32HeaderP2PKHpub = 0x043587cf; bip32HeaderP2PKHpriv = 0x04358394; strSporkAddress = sporkAddress; budgetPaymentsStartBlock = 4100; budgetPaymentsCycleBlocks = 50; budgetPaymentsWindowBlocks = 10; majorityEnforceBlockUpgrade = TestNet3Params.TESTNET_MAJORITY_ENFORCE_BLOCK_UPGRADE; majorityRejectBlockOutdated = TestNet3Params.TESTNET_MAJORITY_REJECT_BLOCK_OUTDATED; majorityWindow = TestNet3Params.TESTNET_MAJORITY_WINDOW; DIP0001Window = DEVNET_MAJORITY_DIP0001_WINDOW; DIP0001Upgrade = DEVNET_MAJORITY_DIP0001_THRESHOLD; DIP0001BlockHeight = 2; fulfilledRequestExpireTime = 5*60; masternodeMinimumConfirmations = 1; superblockStartBlock = 4200; superblockCycle = 24; nGovernanceMinQuorum = 1; nGovernanceFilterElements = 500; powDGWHeight = 4001; powKGWHeight = 4001; powAllowMinimumDifficulty = true; powNoRetargeting = false; this.supportsEvolution = supportsEvolution; instantSendConfirmationsRequired = 2; instantSendKeepLock = 6; this.protocolVersion = protocolVersion; //LLMQ parameters llmqs = new HashMap<LLMQParameters.LLMQType, LLMQParameters>(3); llmqs.put(LLMQParameters.LLMQType.LLMQ_50_60, LLMQParameters.llmq50_60); llmqs.put(LLMQParameters.LLMQType.LLMQ_400_60, LLMQParameters.llmq400_60); llmqs.put(LLMQParameters.LLMQType.LLMQ_400_85, LLMQParameters.llmq400_85); llmqChainLocks = LLMQParameters.LLMQType.LLMQ_50_60; llmqForInstantSend = LLMQParameters.LLMQType.LLMQ_50_60; BIP65Height = 1; } //support more than one DevNet private static HashMap<String, DevNetParams> instances; //get the devnet by name or create it if it doesn't exist. public static synchronized DevNetParams get(String devNetName, String sporkAddress, int defaultPort, String [] dnsSeeds) { if (instances == null) { instances = new HashMap<String, DevNetParams>(1); } if(!instances.containsKey("devnet-" + devNetName)) { DevNetParams instance = new DevNetParams(devNetName, sporkAddress, defaultPort, dnsSeeds); instances.put("devnet-" + devNetName, instance); return instance; } else { return instances.get("devnet-" + devNetName); } } public static synchronized DevNetParams get(String devNetName) { if (instances == null) { instances = new HashMap<>(1); } if(!instances.containsKey("devnet-" + devNetName)) { return null; } else { return instances.get("devnet-" + devNetName); } } public static synchronized void add(DevNetParams params) { if (instances == null) instances = new HashMap<>(1); instances.put(params.devNetName, params); } @Override public String getPaymentProtocolId() { return PAYMENT_PROTOCOL_ID_DEVNET; } @Override public void checkDifficultyTransitions_BTC(final StoredBlock storedPrev, final Block nextBlock, final BlockStore blockStore) throws VerificationException, BlockStoreException { } public void DarkGravityWave(StoredBlock storedPrev, Block nextBlock, final BlockStore blockStore) throws VerificationException { } @Override public int getProtocolVersionNum(ProtocolVersion version) { switch(version) { case MINIMUM: case CURRENT: case BLOOM_FILTER: return protocolVersion; } return super.getProtocolVersionNum(version); } }
core/src/main/java/org/bitcoinj/params/DevNetParams.java
/* * Copyright 2013 Google Inc. * Copyright 2014 Andreas Schildbach * * 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.bitcoinj.params; import com.google.common.base.Stopwatch; import org.bitcoinj.core.*; import org.bitcoinj.quorums.LLMQParameters; import org.bitcoinj.store.BlockStore; import org.bitcoinj.store.BlockStoreException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.math.BigInteger; import java.util.HashMap; import java.util.concurrent.TimeUnit; import static com.google.common.base.Preconditions.checkState; import static org.bitcoinj.core.Utils.HEX; /** * Parameters for a named devnet, a separate instance of Dash that has relaxed rules suitable for development * and testing of applications and new Dash versions. The name of the devnet is used to generate the * second block of the blockchain. */ public class DevNetParams extends AbstractBitcoinNetParams { private static final Logger log = LoggerFactory.getLogger(DevNetParams.class); public static final int DEVNET_MAJORITY_DIP0001_WINDOW = 4032; public static final int DEVNET_MAJORITY_DIP0001_THRESHOLD = 3226; private static final BigInteger MAX_TARGET = Utils.decodeCompactBits(0x207fffff); BigInteger maxUint256 = new BigInteger("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 16); private static int DEFAULT_PROTOCOL_VERSION = 70211; private int protocolVersion; public DevNetParams(String devNetName, String sporkAddress, int defaultPort, String [] dnsSeeds) { this(devNetName, sporkAddress, defaultPort, dnsSeeds, false, DEFAULT_PROTOCOL_VERSION); } public DevNetParams(String devNetName, String sporkAddress, int defaultPort, String [] dnsSeeds, boolean supportsEvolution) { this(devNetName, sporkAddress, defaultPort, dnsSeeds, supportsEvolution, DEFAULT_PROTOCOL_VERSION); } public DevNetParams(String devNetName, String sporkAddress, int defaultPort, String [] dnsSeeds, boolean supportsEvolution, int protocolVersion) { super(); this.devNetName = "devnet-" + devNetName; id = ID_DEVNET + "." + devNetName; packetMagic = 0xe2caffce; interval = INTERVAL; targetTimespan = TARGET_TIMESPAN; maxTarget = MAX_TARGET; port = defaultPort; addressHeader = CoinDefinition.testnetAddressHeader; p2shHeader = CoinDefinition.testnetp2shHeader; dumpedPrivateKeyHeader = 239; genesisBlock.setTime(1417713337L); genesisBlock.setDifficultyTarget(0x207fffff); genesisBlock.setNonce(1096447); spendableCoinbaseDepth = 100; subsidyDecreaseBlockCount = 210240; String genesisHash = genesisBlock.getHashAsString(); checkState(genesisHash.equals("000008ca1832a4baf228eb1553c03d3a2c8e02399550dd6ea8d65cec3ef23d2e")); devnetGenesisBlock = findDevnetGenesis(this, this.devNetName, getGenesisBlock(), Coin.valueOf(50, 0)); alertSigningKey = HEX.decode(CoinDefinition.TESTNET_SATOSHI_KEY); this.dnsSeeds = dnsSeeds; checkpoints.put( 1, devnetGenesisBlock.getHash()); addrSeeds = null; bip32HeaderP2PKHpub = 0x043587cf; bip32HeaderP2PKHpriv = 0x04358394; strSporkAddress = sporkAddress; budgetPaymentsStartBlock = 4100; budgetPaymentsCycleBlocks = 50; budgetPaymentsWindowBlocks = 10; majorityEnforceBlockUpgrade = TestNet3Params.TESTNET_MAJORITY_ENFORCE_BLOCK_UPGRADE; majorityRejectBlockOutdated = TestNet3Params.TESTNET_MAJORITY_REJECT_BLOCK_OUTDATED; majorityWindow = TestNet3Params.TESTNET_MAJORITY_WINDOW; DIP0001Window = DEVNET_MAJORITY_DIP0001_WINDOW; DIP0001Upgrade = DEVNET_MAJORITY_DIP0001_THRESHOLD; DIP0001BlockHeight = 2; fulfilledRequestExpireTime = 5*60; masternodeMinimumConfirmations = 1; superblockStartBlock = 4200; superblockCycle = 24; nGovernanceMinQuorum = 1; nGovernanceFilterElements = 500; powDGWHeight = 4001; powKGWHeight = 4001; powAllowMinimumDifficulty = true; powNoRetargeting = false; this.supportsEvolution = supportsEvolution; instantSendConfirmationsRequired = 2; instantSendKeepLock = 6; this.protocolVersion = protocolVersion; //LLMQ parameters llmqs = new HashMap<LLMQParameters.LLMQType, LLMQParameters>(3); llmqs.put(LLMQParameters.LLMQType.LLMQ_50_60, LLMQParameters.llmq50_60); llmqs.put(LLMQParameters.LLMQType.LLMQ_400_60, LLMQParameters.llmq400_60); llmqs.put(LLMQParameters.LLMQType.LLMQ_400_85, LLMQParameters.llmq400_85); llmqChainLocks = LLMQParameters.LLMQType.LLMQ_50_60; llmqForInstantSend = LLMQParameters.LLMQType.LLMQ_50_60; BIP65Height = 1; } //support more than one DevNet private static HashMap<String, DevNetParams> instances; //get the devnet by name or create it if it doesn't exist. public static synchronized DevNetParams get(String devNetName, String sporkAddress, int defaultPort, String [] dnsSeeds) { if (instances == null) { instances = new HashMap<String, DevNetParams>(1); } if(!instances.containsKey("devnet-" + devNetName)) { DevNetParams instance = new DevNetParams(devNetName, sporkAddress, defaultPort, dnsSeeds); instances.put("devnet-" + devNetName, instance); return instance; } else { return instances.get("devnet-" + devNetName); } } public static synchronized DevNetParams get(String devNetName) { if(!instances.containsKey("devnet-" + devNetName)) { return null; } else { return instances.get("devnet-" + devNetName); } } @Override public String getPaymentProtocolId() { return PAYMENT_PROTOCOL_ID_DEVNET; } @Override public void checkDifficultyTransitions_BTC(final StoredBlock storedPrev, final Block nextBlock, final BlockStore blockStore) throws VerificationException, BlockStoreException { } public void DarkGravityWave(StoredBlock storedPrev, Block nextBlock, final BlockStore blockStore) throws VerificationException { } @Override public int getProtocolVersionNum(ProtocolVersion version) { switch(version) { case MINIMUM: case CURRENT: case BLOOM_FILTER: return protocolVersion; } return super.getProtocolVersionNum(version); } }
DevNetParams: Add an add method, fix get method
core/src/main/java/org/bitcoinj/params/DevNetParams.java
DevNetParams: Add an add method, fix get method
Java
apache-2.0
a50f4b504824f9023bafb9403fc0c5d281b3bf7d
0
AndroidX/androidx,androidx/androidx,androidx/androidx,AndroidX/androidx,androidx/androidx,AndroidX/androidx,androidx/androidx,androidx/androidx,AndroidX/androidx,AndroidX/androidx,androidx/androidx,androidx/androidx,AndroidX/androidx,androidx/androidx,AndroidX/androidx,AndroidX/androidx,AndroidX/androidx,androidx/androidx,androidx/androidx,AndroidX/androidx
/* * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.fragment.app; import static androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP; import android.animation.Animator; import android.animation.AnimatorInflater; import android.animation.AnimatorListenerAdapter; import android.animation.AnimatorSet; import android.animation.PropertyValuesHolder; import android.animation.ValueAnimator; import android.content.Context; import android.content.res.Configuration; import android.content.res.Resources.NotFoundException; import android.content.res.TypedArray; import android.os.Build; import android.os.Bundle; import android.os.Looper; import android.os.Parcel; import android.os.Parcelable; import android.util.AttributeSet; import android.util.Log; import android.util.SparseArray; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.animation.AccelerateInterpolator; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.Animation.AnimationListener; import android.view.animation.AnimationSet; import android.view.animation.AnimationUtils; import android.view.animation.DecelerateInterpolator; import android.view.animation.Interpolator; import android.view.animation.ScaleAnimation; import android.view.animation.Transformation; import androidx.annotation.CallSuper; import androidx.annotation.IdRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RestrictTo; import androidx.annotation.StringRes; import androidx.collection.ArraySet; import androidx.core.util.DebugUtils; import androidx.core.util.LogWriter; import androidx.core.view.ViewCompat; import androidx.lifecycle.ViewModelStore; import java.io.FileDescriptor; import java.io.PrintWriter; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; /** * Static library support version of the framework's {@link android.app.FragmentManager}. * Used to write apps that run on platforms prior to Android 3.0. When running * on Android 3.0 or above, this implementation is still used; it does not try * to switch to the framework's implementation. See the framework {@link FragmentManager} * documentation for a class overview. * * <p>Your activity must derive from {@link FragmentActivity} to use this. From such an activity, * you can acquire the {@link FragmentManager} by calling * {@link FragmentActivity#getSupportFragmentManager}. */ public abstract class FragmentManager { /** * Representation of an entry on the fragment back stack, as created * with {@link FragmentTransaction#addToBackStack(String) * FragmentTransaction.addToBackStack()}. Entries can later be * retrieved with {@link FragmentManager#getBackStackEntryAt(int) * FragmentManager.getBackStackEntryAt()}. * * <p>Note that you should never hold on to a BackStackEntry object; * the identifier as returned by {@link #getId} is the only thing that * will be persisted across activity instances. */ public interface BackStackEntry { /** * Return the unique identifier for the entry. This is the only * representation of the entry that will persist across activity * instances. */ public int getId(); /** * Get the name that was supplied to * {@link FragmentTransaction#addToBackStack(String) * FragmentTransaction.addToBackStack(String)} when creating this entry. */ @Nullable public String getName(); /** * Return the full bread crumb title resource identifier for the entry, * or 0 if it does not have one. */ @StringRes public int getBreadCrumbTitleRes(); /** * Return the short bread crumb title resource identifier for the entry, * or 0 if it does not have one. */ @StringRes public int getBreadCrumbShortTitleRes(); /** * Return the full bread crumb title for the entry, or null if it * does not have one. */ @Nullable public CharSequence getBreadCrumbTitle(); /** * Return the short bread crumb title for the entry, or null if it * does not have one. */ @Nullable public CharSequence getBreadCrumbShortTitle(); } /** * Interface to watch for changes to the back stack. */ public interface OnBackStackChangedListener { /** * Called whenever the contents of the back stack change. */ public void onBackStackChanged(); } /** * Start a series of edit operations on the Fragments associated with * this FragmentManager. * * <p>Note: A fragment transaction can only be created/committed prior * to an activity saving its state. If you try to commit a transaction * after {@link FragmentActivity#onSaveInstanceState FragmentActivity.onSaveInstanceState()} * (and prior to a following {@link FragmentActivity#onStart FragmentActivity.onStart} * or {@link FragmentActivity#onResume FragmentActivity.onResume()}, you will get an error. * This is because the framework takes care of saving your current fragments * in the state, and if changes are made after the state is saved then they * will be lost.</p> */ @NonNull public abstract FragmentTransaction beginTransaction(); /** * @hide -- remove once prebuilts are in. * @deprecated */ @RestrictTo(LIBRARY_GROUP) @Deprecated public FragmentTransaction openTransaction() { return beginTransaction(); } /** * After a {@link FragmentTransaction} is committed with * {@link FragmentTransaction#commit FragmentTransaction.commit()}, it * is scheduled to be executed asynchronously on the process's main thread. * If you want to immediately executing any such pending operations, you * can call this function (only from the main thread) to do so. Note that * all callbacks and other related behavior will be done from within this * call, so be careful about where this is called from. * * <p>If you are committing a single transaction that does not modify the * fragment back stack, strongly consider using * {@link FragmentTransaction#commitNow()} instead. This can help avoid * unwanted side effects when other code in your app has pending committed * transactions that expect different timing.</p> * <p> * This also forces the start of any postponed Transactions where * {@link Fragment#postponeEnterTransition()} has been called. * * @return Returns true if there were any pending transactions to be * executed. */ public abstract boolean executePendingTransactions(); /** * Finds a fragment that was identified by the given id either when inflated * from XML or as the container ID when added in a transaction. This first * searches through fragments that are currently added to the manager's * activity; if no such fragment is found, then all fragments currently * on the back stack associated with this ID are searched. * @return The fragment if found or null otherwise. */ @Nullable public abstract Fragment findFragmentById(@IdRes int id); /** * Finds a fragment that was identified by the given tag either when inflated * from XML or as supplied when added in a transaction. This first * searches through fragments that are currently added to the manager's * activity; if no such fragment is found, then all fragments currently * on the back stack are searched. * @return The fragment if found or null otherwise. */ @Nullable public abstract Fragment findFragmentByTag(@Nullable String tag); /** * Flag for {@link #popBackStack(String, int)} * and {@link #popBackStack(int, int)}: If set, and the name or ID of * a back stack entry has been supplied, then all matching entries will * be consumed until one that doesn't match is found or the bottom of * the stack is reached. Otherwise, all entries up to but not including that entry * will be removed. */ public static final int POP_BACK_STACK_INCLUSIVE = 1<<0; /** * Pop the top state off the back stack. This function is asynchronous -- it enqueues the * request to pop, but the action will not be performed until the application * returns to its event loop. */ public abstract void popBackStack(); /** * Like {@link #popBackStack()}, but performs the operation immediately * inside of the call. This is like calling {@link #executePendingTransactions()} * afterwards without forcing the start of postponed Transactions. * @return Returns true if there was something popped, else false. */ public abstract boolean popBackStackImmediate(); /** * Pop the last fragment transition from the manager's fragment * back stack. * This function is asynchronous -- it enqueues the * request to pop, but the action will not be performed until the application * returns to its event loop. * * @param name If non-null, this is the name of a previous back state * to look for; if found, all states up to that state will be popped. The * {@link #POP_BACK_STACK_INCLUSIVE} flag can be used to control whether * the named state itself is popped. If null, only the top state is popped. * @param flags Either 0 or {@link #POP_BACK_STACK_INCLUSIVE}. */ public abstract void popBackStack(@Nullable String name, int flags); /** * Like {@link #popBackStack(String, int)}, but performs the operation immediately * inside of the call. This is like calling {@link #executePendingTransactions()} * afterwards without forcing the start of postponed Transactions. * @return Returns true if there was something popped, else false. */ public abstract boolean popBackStackImmediate(@Nullable String name, int flags); /** * Pop all back stack states up to the one with the given identifier. * This function is asynchronous -- it enqueues the * request to pop, but the action will not be performed until the application * returns to its event loop. * * @param id Identifier of the stated to be popped. If no identifier exists, * false is returned. * The identifier is the number returned by * {@link FragmentTransaction#commit() FragmentTransaction.commit()}. The * {@link #POP_BACK_STACK_INCLUSIVE} flag can be used to control whether * the named state itself is popped. * @param flags Either 0 or {@link #POP_BACK_STACK_INCLUSIVE}. */ public abstract void popBackStack(int id, int flags); /** * Like {@link #popBackStack(int, int)}, but performs the operation immediately * inside of the call. This is like calling {@link #executePendingTransactions()} * afterwards without forcing the start of postponed Transactions. * @return Returns true if there was something popped, else false. */ public abstract boolean popBackStackImmediate(int id, int flags); /** * Return the number of entries currently in the back stack. */ public abstract int getBackStackEntryCount(); /** * Return the BackStackEntry at index <var>index</var> in the back stack; * entries start index 0 being the bottom of the stack. */ @NonNull public abstract BackStackEntry getBackStackEntryAt(int index); /** * Add a new listener for changes to the fragment back stack. */ public abstract void addOnBackStackChangedListener( @NonNull OnBackStackChangedListener listener); /** * Remove a listener that was previously added with * {@link #addOnBackStackChangedListener(OnBackStackChangedListener)}. */ public abstract void removeOnBackStackChangedListener( @NonNull OnBackStackChangedListener listener); /** * Put a reference to a fragment in a Bundle. This Bundle can be * persisted as saved state, and when later restoring * {@link #getFragment(Bundle, String)} will return the current * instance of the same fragment. * * @param bundle The bundle in which to put the fragment reference. * @param key The name of the entry in the bundle. * @param fragment The Fragment whose reference is to be stored. */ public abstract void putFragment(@NonNull Bundle bundle, @NonNull String key, @NonNull Fragment fragment); /** * Retrieve the current Fragment instance for a reference previously * placed with {@link #putFragment(Bundle, String, Fragment)}. * * @param bundle The bundle from which to retrieve the fragment reference. * @param key The name of the entry in the bundle. * @return Returns the current Fragment instance that is associated with * the given reference. */ @Nullable public abstract Fragment getFragment(@NonNull Bundle bundle, @NonNull String key); /** * Get a list of all fragments that are currently added to the FragmentManager. * This may include those that are hidden as well as those that are shown. * This will not include any fragments only in the back stack, or fragments that * are detached or removed. * <p> * The order of the fragments in the list is the order in which they were * added or attached. * * @return A list of all fragments that are added to the FragmentManager. */ @NonNull public abstract List<Fragment> getFragments(); /** * Save the current instance state of the given Fragment. This can be * used later when creating a new instance of the Fragment and adding * it to the fragment manager, to have it create itself to match the * current state returned here. Note that there are limits on how * this can be used: * * <ul> * <li>The Fragment must currently be attached to the FragmentManager. * <li>A new Fragment created using this saved state must be the same class * type as the Fragment it was created from. * <li>The saved state can not contain dependencies on other fragments -- * that is it can't use {@link #putFragment(Bundle, String, Fragment)} to * store a fragment reference because that reference may not be valid when * this saved state is later used. Likewise the Fragment's target and * result code are not included in this state. * </ul> * * @param f The Fragment whose state is to be saved. * @return The generated state. This will be null if there was no * interesting state created by the fragment. */ @Nullable public abstract Fragment.SavedState saveFragmentInstanceState(Fragment f); /** * Returns true if the final {@link android.app.Activity#onDestroy() Activity.onDestroy()} * call has been made on the FragmentManager's Activity, so this instance is now dead. */ public abstract boolean isDestroyed(); /** * Registers a {@link FragmentLifecycleCallbacks} to listen to fragment lifecycle events * happening in this FragmentManager. All registered callbacks will be automatically * unregistered when this FragmentManager is destroyed. * * @param cb Callbacks to register * @param recursive true to automatically register this callback for all child FragmentManagers */ public abstract void registerFragmentLifecycleCallbacks(@NonNull FragmentLifecycleCallbacks cb, boolean recursive); /** * Unregisters a previously registered {@link FragmentLifecycleCallbacks}. If the callback * was not previously registered this call has no effect. All registered callbacks will be * automatically unregistered when this FragmentManager is destroyed. * * @param cb Callbacks to unregister */ public abstract void unregisterFragmentLifecycleCallbacks( @NonNull FragmentLifecycleCallbacks cb); /** * Return the currently active primary navigation fragment for this FragmentManager. * The primary navigation fragment is set by fragment transactions using * {@link FragmentTransaction#setPrimaryNavigationFragment(Fragment)}. * * <p>The primary navigation fragment's * {@link Fragment#getChildFragmentManager() child FragmentManager} will be called first * to process delegated navigation actions such as {@link #popBackStack()} if no ID * or transaction name is provided to pop to.</p> * * @return the fragment designated as the primary navigation fragment */ @Nullable public abstract Fragment getPrimaryNavigationFragment(); /** * Print the FragmentManager's state into the given stream. * * @param prefix Text to print at the front of each line. * @param fd The raw file descriptor that the dump is being sent to. * @param writer A PrintWriter to which the dump is to be set. * @param args Additional arguments to the dump request. */ public abstract void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args); /** * Control whether the framework's internal fragment manager debugging * logs are turned on. If enabled, you will see output in logcat as * the framework performs fragment operations. */ public static void enableDebugLogging(boolean enabled) { FragmentManagerImpl.DEBUG = enabled; } /** * Returns {@code true} if the FragmentManager's state has already been saved * by its host. Any operations that would change saved state should not be performed * if this method returns true. For example, any popBackStack() method, such as * {@link #popBackStackImmediate()} or any FragmentTransaction using * {@link FragmentTransaction#commit()} instead of * {@link FragmentTransaction#commitAllowingStateLoss()} will change * the state and will result in an error. * * @return true if this FragmentManager's state has already been saved by its host */ public abstract boolean isStateSaved(); /** * Callback interface for listening to fragment state changes that happen * within a given FragmentManager. */ public abstract static class FragmentLifecycleCallbacks { /** * Called right before the fragment's {@link Fragment#onAttach(Context)} method is called. * This is a good time to inject any required dependencies or perform other configuration * for the fragment before any of the fragment's lifecycle methods are invoked. * * @param fm Host FragmentManager * @param f Fragment changing state * @param context Context that the Fragment is being attached to */ public void onFragmentPreAttached(@NonNull FragmentManager fm, @NonNull Fragment f, @NonNull Context context) {} /** * Called after the fragment has been attached to its host. Its host will have had * <code>onAttachFragment</code> called before this call happens. * * @param fm Host FragmentManager * @param f Fragment changing state * @param context Context that the Fragment was attached to */ public void onFragmentAttached(@NonNull FragmentManager fm, @NonNull Fragment f, @NonNull Context context) {} /** * Called right before the fragment's {@link Fragment#onCreate(Bundle)} method is called. * This is a good time to inject any required dependencies or perform other configuration * for the fragment. * * @param fm Host FragmentManager * @param f Fragment changing state * @param savedInstanceState Saved instance bundle from a previous instance */ public void onFragmentPreCreated(@NonNull FragmentManager fm, @NonNull Fragment f, @Nullable Bundle savedInstanceState) {} /** * Called after the fragment has returned from the FragmentManager's call to * {@link Fragment#onCreate(Bundle)}. This will only happen once for any given * fragment instance, though the fragment may be attached and detached multiple times. * * @param fm Host FragmentManager * @param f Fragment changing state * @param savedInstanceState Saved instance bundle from a previous instance */ public void onFragmentCreated(@NonNull FragmentManager fm, @NonNull Fragment f, @Nullable Bundle savedInstanceState) {} /** * Called after the fragment has returned from the FragmentManager's call to * {@link Fragment#onActivityCreated(Bundle)}. This will only happen once for any given * fragment instance, though the fragment may be attached and detached multiple times. * * @param fm Host FragmentManager * @param f Fragment changing state * @param savedInstanceState Saved instance bundle from a previous instance */ public void onFragmentActivityCreated(@NonNull FragmentManager fm, @NonNull Fragment f, @Nullable Bundle savedInstanceState) {} /** * Called after the fragment has returned a non-null view from the FragmentManager's * request to {@link Fragment#onCreateView(LayoutInflater, ViewGroup, Bundle)}. * * @param fm Host FragmentManager * @param f Fragment that created and owns the view * @param v View returned by the fragment * @param savedInstanceState Saved instance bundle from a previous instance */ public void onFragmentViewCreated(@NonNull FragmentManager fm, @NonNull Fragment f, @NonNull View v, @Nullable Bundle savedInstanceState) {} /** * Called after the fragment has returned from the FragmentManager's call to * {@link Fragment#onStart()}. * * @param fm Host FragmentManager * @param f Fragment changing state */ public void onFragmentStarted(@NonNull FragmentManager fm, @NonNull Fragment f) {} /** * Called after the fragment has returned from the FragmentManager's call to * {@link Fragment#onResume()}. * * @param fm Host FragmentManager * @param f Fragment changing state */ public void onFragmentResumed(@NonNull FragmentManager fm, @NonNull Fragment f) {} /** * Called after the fragment has returned from the FragmentManager's call to * {@link Fragment#onPause()}. * * @param fm Host FragmentManager * @param f Fragment changing state */ public void onFragmentPaused(@NonNull FragmentManager fm, @NonNull Fragment f) {} /** * Called after the fragment has returned from the FragmentManager's call to * {@link Fragment#onStop()}. * * @param fm Host FragmentManager * @param f Fragment changing state */ public void onFragmentStopped(@NonNull FragmentManager fm, @NonNull Fragment f) {} /** * Called after the fragment has returned from the FragmentManager's call to * {@link Fragment#onSaveInstanceState(Bundle)}. * * @param fm Host FragmentManager * @param f Fragment changing state * @param outState Saved state bundle for the fragment */ public void onFragmentSaveInstanceState(@NonNull FragmentManager fm, @NonNull Fragment f, @NonNull Bundle outState) {} /** * Called after the fragment has returned from the FragmentManager's call to * {@link Fragment#onDestroyView()}. * * @param fm Host FragmentManager * @param f Fragment changing state */ public void onFragmentViewDestroyed(@NonNull FragmentManager fm, @NonNull Fragment f) {} /** * Called after the fragment has returned from the FragmentManager's call to * {@link Fragment#onDestroy()}. * * @param fm Host FragmentManager * @param f Fragment changing state */ public void onFragmentDestroyed(@NonNull FragmentManager fm, @NonNull Fragment f) {} /** * Called after the fragment has returned from the FragmentManager's call to * {@link Fragment#onDetach()}. * * @param fm Host FragmentManager * @param f Fragment changing state */ public void onFragmentDetached(@NonNull FragmentManager fm, @NonNull Fragment f) {} } } final class FragmentManagerState implements Parcelable { FragmentState[] mActive; int[] mAdded; BackStackState[] mBackStack; int mPrimaryNavActiveIndex = -1; int mNextFragmentIndex; public FragmentManagerState() { } public FragmentManagerState(Parcel in) { mActive = in.createTypedArray(FragmentState.CREATOR); mAdded = in.createIntArray(); mBackStack = in.createTypedArray(BackStackState.CREATOR); mPrimaryNavActiveIndex = in.readInt(); mNextFragmentIndex = in.readInt(); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeTypedArray(mActive, flags); dest.writeIntArray(mAdded); dest.writeTypedArray(mBackStack, flags); dest.writeInt(mPrimaryNavActiveIndex); dest.writeInt(mNextFragmentIndex); } public static final Parcelable.Creator<FragmentManagerState> CREATOR = new Parcelable.Creator<FragmentManagerState>() { @Override public FragmentManagerState createFromParcel(Parcel in) { return new FragmentManagerState(in); } @Override public FragmentManagerState[] newArray(int size) { return new FragmentManagerState[size]; } }; } /** * Container for fragments associated with an activity. */ final class FragmentManagerImpl extends FragmentManager implements LayoutInflater.Factory2 { static boolean DEBUG = false; static final String TAG = "FragmentManager"; static final String TARGET_REQUEST_CODE_STATE_TAG = "android:target_req_state"; static final String TARGET_STATE_TAG = "android:target_state"; static final String VIEW_STATE_TAG = "android:view_state"; static final String USER_VISIBLE_HINT_TAG = "android:user_visible_hint"; private static final class FragmentLifecycleCallbacksHolder { final FragmentLifecycleCallbacks mCallback; final boolean mRecursive; FragmentLifecycleCallbacksHolder(FragmentLifecycleCallbacks callback, boolean recursive) { mCallback = callback; mRecursive = recursive; } } ArrayList<OpGenerator> mPendingActions; boolean mExecutingActions; int mNextFragmentIndex = 0; final ArrayList<Fragment> mAdded = new ArrayList<>(); SparseArray<Fragment> mActive; ArrayList<BackStackRecord> mBackStack; ArrayList<Fragment> mCreatedMenus; // Must be accessed while locked. ArrayList<BackStackRecord> mBackStackIndices; ArrayList<Integer> mAvailBackStackIndices; ArrayList<OnBackStackChangedListener> mBackStackChangeListeners; private final CopyOnWriteArrayList<FragmentLifecycleCallbacksHolder> mLifecycleCallbacks = new CopyOnWriteArrayList<>(); int mCurState = Fragment.INITIALIZING; FragmentHostCallback mHost; FragmentContainer mContainer; Fragment mParent; @Nullable Fragment mPrimaryNav; static Field sAnimationListenerField = null; boolean mNeedMenuInvalidate; boolean mStateSaved; boolean mStopped; boolean mDestroyed; String mNoTransactionsBecause; boolean mHavePendingDeferredStart; // Temporary vars for removing redundant operations in BackStackRecords: ArrayList<BackStackRecord> mTmpRecords; ArrayList<Boolean> mTmpIsPop; ArrayList<Fragment> mTmpAddedFragments; // Temporary vars for state save and restore. Bundle mStateBundle = null; SparseArray<Parcelable> mStateArray = null; // Postponed transactions. ArrayList<StartEnterTransitionListener> mPostponedTransactions; // Saved FragmentManagerNonConfig during saveAllState() and cleared in noteStateNotSaved() FragmentManagerNonConfig mSavedNonConfig; Runnable mExecCommit = new Runnable() { @Override public void run() { execPendingActions(); } }; static boolean modifiesAlpha(AnimationOrAnimator anim) { if (anim.animation instanceof AlphaAnimation) { return true; } else if (anim.animation instanceof AnimationSet) { List<Animation> anims = ((AnimationSet) anim.animation).getAnimations(); for (int i = 0; i < anims.size(); i++) { if (anims.get(i) instanceof AlphaAnimation) { return true; } } return false; } else { return modifiesAlpha(anim.animator); } } static boolean modifiesAlpha(Animator anim) { if (anim == null) { return false; } if (anim instanceof ValueAnimator) { ValueAnimator valueAnim = (ValueAnimator) anim; PropertyValuesHolder[] values = valueAnim.getValues(); for (int i = 0; i < values.length; i++) { if (("alpha").equals(values[i].getPropertyName())) { return true; } } } else if (anim instanceof AnimatorSet) { List<Animator> animList = ((AnimatorSet) anim).getChildAnimations(); for (int i = 0; i < animList.size(); i++) { if (modifiesAlpha(animList.get(i))) { return true; } } } return false; } static boolean shouldRunOnHWLayer(View v, AnimationOrAnimator anim) { if (v == null || anim == null) { return false; } return Build.VERSION.SDK_INT >= 19 && v.getLayerType() == View.LAYER_TYPE_NONE && ViewCompat.hasOverlappingRendering(v) && modifiesAlpha(anim); } private void throwException(RuntimeException ex) { Log.e(TAG, ex.getMessage()); Log.e(TAG, "Activity state:"); LogWriter logw = new LogWriter(TAG); PrintWriter pw = new PrintWriter(logw); if (mHost != null) { try { mHost.onDump(" ", null, pw, new String[] { }); } catch (Exception e) { Log.e(TAG, "Failed dumping state", e); } } else { try { dump(" ", null, pw, new String[] { }); } catch (Exception e) { Log.e(TAG, "Failed dumping state", e); } } throw ex; } @Override public FragmentTransaction beginTransaction() { return new BackStackRecord(this); } @Override public boolean executePendingTransactions() { boolean updates = execPendingActions(); forcePostponedTransactions(); return updates; } @Override public void popBackStack() { enqueueAction(new PopBackStackState(null, -1, 0), false); } @Override public boolean popBackStackImmediate() { checkStateLoss(); return popBackStackImmediate(null, -1, 0); } @Override public void popBackStack(@Nullable final String name, final int flags) { enqueueAction(new PopBackStackState(name, -1, flags), false); } @Override public boolean popBackStackImmediate(@Nullable String name, int flags) { checkStateLoss(); return popBackStackImmediate(name, -1, flags); } @Override public void popBackStack(final int id, final int flags) { if (id < 0) { throw new IllegalArgumentException("Bad id: " + id); } enqueueAction(new PopBackStackState(null, id, flags), false); } @Override public boolean popBackStackImmediate(int id, int flags) { checkStateLoss(); execPendingActions(); if (id < 0) { throw new IllegalArgumentException("Bad id: " + id); } return popBackStackImmediate(null, id, flags); } /** * Used by all public popBackStackImmediate methods, this executes pending transactions and * returns true if the pop action did anything, regardless of what other pending * transactions did. * * @return true if the pop operation did anything or false otherwise. */ private boolean popBackStackImmediate(String name, int id, int flags) { execPendingActions(); ensureExecReady(true); if (mPrimaryNav != null // We have a primary nav fragment && id < 0 // No valid id (since they're local) && name == null) { // no name to pop to (since they're local) final FragmentManager childManager = mPrimaryNav.peekChildFragmentManager(); if (childManager != null && childManager.popBackStackImmediate()) { // We did something, just not to this specific FragmentManager. Return true. return true; } } boolean executePop = popBackStackState(mTmpRecords, mTmpIsPop, name, id, flags); if (executePop) { mExecutingActions = true; try { removeRedundantOperationsAndExecute(mTmpRecords, mTmpIsPop); } finally { cleanupExec(); } } doPendingDeferredStart(); burpActive(); return executePop; } @Override public int getBackStackEntryCount() { return mBackStack != null ? mBackStack.size() : 0; } @Override public BackStackEntry getBackStackEntryAt(int index) { return mBackStack.get(index); } @Override public void addOnBackStackChangedListener(OnBackStackChangedListener listener) { if (mBackStackChangeListeners == null) { mBackStackChangeListeners = new ArrayList<OnBackStackChangedListener>(); } mBackStackChangeListeners.add(listener); } @Override public void removeOnBackStackChangedListener(OnBackStackChangedListener listener) { if (mBackStackChangeListeners != null) { mBackStackChangeListeners.remove(listener); } } @Override public void putFragment(Bundle bundle, String key, Fragment fragment) { if (fragment.mIndex < 0) { throwException(new IllegalStateException("Fragment " + fragment + " is not currently in the FragmentManager")); } bundle.putInt(key, fragment.mIndex); } @Override @Nullable public Fragment getFragment(Bundle bundle, String key) { int index = bundle.getInt(key, -1); if (index == -1) { return null; } Fragment f = mActive.get(index); if (f == null) { throwException(new IllegalStateException("Fragment no longer exists for key " + key + ": index " + index)); } return f; } @Override public List<Fragment> getFragments() { if (mAdded.isEmpty()) { return Collections.emptyList(); } synchronized (mAdded) { return (List<Fragment>) mAdded.clone(); } } /** * This is used by FragmentController to get the Active fragments. * * @return A list of active fragments in the fragment manager, including those that are in the * back stack. */ List<Fragment> getActiveFragments() { if (mActive == null) { return null; } final int count = mActive.size(); ArrayList<Fragment> fragments = new ArrayList<>(count); for (int i = 0; i < count; i++) { fragments.add(mActive.valueAt(i)); } return fragments; } /** * Used by FragmentController to get the number of Active Fragments. * * @return The number of active fragments. */ int getActiveFragmentCount() { if (mActive == null) { return 0; } return mActive.size(); } @Override @Nullable public Fragment.SavedState saveFragmentInstanceState(Fragment fragment) { if (fragment.mIndex < 0) { throwException( new IllegalStateException("Fragment " + fragment + " is not currently in the FragmentManager")); } if (fragment.mState > Fragment.INITIALIZING) { Bundle result = saveFragmentBasicState(fragment); return result != null ? new Fragment.SavedState(result) : null; } return null; } @Override public boolean isDestroyed() { return mDestroyed; } @Override public String toString() { StringBuilder sb = new StringBuilder(128); sb.append("FragmentManager{"); sb.append(Integer.toHexString(System.identityHashCode(this))); sb.append(" in "); if (mParent != null) { DebugUtils.buildShortClassTag(mParent, sb); } else { DebugUtils.buildShortClassTag(mHost, sb); } sb.append("}}"); return sb.toString(); } @Override public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) { String innerPrefix = prefix + " "; int N; if (mActive != null) { N = mActive.size(); if (N > 0) { writer.print(prefix); writer.print("Active Fragments in "); writer.print(Integer.toHexString(System.identityHashCode(this))); writer.println(":"); for (int i=0; i<N; i++) { Fragment f = mActive.valueAt(i); writer.print(prefix); writer.print(" #"); writer.print(i); writer.print(": "); writer.println(f); if (f != null) { f.dump(innerPrefix, fd, writer, args); } } } } N = mAdded.size(); if (N > 0) { writer.print(prefix); writer.println("Added Fragments:"); for (int i = 0; i < N; i++) { Fragment f = mAdded.get(i); writer.print(prefix); writer.print(" #"); writer.print(i); writer.print(": "); writer.println(f.toString()); } } if (mCreatedMenus != null) { N = mCreatedMenus.size(); if (N > 0) { writer.print(prefix); writer.println("Fragments Created Menus:"); for (int i=0; i<N; i++) { Fragment f = mCreatedMenus.get(i); writer.print(prefix); writer.print(" #"); writer.print(i); writer.print(": "); writer.println(f.toString()); } } } if (mBackStack != null) { N = mBackStack.size(); if (N > 0) { writer.print(prefix); writer.println("Back Stack:"); for (int i=0; i<N; i++) { BackStackRecord bs = mBackStack.get(i); writer.print(prefix); writer.print(" #"); writer.print(i); writer.print(": "); writer.println(bs.toString()); bs.dump(innerPrefix, fd, writer, args); } } } synchronized (this) { if (mBackStackIndices != null) { N = mBackStackIndices.size(); if (N > 0) { writer.print(prefix); writer.println("Back Stack Indices:"); for (int i=0; i<N; i++) { BackStackRecord bs = mBackStackIndices.get(i); writer.print(prefix); writer.print(" #"); writer.print(i); writer.print(": "); writer.println(bs); } } } if (mAvailBackStackIndices != null && mAvailBackStackIndices.size() > 0) { writer.print(prefix); writer.print("mAvailBackStackIndices: "); writer.println(Arrays.toString(mAvailBackStackIndices.toArray())); } } if (mPendingActions != null) { N = mPendingActions.size(); if (N > 0) { writer.print(prefix); writer.println("Pending Actions:"); for (int i=0; i<N; i++) { OpGenerator r = mPendingActions.get(i); writer.print(prefix); writer.print(" #"); writer.print(i); writer.print(": "); writer.println(r); } } } writer.print(prefix); writer.println("FragmentManager misc state:"); writer.print(prefix); writer.print(" mHost="); writer.println(mHost); writer.print(prefix); writer.print(" mContainer="); writer.println(mContainer); if (mParent != null) { writer.print(prefix); writer.print(" mParent="); writer.println(mParent); } writer.print(prefix); writer.print(" mCurState="); writer.print(mCurState); writer.print(" mStateSaved="); writer.print(mStateSaved); writer.print(" mStopped="); writer.print(mStopped); writer.print(" mDestroyed="); writer.println(mDestroyed); if (mNeedMenuInvalidate) { writer.print(prefix); writer.print(" mNeedMenuInvalidate="); writer.println(mNeedMenuInvalidate); } if (mNoTransactionsBecause != null) { writer.print(prefix); writer.print(" mNoTransactionsBecause="); writer.println(mNoTransactionsBecause); } } static final Interpolator DECELERATE_QUINT = new DecelerateInterpolator(2.5f); static final Interpolator DECELERATE_CUBIC = new DecelerateInterpolator(1.5f); static final Interpolator ACCELERATE_QUINT = new AccelerateInterpolator(2.5f); static final Interpolator ACCELERATE_CUBIC = new AccelerateInterpolator(1.5f); static final int ANIM_DUR = 220; static AnimationOrAnimator makeOpenCloseAnimation(Context context, float startScale, float endScale, float startAlpha, float endAlpha) { AnimationSet set = new AnimationSet(false); ScaleAnimation scale = new ScaleAnimation(startScale, endScale, startScale, endScale, Animation.RELATIVE_TO_SELF, .5f, Animation.RELATIVE_TO_SELF, .5f); scale.setInterpolator(DECELERATE_QUINT); scale.setDuration(ANIM_DUR); set.addAnimation(scale); AlphaAnimation alpha = new AlphaAnimation(startAlpha, endAlpha); alpha.setInterpolator(DECELERATE_CUBIC); alpha.setDuration(ANIM_DUR); set.addAnimation(alpha); return new AnimationOrAnimator(set); } static AnimationOrAnimator makeFadeAnimation(Context context, float start, float end) { AlphaAnimation anim = new AlphaAnimation(start, end); anim.setInterpolator(DECELERATE_CUBIC); anim.setDuration(ANIM_DUR); return new AnimationOrAnimator(anim); } AnimationOrAnimator loadAnimation(Fragment fragment, int transit, boolean enter, int transitionStyle) { int nextAnim = fragment.getNextAnim(); Animation animation = fragment.onCreateAnimation(transit, enter, nextAnim); if (animation != null) { return new AnimationOrAnimator(animation); } Animator animator = fragment.onCreateAnimator(transit, enter, nextAnim); if (animator != null) { return new AnimationOrAnimator(animator); } if (nextAnim != 0) { String dir = mHost.getContext().getResources().getResourceTypeName(nextAnim); boolean isAnim = "anim".equals(dir); boolean successfulLoad = false; if (isAnim) { // try AnimationUtils first try { animation = AnimationUtils.loadAnimation(mHost.getContext(), nextAnim); if (animation != null) { return new AnimationOrAnimator(animation); } // A null animation may be returned and that is acceptable successfulLoad = true; // succeeded in loading animation, but it is null } catch (NotFoundException e) { throw e; // Rethrow it -- the resource should be found if it is provided. } catch (RuntimeException e) { // Other exceptions can occur when loading an Animator from AnimationUtils. } } if (!successfulLoad) { // try Animator try { animator = AnimatorInflater.loadAnimator(mHost.getContext(), nextAnim); if (animator != null) { return new AnimationOrAnimator(animator); } } catch (RuntimeException e) { if (isAnim) { // Rethrow it -- we already tried AnimationUtils and it failed. throw e; } // Otherwise, it is probably an animation resource animation = AnimationUtils.loadAnimation(mHost.getContext(), nextAnim); if (animation != null) { return new AnimationOrAnimator(animation); } } } } if (transit == 0) { return null; } int styleIndex = transitToStyleIndex(transit, enter); if (styleIndex < 0) { return null; } switch (styleIndex) { case ANIM_STYLE_OPEN_ENTER: return makeOpenCloseAnimation(mHost.getContext(), 1.125f, 1.0f, 0, 1); case ANIM_STYLE_OPEN_EXIT: return makeOpenCloseAnimation(mHost.getContext(), 1.0f, .975f, 1, 0); case ANIM_STYLE_CLOSE_ENTER: return makeOpenCloseAnimation(mHost.getContext(), .975f, 1.0f, 0, 1); case ANIM_STYLE_CLOSE_EXIT: return makeOpenCloseAnimation(mHost.getContext(), 1.0f, 1.075f, 1, 0); case ANIM_STYLE_FADE_ENTER: return makeFadeAnimation(mHost.getContext(), 0, 1); case ANIM_STYLE_FADE_EXIT: return makeFadeAnimation(mHost.getContext(), 1, 0); } // TODO: remove or fix transitionStyle -- it apparently never worked. if (transitionStyle == 0 && mHost.onHasWindowAnimations()) { transitionStyle = mHost.onGetWindowAnimations(); } if (transitionStyle == 0) { return null; } //TypedArray attrs = mActivity.obtainStyledAttributes(transitionStyle, // com.android.internal.R.styleable.FragmentAnimation); //int anim = attrs.getResourceId(styleIndex, 0); //attrs.recycle(); //if (anim == 0) { // return null; //} //return AnimatorInflater.loadAnimator(mActivity, anim); return null; } public void performPendingDeferredStart(Fragment f) { if (f.mDeferStart) { if (mExecutingActions) { // Wait until we're done executing our pending transactions mHavePendingDeferredStart = true; return; } f.mDeferStart = false; moveToState(f, mCurState, 0, 0, false); } } /** * Sets the to be animated view on hardware layer during the animation. Note * that calling this will replace any existing animation listener on the animation * with a new one, as animations do not support more than one listeners. Therefore, * animations that already have listeners should do the layer change operations * in their existing listeners, rather than calling this function. */ private static void setHWLayerAnimListenerIfAlpha(final View v, AnimationOrAnimator anim) { if (v == null || anim == null) { return; } if (shouldRunOnHWLayer(v, anim)) { if (anim.animator != null) { anim.animator.addListener(new AnimatorOnHWLayerIfNeededListener(v)); } else { AnimationListener originalListener = getAnimationListener(anim.animation); // If there's already a listener set on the animation, we need wrap the new listener // around the existing listener, so that they will both get animation listener // callbacks. v.setLayerType(View.LAYER_TYPE_HARDWARE, null); anim.animation.setAnimationListener(new AnimateOnHWLayerIfNeededListener(v, originalListener)); } } } /** * Returns an existing AnimationListener on an Animation or {@code null} if none exists. */ private static AnimationListener getAnimationListener(Animation animation) { AnimationListener originalListener = null; try { if (sAnimationListenerField == null) { sAnimationListenerField = Animation.class.getDeclaredField("mListener"); sAnimationListenerField.setAccessible(true); } originalListener = (AnimationListener) sAnimationListenerField.get(animation); } catch (NoSuchFieldException e) { Log.e(TAG, "No field with the name mListener is found in Animation class", e); } catch (IllegalAccessException e) { Log.e(TAG, "Cannot access Animation's mListener field", e); } return originalListener; } boolean isStateAtLeast(int state) { return mCurState >= state; } @SuppressWarnings("ReferenceEquality") void moveToState(Fragment f, int newState, int transit, int transitionStyle, boolean keepActive) { // Fragments that are not currently added will sit in the onCreate() state. if ((!f.mAdded || f.mDetached) && newState > Fragment.CREATED) { newState = Fragment.CREATED; } if (f.mRemoving && newState > f.mState) { if (f.mState == Fragment.INITIALIZING && f.isInBackStack()) { // Allow the fragment to be created so that it can be saved later. newState = Fragment.CREATED; } else { // While removing a fragment, we can't change it to a higher state. newState = f.mState; } } // Defer start if requested; don't allow it to move to STARTED or higher // if it's not already started. if (f.mDeferStart && f.mState < Fragment.STARTED && newState > Fragment.ACTIVITY_CREATED) { newState = Fragment.ACTIVITY_CREATED; } if (f.mState <= newState) { // For fragments that are created from a layout, when restoring from // state we don't want to allow them to be created until they are // being reloaded from the layout. if (f.mFromLayout && !f.mInLayout) { return; } if (f.getAnimatingAway() != null || f.getAnimator() != null) { // The fragment is currently being animated... but! Now we // want to move our state back up. Give up on waiting for the // animation, move to whatever the final state should be once // the animation is done, and then we can proceed from there. f.setAnimatingAway(null); f.setAnimator(null); moveToState(f, f.getStateAfterAnimating(), 0, 0, true); } switch (f.mState) { case Fragment.INITIALIZING: if (newState > Fragment.INITIALIZING) { if (DEBUG) Log.v(TAG, "moveto CREATED: " + f); if (f.mSavedFragmentState != null) { f.mSavedFragmentState.setClassLoader(mHost.getContext() .getClassLoader()); f.mSavedViewState = f.mSavedFragmentState.getSparseParcelableArray( FragmentManagerImpl.VIEW_STATE_TAG); f.mTarget = getFragment(f.mSavedFragmentState, FragmentManagerImpl.TARGET_STATE_TAG); if (f.mTarget != null) { f.mTargetRequestCode = f.mSavedFragmentState.getInt( FragmentManagerImpl.TARGET_REQUEST_CODE_STATE_TAG, 0); } if (f.mSavedUserVisibleHint != null) { f.mUserVisibleHint = f.mSavedUserVisibleHint; f.mSavedUserVisibleHint = null; } else { f.mUserVisibleHint = f.mSavedFragmentState.getBoolean( FragmentManagerImpl.USER_VISIBLE_HINT_TAG, true); } if (!f.mUserVisibleHint) { f.mDeferStart = true; if (newState > Fragment.ACTIVITY_CREATED) { newState = Fragment.ACTIVITY_CREATED; } } } f.mHost = mHost; f.mParentFragment = mParent; f.mFragmentManager = mParent != null ? mParent.mChildFragmentManager : mHost.getFragmentManagerImpl(); // If we have a target fragment, push it along to at least CREATED // so that this one can rely on it as an initialized dependency. if (f.mTarget != null) { if (mActive.get(f.mTarget.mIndex) != f.mTarget) { throw new IllegalStateException("Fragment " + f + " declared target fragment " + f.mTarget + " that does not belong to this FragmentManager!"); } if (f.mTarget.mState < Fragment.CREATED) { moveToState(f.mTarget, Fragment.CREATED, 0, 0, true); } } dispatchOnFragmentPreAttached(f, mHost.getContext(), false); f.mCalled = false; f.onAttach(mHost.getContext()); if (!f.mCalled) { throw new SuperNotCalledException("Fragment " + f + " did not call through to super.onAttach()"); } if (f.mParentFragment == null) { mHost.onAttachFragment(f); } else { f.mParentFragment.onAttachFragment(f); } dispatchOnFragmentAttached(f, mHost.getContext(), false); if (!f.mIsCreated) { dispatchOnFragmentPreCreated(f, f.mSavedFragmentState, false); f.performCreate(f.mSavedFragmentState); dispatchOnFragmentCreated(f, f.mSavedFragmentState, false); } else { f.restoreChildFragmentState(f.mSavedFragmentState); f.mState = Fragment.CREATED; } f.mRetaining = false; } // fall through case Fragment.CREATED: // This is outside the if statement below on purpose; we want this to run // even if we do a moveToState from CREATED => *, CREATED => CREATED, and // * => CREATED as part of the case fallthrough above. ensureInflatedFragmentView(f); if (newState > Fragment.CREATED) { if (DEBUG) Log.v(TAG, "moveto ACTIVITY_CREATED: " + f); if (!f.mFromLayout) { ViewGroup container = null; if (f.mContainerId != 0) { if (f.mContainerId == View.NO_ID) { throwException(new IllegalArgumentException( "Cannot create fragment " + f + " for a container view with no id")); } container = (ViewGroup) mContainer.onFindViewById(f.mContainerId); if (container == null && !f.mRestored) { String resName; try { resName = f.getResources().getResourceName(f.mContainerId); } catch (NotFoundException e) { resName = "unknown"; } throwException(new IllegalArgumentException( "No view found for id 0x" + Integer.toHexString(f.mContainerId) + " (" + resName + ") for fragment " + f)); } } f.mContainer = container; f.performCreateView(f.performGetLayoutInflater( f.mSavedFragmentState), container, f.mSavedFragmentState); if (f.mView != null) { f.mInnerView = f.mView; f.mView.setSaveFromParentEnabled(false); if (container != null) { container.addView(f.mView); } if (f.mHidden) { f.mView.setVisibility(View.GONE); } f.onViewCreated(f.mView, f.mSavedFragmentState); dispatchOnFragmentViewCreated(f, f.mView, f.mSavedFragmentState, false); // Only animate the view if it is visible. This is done after // dispatchOnFragmentViewCreated in case visibility is changed f.mIsNewlyAdded = (f.mView.getVisibility() == View.VISIBLE) && f.mContainer != null; } else { f.mInnerView = null; } } f.performActivityCreated(f.mSavedFragmentState); dispatchOnFragmentActivityCreated(f, f.mSavedFragmentState, false); if (f.mView != null) { f.restoreViewState(f.mSavedFragmentState); } f.mSavedFragmentState = null; } // fall through case Fragment.ACTIVITY_CREATED: if (newState > Fragment.ACTIVITY_CREATED) { if (DEBUG) Log.v(TAG, "moveto STARTED: " + f); f.performStart(); dispatchOnFragmentStarted(f, false); } // fall through case Fragment.STARTED: if (newState > Fragment.STARTED) { if (DEBUG) Log.v(TAG, "moveto RESUMED: " + f); f.performResume(); dispatchOnFragmentResumed(f, false); f.mSavedFragmentState = null; f.mSavedViewState = null; } } } else if (f.mState > newState) { switch (f.mState) { case Fragment.RESUMED: if (newState < Fragment.RESUMED) { if (DEBUG) Log.v(TAG, "movefrom RESUMED: " + f); f.performPause(); dispatchOnFragmentPaused(f, false); } // fall through case Fragment.STARTED: if (newState < Fragment.STARTED) { if (DEBUG) Log.v(TAG, "movefrom STARTED: " + f); f.performStop(); dispatchOnFragmentStopped(f, false); } // fall through case Fragment.ACTIVITY_CREATED: if (newState < Fragment.ACTIVITY_CREATED) { if (DEBUG) Log.v(TAG, "movefrom ACTIVITY_CREATED: " + f); if (f.mView != null) { // Need to save the current view state if not // done already. if (mHost.onShouldSaveFragmentState(f) && f.mSavedViewState == null) { saveFragmentViewState(f); } } f.performDestroyView(); dispatchOnFragmentViewDestroyed(f, false); if (f.mView != null && f.mContainer != null) { // Stop any current animations: f.mContainer.endViewTransition(f.mView); f.mView.clearAnimation(); AnimationOrAnimator anim = null; if (mCurState > Fragment.INITIALIZING && !mDestroyed && f.mView.getVisibility() == View.VISIBLE && f.mPostponedAlpha >= 0) { anim = loadAnimation(f, transit, false, transitionStyle); } f.mPostponedAlpha = 0; if (anim != null) { animateRemoveFragment(f, anim, newState); } f.mContainer.removeView(f.mView); } f.mContainer = null; f.mView = null; // Set here to ensure that Observers are called after // the Fragment's view is set to null f.mViewLifecycleOwner = null; f.mViewLifecycleOwnerLiveData.setValue(null); f.mInnerView = null; f.mInLayout = false; } // fall through case Fragment.CREATED: if (newState < Fragment.CREATED) { if (mDestroyed) { // The fragment's containing activity is // being destroyed, but this fragment is // currently animating away. Stop the // animation right now -- it is not needed, // and we can't wait any more on destroying // the fragment. if (f.getAnimatingAway() != null) { View v = f.getAnimatingAway(); f.setAnimatingAway(null); v.clearAnimation(); } else if (f.getAnimator() != null) { Animator animator = f.getAnimator(); f.setAnimator(null); animator.cancel(); } } if (f.getAnimatingAway() != null || f.getAnimator() != null) { // We are waiting for the fragment's view to finish // animating away. Just make a note of the state // the fragment now should move to once the animation // is done. f.setStateAfterAnimating(newState); newState = Fragment.CREATED; } else { if (DEBUG) Log.v(TAG, "movefrom CREATED: " + f); if (!f.mRetaining) { f.performDestroy(); dispatchOnFragmentDestroyed(f, false); } else { f.mState = Fragment.INITIALIZING; } f.performDetach(); dispatchOnFragmentDetached(f, false); if (!keepActive) { if (!f.mRetaining) { makeInactive(f); } else { f.mHost = null; f.mParentFragment = null; f.mFragmentManager = null; } } } } } } if (f.mState != newState) { Log.w(TAG, "moveToState: Fragment state for " + f + " not updated inline; " + "expected state " + newState + " found " + f.mState); f.mState = newState; } } /** * Animates the removal of a fragment with the given animator or animation. After animating, * the fragment's view will be removed from the hierarchy. * * @param fragment The fragment to animate out * @param anim The animator or animation to run on the fragment's view * @param newState The final state after animating. */ private void animateRemoveFragment(@NonNull final Fragment fragment, @NonNull AnimationOrAnimator anim, final int newState) { final View viewToAnimate = fragment.mView; final ViewGroup container = fragment.mContainer; container.startViewTransition(viewToAnimate); fragment.setStateAfterAnimating(newState); if (anim.animation != null) { Animation animation = new EndViewTransitionAnimator(anim.animation, container, viewToAnimate); fragment.setAnimatingAway(fragment.mView); AnimationListener listener = getAnimationListener(animation); animation.setAnimationListener(new AnimationListenerWrapper(listener) { @Override public void onAnimationEnd(Animation animation) { super.onAnimationEnd(animation); // onAnimationEnd() comes during draw(), so there can still be some // draw events happening after this call. We don't want to detach // the view until after the onAnimationEnd() container.post(new Runnable() { @Override public void run() { if (fragment.getAnimatingAway() != null) { fragment.setAnimatingAway(null); moveToState(fragment, fragment.getStateAfterAnimating(), 0, 0, false); } } }); } }); setHWLayerAnimListenerIfAlpha(viewToAnimate, anim); fragment.mView.startAnimation(animation); } else { Animator animator = anim.animator; fragment.setAnimator(anim.animator); animator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator anim) { container.endViewTransition(viewToAnimate); // If an animator ends immediately, we can just pretend there is no animation. // When that happens the the fragment's view won't have been removed yet. Animator animator = fragment.getAnimator(); fragment.setAnimator(null); if (animator != null && container.indexOfChild(viewToAnimate) < 0) { moveToState(fragment, fragment.getStateAfterAnimating(), 0, 0, false); } } }); animator.setTarget(fragment.mView); setHWLayerAnimListenerIfAlpha(fragment.mView, anim); animator.start(); } } void moveToState(Fragment f) { moveToState(f, mCurState, 0, 0, false); } void ensureInflatedFragmentView(Fragment f) { if (f.mFromLayout && !f.mPerformedCreateView) { f.performCreateView(f.performGetLayoutInflater( f.mSavedFragmentState), null, f.mSavedFragmentState); if (f.mView != null) { f.mInnerView = f.mView; f.mView.setSaveFromParentEnabled(false); if (f.mHidden) f.mView.setVisibility(View.GONE); f.onViewCreated(f.mView, f.mSavedFragmentState); dispatchOnFragmentViewCreated(f, f.mView, f.mSavedFragmentState, false); } else { f.mInnerView = null; } } } /** * Fragments that have been shown or hidden don't have their visibility changed or * animations run during the {@link #showFragment(Fragment)} or {@link #hideFragment(Fragment)} * calls. After fragments are brought to their final state in * {@link #moveFragmentToExpectedState(Fragment)} the fragments that have been shown or * hidden must have their visibility changed and their animations started here. * * @param fragment The fragment with mHiddenChanged = true that should change its View's * visibility and start the show or hide animation. */ void completeShowHideFragment(final Fragment fragment) { if (fragment.mView != null) { AnimationOrAnimator anim = loadAnimation(fragment, fragment.getNextTransition(), !fragment.mHidden, fragment.getNextTransitionStyle()); if (anim != null && anim.animator != null) { anim.animator.setTarget(fragment.mView); if (fragment.mHidden) { if (fragment.isHideReplaced()) { fragment.setHideReplaced(false); } else { final ViewGroup container = fragment.mContainer; final View animatingView = fragment.mView; container.startViewTransition(animatingView); // Delay the actual hide operation until the animation finishes, // otherwise the fragment will just immediately disappear anim.animator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { container.endViewTransition(animatingView); animation.removeListener(this); if (fragment.mView != null) { fragment.mView.setVisibility(View.GONE); } } }); } } else { fragment.mView.setVisibility(View.VISIBLE); } setHWLayerAnimListenerIfAlpha(fragment.mView, anim); anim.animator.start(); } else { if (anim != null) { setHWLayerAnimListenerIfAlpha(fragment.mView, anim); fragment.mView.startAnimation(anim.animation); anim.animation.start(); } final int visibility = fragment.mHidden && !fragment.isHideReplaced() ? View.GONE : View.VISIBLE; fragment.mView.setVisibility(visibility); if (fragment.isHideReplaced()) { fragment.setHideReplaced(false); } } } if (fragment.mAdded && fragment.mHasMenu && fragment.mMenuVisible) { mNeedMenuInvalidate = true; } fragment.mHiddenChanged = false; fragment.onHiddenChanged(fragment.mHidden); } /** * Moves a fragment to its expected final state or the fragment manager's state, depending * on whether the fragment manager's state is raised properly. * * @param f The fragment to change. */ void moveFragmentToExpectedState(Fragment f) { if (f == null) { return; } int nextState = mCurState; if (f.mRemoving) { if (f.isInBackStack()) { nextState = Math.min(nextState, Fragment.CREATED); } else { nextState = Math.min(nextState, Fragment.INITIALIZING); } } moveToState(f, nextState, f.getNextTransition(), f.getNextTransitionStyle(), false); if (f.mView != null) { // Move the view if it is out of order Fragment underFragment = findFragmentUnder(f); if (underFragment != null) { final View underView = underFragment.mView; // make sure this fragment is in the right order. final ViewGroup container = f.mContainer; int underIndex = container.indexOfChild(underView); int viewIndex = container.indexOfChild(f.mView); if (viewIndex < underIndex) { container.removeViewAt(viewIndex); container.addView(f.mView, underIndex); } } if (f.mIsNewlyAdded && f.mContainer != null) { // Make it visible and run the animations if (f.mPostponedAlpha > 0f) { f.mView.setAlpha(f.mPostponedAlpha); } f.mPostponedAlpha = 0f; f.mIsNewlyAdded = false; // run animations: AnimationOrAnimator anim = loadAnimation(f, f.getNextTransition(), true, f.getNextTransitionStyle()); if (anim != null) { setHWLayerAnimListenerIfAlpha(f.mView, anim); if (anim.animation != null) { f.mView.startAnimation(anim.animation); } else { anim.animator.setTarget(f.mView); anim.animator.start(); } } } } if (f.mHiddenChanged) { completeShowHideFragment(f); } } /** * Changes the state of the fragment manager to {@code newState}. If the fragment manager * changes state or {@code always} is {@code true}, any fragments within it have their * states updated as well. * * @param newState The new state for the fragment manager * @param always If {@code true}, all fragments update their state, even * if {@code newState} matches the current fragment manager's state. */ void moveToState(int newState, boolean always) { if (mHost == null && newState != Fragment.INITIALIZING) { throw new IllegalStateException("No activity"); } if (!always && newState == mCurState) { return; } mCurState = newState; if (mActive != null) { // Must add them in the proper order. mActive fragments may be out of order final int numAdded = mAdded.size(); for (int i = 0; i < numAdded; i++) { Fragment f = mAdded.get(i); moveFragmentToExpectedState(f); } // Now iterate through all active fragments. These will include those that are removed // and detached. final int numActive = mActive.size(); for (int i = 0; i < numActive; i++) { Fragment f = mActive.valueAt(i); if (f != null && (f.mRemoving || f.mDetached) && !f.mIsNewlyAdded) { moveFragmentToExpectedState(f); } } startPendingDeferredFragments(); if (mNeedMenuInvalidate && mHost != null && mCurState == Fragment.RESUMED) { mHost.onSupportInvalidateOptionsMenu(); mNeedMenuInvalidate = false; } } } void startPendingDeferredFragments() { if (mActive == null) return; for (int i=0; i<mActive.size(); i++) { Fragment f = mActive.valueAt(i); if (f != null) { performPendingDeferredStart(f); } } } void makeActive(Fragment f) { if (f.mIndex >= 0) { return; } f.setIndex(mNextFragmentIndex++, mParent); if (mActive == null) { mActive = new SparseArray<>(); } mActive.put(f.mIndex, f); if (DEBUG) Log.v(TAG, "Allocated fragment index " + f); } void makeInactive(Fragment f) { if (f.mIndex < 0) { return; } if (DEBUG) Log.v(TAG, "Freeing fragment index " + f); // Don't remove yet. That happens in burpActive(). This prevents // concurrent modification while iterating over mActive mActive.put(f.mIndex, null); f.initState(); } public void addFragment(Fragment fragment, boolean moveToStateNow) { if (DEBUG) Log.v(TAG, "add: " + fragment); makeActive(fragment); if (!fragment.mDetached) { if (mAdded.contains(fragment)) { throw new IllegalStateException("Fragment already added: " + fragment); } synchronized (mAdded) { mAdded.add(fragment); } fragment.mAdded = true; fragment.mRemoving = false; if (fragment.mView == null) { fragment.mHiddenChanged = false; } if (fragment.mHasMenu && fragment.mMenuVisible) { mNeedMenuInvalidate = true; } if (moveToStateNow) { moveToState(fragment); } } } public void removeFragment(Fragment fragment) { if (DEBUG) Log.v(TAG, "remove: " + fragment + " nesting=" + fragment.mBackStackNesting); final boolean inactive = !fragment.isInBackStack(); if (!fragment.mDetached || inactive) { synchronized (mAdded) { mAdded.remove(fragment); } if (fragment.mHasMenu && fragment.mMenuVisible) { mNeedMenuInvalidate = true; } fragment.mAdded = false; fragment.mRemoving = true; } } /** * Marks a fragment as hidden to be later animated in with * {@link #completeShowHideFragment(Fragment)}. * * @param fragment The fragment to be shown. */ public void hideFragment(Fragment fragment) { if (DEBUG) Log.v(TAG, "hide: " + fragment); if (!fragment.mHidden) { fragment.mHidden = true; // Toggle hidden changed so that if a fragment goes through show/hide/show // it doesn't go through the animation. fragment.mHiddenChanged = !fragment.mHiddenChanged; } } /** * Marks a fragment as shown to be later animated in with * {@link #completeShowHideFragment(Fragment)}. * * @param fragment The fragment to be shown. */ public void showFragment(Fragment fragment) { if (DEBUG) Log.v(TAG, "show: " + fragment); if (fragment.mHidden) { fragment.mHidden = false; // Toggle hidden changed so that if a fragment goes through show/hide/show // it doesn't go through the animation. fragment.mHiddenChanged = !fragment.mHiddenChanged; } } public void detachFragment(Fragment fragment) { if (DEBUG) Log.v(TAG, "detach: " + fragment); if (!fragment.mDetached) { fragment.mDetached = true; if (fragment.mAdded) { // We are not already in back stack, so need to remove the fragment. if (DEBUG) Log.v(TAG, "remove from detach: " + fragment); synchronized (mAdded) { mAdded.remove(fragment); } if (fragment.mHasMenu && fragment.mMenuVisible) { mNeedMenuInvalidate = true; } fragment.mAdded = false; } } } public void attachFragment(Fragment fragment) { if (DEBUG) Log.v(TAG, "attach: " + fragment); if (fragment.mDetached) { fragment.mDetached = false; if (!fragment.mAdded) { if (mAdded.contains(fragment)) { throw new IllegalStateException("Fragment already added: " + fragment); } if (DEBUG) Log.v(TAG, "add from attach: " + fragment); synchronized (mAdded) { mAdded.add(fragment); } fragment.mAdded = true; if (fragment.mHasMenu && fragment.mMenuVisible) { mNeedMenuInvalidate = true; } } } } @Override @Nullable public Fragment findFragmentById(int id) { // First look through added fragments. for (int i = mAdded.size() - 1; i >= 0; i--) { Fragment f = mAdded.get(i); if (f != null && f.mFragmentId == id) { return f; } } if (mActive != null) { // Now for any known fragment. for (int i=mActive.size()-1; i>=0; i--) { Fragment f = mActive.valueAt(i); if (f != null && f.mFragmentId == id) { return f; } } } return null; } @Override @Nullable public Fragment findFragmentByTag(@Nullable String tag) { if (tag != null) { // First look through added fragments. for (int i=mAdded.size()-1; i>=0; i--) { Fragment f = mAdded.get(i); if (f != null && tag.equals(f.mTag)) { return f; } } } if (mActive != null && tag != null) { // Now for any known fragment. for (int i=mActive.size()-1; i>=0; i--) { Fragment f = mActive.valueAt(i); if (f != null && tag.equals(f.mTag)) { return f; } } } return null; } public Fragment findFragmentByWho(String who) { if (mActive != null && who != null) { for (int i=mActive.size()-1; i>=0; i--) { Fragment f = mActive.valueAt(i); if (f != null && (f=f.findFragmentByWho(who)) != null) { return f; } } } return null; } private void checkStateLoss() { if (isStateSaved()) { throw new IllegalStateException( "Can not perform this action after onSaveInstanceState"); } if (mNoTransactionsBecause != null) { throw new IllegalStateException( "Can not perform this action inside of " + mNoTransactionsBecause); } } @Override public boolean isStateSaved() { // See saveAllState() for the explanation of this. We do this for // all platform versions, to keep our behavior more consistent between // them. return mStateSaved || mStopped; } /** * Adds an action to the queue of pending actions. * * @param action the action to add * @param allowStateLoss whether to allow loss of state information * @throws IllegalStateException if the activity has been destroyed */ public void enqueueAction(OpGenerator action, boolean allowStateLoss) { if (!allowStateLoss) { checkStateLoss(); } synchronized (this) { if (mDestroyed || mHost == null) { if (allowStateLoss) { // This FragmentManager isn't attached, so drop the entire transaction. return; } throw new IllegalStateException("Activity has been destroyed"); } if (mPendingActions == null) { mPendingActions = new ArrayList<>(); } mPendingActions.add(action); scheduleCommit(); } } /** * Schedules the execution when one hasn't been scheduled already. This should happen * the first time {@link #enqueueAction(OpGenerator, boolean)} is called or when * a postponed transaction has been started with * {@link Fragment#startPostponedEnterTransition()} */ @SuppressWarnings("WeakerAccess") /* synthetic access */ void scheduleCommit() { synchronized (this) { boolean postponeReady = mPostponedTransactions != null && !mPostponedTransactions.isEmpty(); boolean pendingReady = mPendingActions != null && mPendingActions.size() == 1; if (postponeReady || pendingReady) { mHost.getHandler().removeCallbacks(mExecCommit); mHost.getHandler().post(mExecCommit); } } } public int allocBackStackIndex(BackStackRecord bse) { synchronized (this) { if (mAvailBackStackIndices == null || mAvailBackStackIndices.size() <= 0) { if (mBackStackIndices == null) { mBackStackIndices = new ArrayList<BackStackRecord>(); } int index = mBackStackIndices.size(); if (DEBUG) Log.v(TAG, "Setting back stack index " + index + " to " + bse); mBackStackIndices.add(bse); return index; } else { int index = mAvailBackStackIndices.remove(mAvailBackStackIndices.size()-1); if (DEBUG) Log.v(TAG, "Adding back stack index " + index + " with " + bse); mBackStackIndices.set(index, bse); return index; } } } public void setBackStackIndex(int index, BackStackRecord bse) { synchronized (this) { if (mBackStackIndices == null) { mBackStackIndices = new ArrayList<BackStackRecord>(); } int N = mBackStackIndices.size(); if (index < N) { if (DEBUG) Log.v(TAG, "Setting back stack index " + index + " to " + bse); mBackStackIndices.set(index, bse); } else { while (N < index) { mBackStackIndices.add(null); if (mAvailBackStackIndices == null) { mAvailBackStackIndices = new ArrayList<Integer>(); } if (DEBUG) Log.v(TAG, "Adding available back stack index " + N); mAvailBackStackIndices.add(N); N++; } if (DEBUG) Log.v(TAG, "Adding back stack index " + index + " with " + bse); mBackStackIndices.add(bse); } } } public void freeBackStackIndex(int index) { synchronized (this) { mBackStackIndices.set(index, null); if (mAvailBackStackIndices == null) { mAvailBackStackIndices = new ArrayList<Integer>(); } if (DEBUG) Log.v(TAG, "Freeing back stack index " + index); mAvailBackStackIndices.add(index); } } /** * Broken out from exec*, this prepares for gathering and executing operations. * * @param allowStateLoss true if state loss should be ignored or false if it should be * checked. */ private void ensureExecReady(boolean allowStateLoss) { if (mExecutingActions) { throw new IllegalStateException("FragmentManager is already executing transactions"); } if (mHost == null) { throw new IllegalStateException("Fragment host has been destroyed"); } if (Looper.myLooper() != mHost.getHandler().getLooper()) { throw new IllegalStateException("Must be called from main thread of fragment host"); } if (!allowStateLoss) { checkStateLoss(); } if (mTmpRecords == null) { mTmpRecords = new ArrayList<>(); mTmpIsPop = new ArrayList<>(); } mExecutingActions = true; try { executePostponedTransaction(null, null); } finally { mExecutingActions = false; } } public void execSingleAction(OpGenerator action, boolean allowStateLoss) { if (allowStateLoss && (mHost == null || mDestroyed)) { // This FragmentManager isn't attached, so drop the entire transaction. return; } ensureExecReady(allowStateLoss); if (action.generateOps(mTmpRecords, mTmpIsPop)) { mExecutingActions = true; try { removeRedundantOperationsAndExecute(mTmpRecords, mTmpIsPop); } finally { cleanupExec(); } } doPendingDeferredStart(); burpActive(); } /** * Broken out of exec*, this cleans up the mExecutingActions and the temporary structures * used in executing operations. */ private void cleanupExec() { mExecutingActions = false; mTmpIsPop.clear(); mTmpRecords.clear(); } /** * Only call from main thread! */ public boolean execPendingActions() { ensureExecReady(true); boolean didSomething = false; while (generateOpsForPendingActions(mTmpRecords, mTmpIsPop)) { mExecutingActions = true; try { removeRedundantOperationsAndExecute(mTmpRecords, mTmpIsPop); } finally { cleanupExec(); } didSomething = true; } doPendingDeferredStart(); burpActive(); return didSomething; } /** * Complete the execution of transactions that have previously been postponed, but are * now ready. */ private void executePostponedTransaction(ArrayList<BackStackRecord> records, ArrayList<Boolean> isRecordPop) { int numPostponed = mPostponedTransactions == null ? 0 : mPostponedTransactions.size(); for (int i = 0; i < numPostponed; i++) { StartEnterTransitionListener listener = mPostponedTransactions.get(i); if (records != null && !listener.mIsBack) { int index = records.indexOf(listener.mRecord); if (index != -1 && isRecordPop.get(index)) { listener.cancelTransaction(); continue; } } if (listener.isReady() || (records != null && listener.mRecord.interactsWith(records, 0, records.size()))) { mPostponedTransactions.remove(i); i--; numPostponed--; int index; if (records != null && !listener.mIsBack && (index = records.indexOf(listener.mRecord)) != -1 && isRecordPop.get(index)) { // This is popping a postponed transaction listener.cancelTransaction(); } else { listener.completeTransaction(); } } } } /** * Remove redundant BackStackRecord operations and executes them. This method merges operations * of proximate records that allow reordering. See * {@link FragmentTransaction#setReorderingAllowed(boolean)}. * <p> * For example, a transaction that adds to the back stack and then another that pops that * back stack record will be optimized to remove the unnecessary operation. * <p> * Likewise, two transactions committed that are executed at the same time will be optimized * to remove the redundant operations as well as two pop operations executed together. * * @param records The records pending execution * @param isRecordPop The direction that these records are being run. */ private void removeRedundantOperationsAndExecute(ArrayList<BackStackRecord> records, ArrayList<Boolean> isRecordPop) { if (records == null || records.isEmpty()) { return; } if (isRecordPop == null || records.size() != isRecordPop.size()) { throw new IllegalStateException("Internal error with the back stack records"); } // Force start of any postponed transactions that interact with scheduled transactions: executePostponedTransaction(records, isRecordPop); final int numRecords = records.size(); int startIndex = 0; for (int recordNum = 0; recordNum < numRecords; recordNum++) { final boolean canReorder = records.get(recordNum).mReorderingAllowed; if (!canReorder) { // execute all previous transactions if (startIndex != recordNum) { executeOpsTogether(records, isRecordPop, startIndex, recordNum); } // execute all pop operations that don't allow reordering together or // one add operation int reorderingEnd = recordNum + 1; if (isRecordPop.get(recordNum)) { while (reorderingEnd < numRecords && isRecordPop.get(reorderingEnd) && !records.get(reorderingEnd).mReorderingAllowed) { reorderingEnd++; } } executeOpsTogether(records, isRecordPop, recordNum, reorderingEnd); startIndex = reorderingEnd; recordNum = reorderingEnd - 1; } } if (startIndex != numRecords) { executeOpsTogether(records, isRecordPop, startIndex, numRecords); } } /** * Executes a subset of a list of BackStackRecords, all of which either allow reordering or * do not allow ordering. * @param records A list of BackStackRecords that are to be executed * @param isRecordPop The direction that these records are being run. * @param startIndex The index of the first record in <code>records</code> to be executed * @param endIndex One more than the final record index in <code>records</code> to executed. */ private void executeOpsTogether(ArrayList<BackStackRecord> records, ArrayList<Boolean> isRecordPop, int startIndex, int endIndex) { final boolean allowReordering = records.get(startIndex).mReorderingAllowed; boolean addToBackStack = false; if (mTmpAddedFragments == null) { mTmpAddedFragments = new ArrayList<>(); } else { mTmpAddedFragments.clear(); } mTmpAddedFragments.addAll(mAdded); Fragment oldPrimaryNav = getPrimaryNavigationFragment(); for (int recordNum = startIndex; recordNum < endIndex; recordNum++) { final BackStackRecord record = records.get(recordNum); final boolean isPop = isRecordPop.get(recordNum); if (!isPop) { oldPrimaryNav = record.expandOps(mTmpAddedFragments, oldPrimaryNav); } else { oldPrimaryNav = record.trackAddedFragmentsInPop(mTmpAddedFragments, oldPrimaryNav); } addToBackStack = addToBackStack || record.mAddToBackStack; } mTmpAddedFragments.clear(); if (!allowReordering) { FragmentTransition.startTransitions(this, records, isRecordPop, startIndex, endIndex, false); } executeOps(records, isRecordPop, startIndex, endIndex); int postponeIndex = endIndex; if (allowReordering) { ArraySet<Fragment> addedFragments = new ArraySet<>(); addAddedFragments(addedFragments); postponeIndex = postponePostponableTransactions(records, isRecordPop, startIndex, endIndex, addedFragments); makeRemovedFragmentsInvisible(addedFragments); } if (postponeIndex != startIndex && allowReordering) { // need to run something now FragmentTransition.startTransitions(this, records, isRecordPop, startIndex, postponeIndex, true); moveToState(mCurState, true); } for (int recordNum = startIndex; recordNum < endIndex; recordNum++) { final BackStackRecord record = records.get(recordNum); final boolean isPop = isRecordPop.get(recordNum); if (isPop && record.mIndex >= 0) { freeBackStackIndex(record.mIndex); record.mIndex = -1; } record.runOnCommitRunnables(); } if (addToBackStack) { reportBackStackChanged(); } } /** * Any fragments that were removed because they have been postponed should have their views * made invisible by setting their alpha to 0. * * @param fragments The fragments that were added during operation execution. Only the ones * that are no longer added will have their alpha changed. */ private void makeRemovedFragmentsInvisible(ArraySet<Fragment> fragments) { final int numAdded = fragments.size(); for (int i = 0; i < numAdded; i++) { final Fragment fragment = fragments.valueAt(i); if (!fragment.mAdded) { final View view = fragment.getView(); fragment.mPostponedAlpha = view.getAlpha(); view.setAlpha(0f); } } } /** * Examine all transactions and determine which ones are marked as postponed. Those will * have their operations rolled back and moved to the end of the record list (up to endIndex). * It will also add the postponed transaction to the queue. * * @param records A list of BackStackRecords that should be checked. * @param isRecordPop The direction that these records are being run. * @param startIndex The index of the first record in <code>records</code> to be checked * @param endIndex One more than the final record index in <code>records</code> to be checked. * @return The index of the first postponed transaction or endIndex if no transaction was * postponed. */ private int postponePostponableTransactions(ArrayList<BackStackRecord> records, ArrayList<Boolean> isRecordPop, int startIndex, int endIndex, ArraySet<Fragment> added) { int postponeIndex = endIndex; for (int i = endIndex - 1; i >= startIndex; i--) { final BackStackRecord record = records.get(i); final boolean isPop = isRecordPop.get(i); boolean isPostponed = record.isPostponed() && !record.interactsWith(records, i + 1, endIndex); if (isPostponed) { if (mPostponedTransactions == null) { mPostponedTransactions = new ArrayList<>(); } StartEnterTransitionListener listener = new StartEnterTransitionListener(record, isPop); mPostponedTransactions.add(listener); record.setOnStartPostponedListener(listener); // roll back the transaction if (isPop) { record.executeOps(); } else { record.executePopOps(false); } // move to the end postponeIndex--; if (i != postponeIndex) { records.remove(i); records.add(postponeIndex, record); } // different views may be visible now addAddedFragments(added); } } return postponeIndex; } /** * When a postponed transaction is ready to be started, this completes the transaction, * removing, hiding, or showing views as well as starting the animations and transitions. * <p> * {@code runtransitions} is set to false when the transaction postponement was interrupted * abnormally -- normally by a new transaction being started that affects the postponed * transaction. * * @param record The transaction to run * @param isPop true if record is popping or false if it is adding * @param runTransitions true if the fragment transition should be run or false otherwise. * @param moveToState true if the state should be changed after executing the operations. * This is false when the transaction is canceled when a postponed * transaction is popped. */ @SuppressWarnings("WeakerAccess") /* synthetic access */ void completeExecute(BackStackRecord record, boolean isPop, boolean runTransitions, boolean moveToState) { if (isPop) { record.executePopOps(moveToState); } else { record.executeOps(); } ArrayList<BackStackRecord> records = new ArrayList<>(1); ArrayList<Boolean> isRecordPop = new ArrayList<>(1); records.add(record); isRecordPop.add(isPop); if (runTransitions) { FragmentTransition.startTransitions(this, records, isRecordPop, 0, 1, true); } if (moveToState) { moveToState(mCurState, true); } if (mActive != null) { final int numActive = mActive.size(); for (int i = 0; i < numActive; i++) { // Allow added fragments to be removed during the pop since we aren't going // to move them to the final state with moveToState(mCurState). Fragment fragment = mActive.valueAt(i); if (fragment != null && fragment.mView != null && fragment.mIsNewlyAdded && record.interactsWith(fragment.mContainerId)) { if (fragment.mPostponedAlpha > 0) { fragment.mView.setAlpha(fragment.mPostponedAlpha); } if (moveToState) { fragment.mPostponedAlpha = 0; } else { fragment.mPostponedAlpha = -1; fragment.mIsNewlyAdded = false; } } } } } /** * Find a fragment within the fragment's container whose View should be below the passed * fragment. {@code null} is returned when the fragment has no View or if there should be * no fragment with a View below the given fragment. * * As an example, if mAdded has two Fragments with Views sharing the same container: * FragmentA * FragmentB * * Then, when processing FragmentB, FragmentA will be returned. If, however, FragmentA * had no View, null would be returned. * * @param f The fragment that may be on top of another fragment. * @return The fragment with a View under f, if one exists or null if f has no View or * there are no fragments with Views in the same container. */ private Fragment findFragmentUnder(Fragment f) { final ViewGroup container = f.mContainer; final View view = f.mView; if (container == null || view == null) { return null; } final int fragmentIndex = mAdded.indexOf(f); for (int i = fragmentIndex - 1; i >= 0; i--) { Fragment underFragment = mAdded.get(i); if (underFragment.mContainer == container && underFragment.mView != null) { // Found the fragment under this one return underFragment; } } return null; } /** * Run the operations in the BackStackRecords, either to push or pop. * * @param records The list of records whose operations should be run. * @param isRecordPop The direction that these records are being run. * @param startIndex The index of the first entry in records to run. * @param endIndex One past the index of the final entry in records to run. */ private static void executeOps(ArrayList<BackStackRecord> records, ArrayList<Boolean> isRecordPop, int startIndex, int endIndex) { for (int i = startIndex; i < endIndex; i++) { final BackStackRecord record = records.get(i); final boolean isPop = isRecordPop.get(i); if (isPop) { record.bumpBackStackNesting(-1); // Only execute the add operations at the end of // all transactions. boolean moveToState = i == (endIndex - 1); record.executePopOps(moveToState); } else { record.bumpBackStackNesting(1); record.executeOps(); } } } /** * Ensure that fragments that are added are moved to at least the CREATED state. * Any newly-added Views are inserted into {@code added} so that the Transaction can be * postponed with {@link Fragment#postponeEnterTransition()}. They will later be made * invisible (by setting their alpha to 0) if they have been removed when postponed. */ private void addAddedFragments(ArraySet<Fragment> added) { if (mCurState < Fragment.CREATED) { return; } // We want to leave the fragment in the started state final int state = Math.min(mCurState, Fragment.STARTED); final int numAdded = mAdded.size(); for (int i = 0; i < numAdded; i++) { Fragment fragment = mAdded.get(i); if (fragment.mState < state) { moveToState(fragment, state, fragment.getNextAnim(), fragment.getNextTransition(), false); if (fragment.mView != null && !fragment.mHidden && fragment.mIsNewlyAdded) { added.add(fragment); } } } } /** * Starts all postponed transactions regardless of whether they are ready or not. */ private void forcePostponedTransactions() { if (mPostponedTransactions != null) { while (!mPostponedTransactions.isEmpty()) { mPostponedTransactions.remove(0).completeTransaction(); } } } /** * Ends the animations of fragments so that they immediately reach the end state. * This is used prior to saving the state so that the correct state is saved. */ private void endAnimatingAwayFragments() { final int numFragments = mActive == null ? 0 : mActive.size(); for (int i = 0; i < numFragments; i++) { Fragment fragment = mActive.valueAt(i); if (fragment != null) { if (fragment.getAnimatingAway() != null) { // Give up waiting for the animation and just end it. final int stateAfterAnimating = fragment.getStateAfterAnimating(); final View animatingAway = fragment.getAnimatingAway(); Animation animation = animatingAway.getAnimation(); if (animation != null) { animation.cancel(); // force-clear the animation, as Animation#cancel() doesn't work prior to N, // and will instead cause the animation to infinitely loop animatingAway.clearAnimation(); } fragment.setAnimatingAway(null); moveToState(fragment, stateAfterAnimating, 0, 0, false); } else if (fragment.getAnimator() != null) { fragment.getAnimator().end(); } } } } /** * Adds all records in the pending actions to records and whether they are add or pop * operations to isPop. After executing, the pending actions will be empty. * * @param records All pending actions will generate BackStackRecords added to this. * This contains the transactions, in order, to execute. * @param isPop All pending actions will generate booleans to add to this. This contains * an entry for each entry in records to indicate whether or not it is a * pop action. */ private boolean generateOpsForPendingActions(ArrayList<BackStackRecord> records, ArrayList<Boolean> isPop) { boolean didSomething = false; synchronized (this) { if (mPendingActions == null || mPendingActions.size() == 0) { return false; } final int numActions = mPendingActions.size(); for (int i = 0; i < numActions; i++) { didSomething |= mPendingActions.get(i).generateOps(records, isPop); } mPendingActions.clear(); mHost.getHandler().removeCallbacks(mExecCommit); } return didSomething; } void doPendingDeferredStart() { if (mHavePendingDeferredStart) { mHavePendingDeferredStart = false; startPendingDeferredFragments(); } } void reportBackStackChanged() { if (mBackStackChangeListeners != null) { for (int i=0; i<mBackStackChangeListeners.size(); i++) { mBackStackChangeListeners.get(i).onBackStackChanged(); } } } void addBackStackState(BackStackRecord state) { if (mBackStack == null) { mBackStack = new ArrayList<BackStackRecord>(); } mBackStack.add(state); } @SuppressWarnings("unused") boolean popBackStackState(ArrayList<BackStackRecord> records, ArrayList<Boolean> isRecordPop, String name, int id, int flags) { if (mBackStack == null) { return false; } if (name == null && id < 0 && (flags & POP_BACK_STACK_INCLUSIVE) == 0) { int last = mBackStack.size() - 1; if (last < 0) { return false; } records.add(mBackStack.remove(last)); isRecordPop.add(true); } else { int index = -1; if (name != null || id >= 0) { // If a name or ID is specified, look for that place in // the stack. index = mBackStack.size()-1; while (index >= 0) { BackStackRecord bss = mBackStack.get(index); if (name != null && name.equals(bss.getName())) { break; } if (id >= 0 && id == bss.mIndex) { break; } index--; } if (index < 0) { return false; } if ((flags&POP_BACK_STACK_INCLUSIVE) != 0) { index--; // Consume all following entries that match. while (index >= 0) { BackStackRecord bss = mBackStack.get(index); if ((name != null && name.equals(bss.getName())) || (id >= 0 && id == bss.mIndex)) { index--; continue; } break; } } } if (index == mBackStack.size()-1) { return false; } for (int i = mBackStack.size() - 1; i > index; i--) { records.add(mBackStack.remove(i)); isRecordPop.add(true); } } return true; } FragmentManagerNonConfig retainNonConfig() { setRetaining(mSavedNonConfig); return mSavedNonConfig; } /** * Recurse the FragmentManagerNonConfig fragments and set the mRetaining to true. This * was previously done while saving the non-config state, but that has been moved to * {@link #saveNonConfig()} called from {@link #saveAllState()}. If mRetaining is set too * early, the fragment won't be destroyed when the FragmentManager is destroyed. */ private static void setRetaining(FragmentManagerNonConfig nonConfig) { if (nonConfig == null) { return; } List<Fragment> fragments = nonConfig.getFragments(); if (fragments != null) { for (Fragment fragment : fragments) { fragment.mRetaining = true; } } List<FragmentManagerNonConfig> children = nonConfig.getChildNonConfigs(); if (children != null) { for (FragmentManagerNonConfig child : children) { setRetaining(child); } } } void saveNonConfig() { ArrayList<Fragment> fragments = null; ArrayList<FragmentManagerNonConfig> childFragments = null; ArrayList<ViewModelStore> viewModelStores = null; if (mActive != null) { for (int i=0; i<mActive.size(); i++) { Fragment f = mActive.valueAt(i); if (f != null) { if (f.mRetainInstance) { if (fragments == null) { fragments = new ArrayList<Fragment>(); } fragments.add(f); f.mTargetIndex = f.mTarget != null ? f.mTarget.mIndex : -1; if (DEBUG) Log.v(TAG, "retainNonConfig: keeping retained " + f); } FragmentManagerNonConfig child; if (f.mChildFragmentManager != null) { f.mChildFragmentManager.saveNonConfig(); child = f.mChildFragmentManager.mSavedNonConfig; } else { // f.mChildNonConfig may be not null, when the parent fragment is // in the backstack. child = f.mChildNonConfig; } if (childFragments == null && child != null) { childFragments = new ArrayList<>(mActive.size()); for (int j = 0; j < i; j++) { childFragments.add(null); } } if (childFragments != null) { childFragments.add(child); } if (viewModelStores == null && f.mViewModelStore != null) { viewModelStores = new ArrayList<>(mActive.size()); for (int j = 0; j < i; j++) { viewModelStores.add(null); } } if (viewModelStores != null) { viewModelStores.add(f.mViewModelStore); } } } } if (fragments == null && childFragments == null && viewModelStores == null) { mSavedNonConfig = null; } else { mSavedNonConfig = new FragmentManagerNonConfig(fragments, childFragments, viewModelStores); } } void saveFragmentViewState(Fragment f) { if (f.mInnerView == null) { return; } if (mStateArray == null) { mStateArray = new SparseArray<Parcelable>(); } else { mStateArray.clear(); } f.mInnerView.saveHierarchyState(mStateArray); if (mStateArray.size() > 0) { f.mSavedViewState = mStateArray; mStateArray = null; } } Bundle saveFragmentBasicState(Fragment f) { Bundle result = null; if (mStateBundle == null) { mStateBundle = new Bundle(); } f.performSaveInstanceState(mStateBundle); dispatchOnFragmentSaveInstanceState(f, mStateBundle, false); if (!mStateBundle.isEmpty()) { result = mStateBundle; mStateBundle = null; } if (f.mView != null) { saveFragmentViewState(f); } if (f.mSavedViewState != null) { if (result == null) { result = new Bundle(); } result.putSparseParcelableArray( FragmentManagerImpl.VIEW_STATE_TAG, f.mSavedViewState); } if (!f.mUserVisibleHint) { if (result == null) { result = new Bundle(); } // Only add this if it's not the default value result.putBoolean(FragmentManagerImpl.USER_VISIBLE_HINT_TAG, f.mUserVisibleHint); } return result; } Parcelable saveAllState() { // Make sure all pending operations have now been executed to get // our state update-to-date. forcePostponedTransactions(); endAnimatingAwayFragments(); execPendingActions(); mStateSaved = true; mSavedNonConfig = null; if (mActive == null || mActive.size() <= 0) { return null; } // First collect all active fragments. int N = mActive.size(); FragmentState[] active = new FragmentState[N]; boolean haveFragments = false; for (int i=0; i<N; i++) { Fragment f = mActive.valueAt(i); if (f != null) { if (f.mIndex < 0) { throwException(new IllegalStateException( "Failure saving state: active " + f + " has cleared index: " + f.mIndex)); } haveFragments = true; FragmentState fs = new FragmentState(f); active[i] = fs; if (f.mState > Fragment.INITIALIZING && fs.mSavedFragmentState == null) { fs.mSavedFragmentState = saveFragmentBasicState(f); if (f.mTarget != null) { if (f.mTarget.mIndex < 0) { throwException(new IllegalStateException( "Failure saving state: " + f + " has target not in fragment manager: " + f.mTarget)); } if (fs.mSavedFragmentState == null) { fs.mSavedFragmentState = new Bundle(); } putFragment(fs.mSavedFragmentState, FragmentManagerImpl.TARGET_STATE_TAG, f.mTarget); if (f.mTargetRequestCode != 0) { fs.mSavedFragmentState.putInt( FragmentManagerImpl.TARGET_REQUEST_CODE_STATE_TAG, f.mTargetRequestCode); } } } else { fs.mSavedFragmentState = f.mSavedFragmentState; } if (DEBUG) Log.v(TAG, "Saved state of " + f + ": " + fs.mSavedFragmentState); } } if (!haveFragments) { if (DEBUG) Log.v(TAG, "saveAllState: no fragments!"); return null; } int[] added = null; BackStackState[] backStack = null; // Build list of currently added fragments. N = mAdded.size(); if (N > 0) { added = new int[N]; for (int i = 0; i < N; i++) { added[i] = mAdded.get(i).mIndex; if (added[i] < 0) { throwException(new IllegalStateException( "Failure saving state: active " + mAdded.get(i) + " has cleared index: " + added[i])); } if (DEBUG) { Log.v(TAG, "saveAllState: adding fragment #" + i + ": " + mAdded.get(i)); } } } // Now save back stack. if (mBackStack != null) { N = mBackStack.size(); if (N > 0) { backStack = new BackStackState[N]; for (int i=0; i<N; i++) { backStack[i] = new BackStackState(mBackStack.get(i)); if (DEBUG) Log.v(TAG, "saveAllState: adding back stack #" + i + ": " + mBackStack.get(i)); } } } FragmentManagerState fms = new FragmentManagerState(); fms.mActive = active; fms.mAdded = added; fms.mBackStack = backStack; if (mPrimaryNav != null) { fms.mPrimaryNavActiveIndex = mPrimaryNav.mIndex; } fms.mNextFragmentIndex = mNextFragmentIndex; saveNonConfig(); return fms; } void restoreAllState(Parcelable state, FragmentManagerNonConfig nonConfig) { // If there is no saved state at all, then there can not be // any nonConfig fragments either, so that is that. if (state == null) return; FragmentManagerState fms = (FragmentManagerState)state; if (fms.mActive == null) return; List<FragmentManagerNonConfig> childNonConfigs = null; List<ViewModelStore> viewModelStores = null; // First re-attach any non-config instances we are retaining back // to their saved state, so we don't try to instantiate them again. if (nonConfig != null) { List<Fragment> nonConfigFragments = nonConfig.getFragments(); childNonConfigs = nonConfig.getChildNonConfigs(); viewModelStores = nonConfig.getViewModelStores(); final int count = nonConfigFragments != null ? nonConfigFragments.size() : 0; for (int i = 0; i < count; i++) { Fragment f = nonConfigFragments.get(i); if (DEBUG) Log.v(TAG, "restoreAllState: re-attaching retained " + f); int index = 0; // index into fms.mActive while (index < fms.mActive.length && fms.mActive[index].mIndex != f.mIndex) { index++; } if (index == fms.mActive.length) { throwException(new IllegalStateException("Could not find active fragment " + "with index " + f.mIndex)); } FragmentState fs = fms.mActive[index]; fs.mInstance = f; f.mSavedViewState = null; f.mBackStackNesting = 0; f.mInLayout = false; f.mAdded = false; f.mTarget = null; if (fs.mSavedFragmentState != null) { fs.mSavedFragmentState.setClassLoader(mHost.getContext().getClassLoader()); f.mSavedViewState = fs.mSavedFragmentState.getSparseParcelableArray( FragmentManagerImpl.VIEW_STATE_TAG); f.mSavedFragmentState = fs.mSavedFragmentState; } } } // Build the full list of active fragments, instantiating them from // their saved state. mActive = new SparseArray<>(fms.mActive.length); for (int i=0; i<fms.mActive.length; i++) { FragmentState fs = fms.mActive[i]; if (fs != null) { FragmentManagerNonConfig childNonConfig = null; if (childNonConfigs != null && i < childNonConfigs.size()) { childNonConfig = childNonConfigs.get(i); } ViewModelStore viewModelStore = null; if (viewModelStores != null && i < viewModelStores.size()) { viewModelStore = viewModelStores.get(i); } Fragment f = fs.instantiate(mHost, mContainer, mParent, childNonConfig, viewModelStore); if (DEBUG) Log.v(TAG, "restoreAllState: active #" + i + ": " + f); mActive.put(f.mIndex, f); // Now that the fragment is instantiated (or came from being // retained above), clear mInstance in case we end up re-restoring // from this FragmentState again. fs.mInstance = null; } } // Update the target of all retained fragments. if (nonConfig != null) { List<Fragment> nonConfigFragments = nonConfig.getFragments(); final int count = nonConfigFragments != null ? nonConfigFragments.size() : 0; for (int i = 0; i < count; i++) { Fragment f = nonConfigFragments.get(i); if (f.mTargetIndex >= 0) { f.mTarget = mActive.get(f.mTargetIndex); if (f.mTarget == null) { Log.w(TAG, "Re-attaching retained fragment " + f + " target no longer exists: " + f.mTargetIndex); } } } } // Build the list of currently added fragments. mAdded.clear(); if (fms.mAdded != null) { for (int i=0; i<fms.mAdded.length; i++) { Fragment f = mActive.get(fms.mAdded[i]); if (f == null) { throwException(new IllegalStateException( "No instantiated fragment for index #" + fms.mAdded[i])); } f.mAdded = true; if (DEBUG) Log.v(TAG, "restoreAllState: added #" + i + ": " + f); if (mAdded.contains(f)) { throw new IllegalStateException("Already added!"); } synchronized (mAdded) { mAdded.add(f); } } } // Build the back stack. if (fms.mBackStack != null) { mBackStack = new ArrayList<BackStackRecord>(fms.mBackStack.length); for (int i=0; i<fms.mBackStack.length; i++) { BackStackRecord bse = fms.mBackStack[i].instantiate(this); if (DEBUG) { Log.v(TAG, "restoreAllState: back stack #" + i + " (index " + bse.mIndex + "): " + bse); LogWriter logw = new LogWriter(TAG); PrintWriter pw = new PrintWriter(logw); bse.dump(" ", pw, false); pw.close(); } mBackStack.add(bse); if (bse.mIndex >= 0) { setBackStackIndex(bse.mIndex, bse); } } } else { mBackStack = null; } if (fms.mPrimaryNavActiveIndex >= 0) { mPrimaryNav = mActive.get(fms.mPrimaryNavActiveIndex); } this.mNextFragmentIndex = fms.mNextFragmentIndex; } /** * To prevent list modification errors, mActive sets values to null instead of * removing them when the Fragment becomes inactive. This cleans up the list at the * end of executing the transactions. */ private void burpActive() { if (mActive != null) { for (int i = mActive.size() - 1; i >= 0; i--) { if (mActive.valueAt(i) == null) { mActive.delete(mActive.keyAt(i)); } } } } public void attachController(FragmentHostCallback host, FragmentContainer container, Fragment parent) { if (mHost != null) throw new IllegalStateException("Already attached"); mHost = host; mContainer = container; mParent = parent; } public void noteStateNotSaved() { mSavedNonConfig = null; mStateSaved = false; mStopped = false; final int addedCount = mAdded.size(); for (int i = 0; i < addedCount; i++) { Fragment fragment = mAdded.get(i); if (fragment != null) { fragment.noteStateNotSaved(); } } } public void dispatchCreate() { mStateSaved = false; mStopped = false; dispatchStateChange(Fragment.CREATED); } public void dispatchActivityCreated() { mStateSaved = false; mStopped = false; dispatchStateChange(Fragment.ACTIVITY_CREATED); } public void dispatchStart() { mStateSaved = false; mStopped = false; dispatchStateChange(Fragment.STARTED); } public void dispatchResume() { mStateSaved = false; mStopped = false; dispatchStateChange(Fragment.RESUMED); } public void dispatchPause() { dispatchStateChange(Fragment.STARTED); } public void dispatchStop() { mStopped = true; dispatchStateChange(Fragment.ACTIVITY_CREATED); } public void dispatchDestroyView() { dispatchStateChange(Fragment.CREATED); } public void dispatchDestroy() { mDestroyed = true; execPendingActions(); dispatchStateChange(Fragment.INITIALIZING); mHost = null; mContainer = null; mParent = null; } private void dispatchStateChange(int nextState) { try { mExecutingActions = true; moveToState(nextState, false); } finally { mExecutingActions = false; } execPendingActions(); } public void dispatchMultiWindowModeChanged(boolean isInMultiWindowMode) { for (int i = mAdded.size() - 1; i >= 0; --i) { final Fragment f = mAdded.get(i); if (f != null) { f.performMultiWindowModeChanged(isInMultiWindowMode); } } } public void dispatchPictureInPictureModeChanged(boolean isInPictureInPictureMode) { for (int i = mAdded.size() - 1; i >= 0; --i) { final Fragment f = mAdded.get(i); if (f != null) { f.performPictureInPictureModeChanged(isInPictureInPictureMode); } } } public void dispatchConfigurationChanged(Configuration newConfig) { for (int i = 0; i < mAdded.size(); i++) { Fragment f = mAdded.get(i); if (f != null) { f.performConfigurationChanged(newConfig); } } } public void dispatchLowMemory() { for (int i = 0; i < mAdded.size(); i++) { Fragment f = mAdded.get(i); if (f != null) { f.performLowMemory(); } } } public boolean dispatchCreateOptionsMenu(Menu menu, MenuInflater inflater) { if (mCurState < Fragment.CREATED) { return false; } boolean show = false; ArrayList<Fragment> newMenus = null; for (int i = 0; i < mAdded.size(); i++) { Fragment f = mAdded.get(i); if (f != null) { if (f.performCreateOptionsMenu(menu, inflater)) { show = true; if (newMenus == null) { newMenus = new ArrayList<Fragment>(); } newMenus.add(f); } } } if (mCreatedMenus != null) { for (int i=0; i<mCreatedMenus.size(); i++) { Fragment f = mCreatedMenus.get(i); if (newMenus == null || !newMenus.contains(f)) { f.onDestroyOptionsMenu(); } } } mCreatedMenus = newMenus; return show; } public boolean dispatchPrepareOptionsMenu(Menu menu) { if (mCurState < Fragment.CREATED) { return false; } boolean show = false; for (int i = 0; i < mAdded.size(); i++) { Fragment f = mAdded.get(i); if (f != null) { if (f.performPrepareOptionsMenu(menu)) { show = true; } } } return show; } public boolean dispatchOptionsItemSelected(MenuItem item) { if (mCurState < Fragment.CREATED) { return false; } for (int i = 0; i < mAdded.size(); i++) { Fragment f = mAdded.get(i); if (f != null) { if (f.performOptionsItemSelected(item)) { return true; } } } return false; } public boolean dispatchContextItemSelected(MenuItem item) { if (mCurState < Fragment.CREATED) { return false; } for (int i = 0; i < mAdded.size(); i++) { Fragment f = mAdded.get(i); if (f != null) { if (f.performContextItemSelected(item)) { return true; } } } return false; } public void dispatchOptionsMenuClosed(Menu menu) { if (mCurState < Fragment.CREATED) { return; } for (int i = 0; i < mAdded.size(); i++) { Fragment f = mAdded.get(i); if (f != null) { f.performOptionsMenuClosed(menu); } } } @SuppressWarnings("ReferenceEquality") public void setPrimaryNavigationFragment(Fragment f) { if (f != null && (mActive.get(f.mIndex) != f || (f.mHost != null && f.getFragmentManager() != this))) { throw new IllegalArgumentException("Fragment " + f + " is not an active fragment of FragmentManager " + this); } mPrimaryNav = f; } @Override @Nullable public Fragment getPrimaryNavigationFragment() { return mPrimaryNav; } @Override public void registerFragmentLifecycleCallbacks(FragmentLifecycleCallbacks cb, boolean recursive) { mLifecycleCallbacks.add(new FragmentLifecycleCallbacksHolder(cb, recursive)); } @Override public void unregisterFragmentLifecycleCallbacks(FragmentLifecycleCallbacks cb) { synchronized (mLifecycleCallbacks) { for (int i = 0, N = mLifecycleCallbacks.size(); i < N; i++) { if (mLifecycleCallbacks.get(i).mCallback == cb) { mLifecycleCallbacks.remove(i); break; } } } } void dispatchOnFragmentPreAttached(@NonNull Fragment f, @NonNull Context context, boolean onlyRecursive) { if (mParent != null) { FragmentManager parentManager = mParent.getFragmentManager(); if (parentManager instanceof FragmentManagerImpl) { ((FragmentManagerImpl) parentManager) .dispatchOnFragmentPreAttached(f, context, true); } } for (FragmentLifecycleCallbacksHolder holder : mLifecycleCallbacks) { if (!onlyRecursive || holder.mRecursive) { holder.mCallback.onFragmentPreAttached(this, f, context); } } } void dispatchOnFragmentAttached(@NonNull Fragment f, @NonNull Context context, boolean onlyRecursive) { if (mParent != null) { FragmentManager parentManager = mParent.getFragmentManager(); if (parentManager instanceof FragmentManagerImpl) { ((FragmentManagerImpl) parentManager) .dispatchOnFragmentAttached(f, context, true); } } for (FragmentLifecycleCallbacksHolder holder : mLifecycleCallbacks) { if (!onlyRecursive || holder.mRecursive) { holder.mCallback.onFragmentAttached(this, f, context); } } } void dispatchOnFragmentPreCreated(@NonNull Fragment f, @Nullable Bundle savedInstanceState, boolean onlyRecursive) { if (mParent != null) { FragmentManager parentManager = mParent.getFragmentManager(); if (parentManager instanceof FragmentManagerImpl) { ((FragmentManagerImpl) parentManager) .dispatchOnFragmentPreCreated(f, savedInstanceState, true); } } for (FragmentLifecycleCallbacksHolder holder : mLifecycleCallbacks) { if (!onlyRecursive || holder.mRecursive) { holder.mCallback.onFragmentPreCreated(this, f, savedInstanceState); } } } void dispatchOnFragmentCreated(@NonNull Fragment f, @Nullable Bundle savedInstanceState, boolean onlyRecursive) { if (mParent != null) { FragmentManager parentManager = mParent.getFragmentManager(); if (parentManager instanceof FragmentManagerImpl) { ((FragmentManagerImpl) parentManager) .dispatchOnFragmentCreated(f, savedInstanceState, true); } } for (FragmentLifecycleCallbacksHolder holder : mLifecycleCallbacks) { if (!onlyRecursive || holder.mRecursive) { holder.mCallback.onFragmentCreated(this, f, savedInstanceState); } } } void dispatchOnFragmentActivityCreated(@NonNull Fragment f, @Nullable Bundle savedInstanceState, boolean onlyRecursive) { if (mParent != null) { FragmentManager parentManager = mParent.getFragmentManager(); if (parentManager instanceof FragmentManagerImpl) { ((FragmentManagerImpl) parentManager) .dispatchOnFragmentActivityCreated(f, savedInstanceState, true); } } for (FragmentLifecycleCallbacksHolder holder : mLifecycleCallbacks) { if (!onlyRecursive || holder.mRecursive) { holder.mCallback.onFragmentActivityCreated(this, f, savedInstanceState); } } } void dispatchOnFragmentViewCreated(@NonNull Fragment f, @NonNull View v, @Nullable Bundle savedInstanceState, boolean onlyRecursive) { if (mParent != null) { FragmentManager parentManager = mParent.getFragmentManager(); if (parentManager instanceof FragmentManagerImpl) { ((FragmentManagerImpl) parentManager) .dispatchOnFragmentViewCreated(f, v, savedInstanceState, true); } } for (FragmentLifecycleCallbacksHolder holder : mLifecycleCallbacks) { if (!onlyRecursive || holder.mRecursive) { holder.mCallback.onFragmentViewCreated(this, f, v, savedInstanceState); } } } void dispatchOnFragmentStarted(@NonNull Fragment f, boolean onlyRecursive) { if (mParent != null) { FragmentManager parentManager = mParent.getFragmentManager(); if (parentManager instanceof FragmentManagerImpl) { ((FragmentManagerImpl) parentManager) .dispatchOnFragmentStarted(f, true); } } for (FragmentLifecycleCallbacksHolder holder : mLifecycleCallbacks) { if (!onlyRecursive || holder.mRecursive) { holder.mCallback.onFragmentStarted(this, f); } } } void dispatchOnFragmentResumed(@NonNull Fragment f, boolean onlyRecursive) { if (mParent != null) { FragmentManager parentManager = mParent.getFragmentManager(); if (parentManager instanceof FragmentManagerImpl) { ((FragmentManagerImpl) parentManager) .dispatchOnFragmentResumed(f, true); } } for (FragmentLifecycleCallbacksHolder holder : mLifecycleCallbacks) { if (!onlyRecursive || holder.mRecursive) { holder.mCallback.onFragmentResumed(this, f); } } } void dispatchOnFragmentPaused(@NonNull Fragment f, boolean onlyRecursive) { if (mParent != null) { FragmentManager parentManager = mParent.getFragmentManager(); if (parentManager instanceof FragmentManagerImpl) { ((FragmentManagerImpl) parentManager) .dispatchOnFragmentPaused(f, true); } } for (FragmentLifecycleCallbacksHolder holder : mLifecycleCallbacks) { if (!onlyRecursive || holder.mRecursive) { holder.mCallback.onFragmentPaused(this, f); } } } void dispatchOnFragmentStopped(@NonNull Fragment f, boolean onlyRecursive) { if (mParent != null) { FragmentManager parentManager = mParent.getFragmentManager(); if (parentManager instanceof FragmentManagerImpl) { ((FragmentManagerImpl) parentManager) .dispatchOnFragmentStopped(f, true); } } for (FragmentLifecycleCallbacksHolder holder : mLifecycleCallbacks) { if (!onlyRecursive || holder.mRecursive) { holder.mCallback.onFragmentStopped(this, f); } } } void dispatchOnFragmentSaveInstanceState(@NonNull Fragment f, @NonNull Bundle outState, boolean onlyRecursive) { if (mParent != null) { FragmentManager parentManager = mParent.getFragmentManager(); if (parentManager instanceof FragmentManagerImpl) { ((FragmentManagerImpl) parentManager) .dispatchOnFragmentSaveInstanceState(f, outState, true); } } for (FragmentLifecycleCallbacksHolder holder : mLifecycleCallbacks) { if (!onlyRecursive || holder.mRecursive) { holder.mCallback.onFragmentSaveInstanceState(this, f, outState); } } } void dispatchOnFragmentViewDestroyed(@NonNull Fragment f, boolean onlyRecursive) { if (mParent != null) { FragmentManager parentManager = mParent.getFragmentManager(); if (parentManager instanceof FragmentManagerImpl) { ((FragmentManagerImpl) parentManager) .dispatchOnFragmentViewDestroyed(f, true); } } for (FragmentLifecycleCallbacksHolder holder : mLifecycleCallbacks) { if (!onlyRecursive || holder.mRecursive) { holder.mCallback.onFragmentViewDestroyed(this, f); } } } void dispatchOnFragmentDestroyed(@NonNull Fragment f, boolean onlyRecursive) { if (mParent != null) { FragmentManager parentManager = mParent.getFragmentManager(); if (parentManager instanceof FragmentManagerImpl) { ((FragmentManagerImpl) parentManager) .dispatchOnFragmentDestroyed(f, true); } } for (FragmentLifecycleCallbacksHolder holder : mLifecycleCallbacks) { if (!onlyRecursive || holder.mRecursive) { holder.mCallback.onFragmentDestroyed(this, f); } } } void dispatchOnFragmentDetached(@NonNull Fragment f, boolean onlyRecursive) { if (mParent != null) { FragmentManager parentManager = mParent.getFragmentManager(); if (parentManager instanceof FragmentManagerImpl) { ((FragmentManagerImpl) parentManager) .dispatchOnFragmentDetached(f, true); } } for (FragmentLifecycleCallbacksHolder holder : mLifecycleCallbacks) { if (!onlyRecursive || holder.mRecursive) { holder.mCallback.onFragmentDetached(this, f); } } } public static int reverseTransit(int transit) { int rev = 0; switch (transit) { case FragmentTransaction.TRANSIT_FRAGMENT_OPEN: rev = FragmentTransaction.TRANSIT_FRAGMENT_CLOSE; break; case FragmentTransaction.TRANSIT_FRAGMENT_CLOSE: rev = FragmentTransaction.TRANSIT_FRAGMENT_OPEN; break; case FragmentTransaction.TRANSIT_FRAGMENT_FADE: rev = FragmentTransaction.TRANSIT_FRAGMENT_FADE; break; } return rev; } public static final int ANIM_STYLE_OPEN_ENTER = 1; public static final int ANIM_STYLE_OPEN_EXIT = 2; public static final int ANIM_STYLE_CLOSE_ENTER = 3; public static final int ANIM_STYLE_CLOSE_EXIT = 4; public static final int ANIM_STYLE_FADE_ENTER = 5; public static final int ANIM_STYLE_FADE_EXIT = 6; public static int transitToStyleIndex(int transit, boolean enter) { int animAttr = -1; switch (transit) { case FragmentTransaction.TRANSIT_FRAGMENT_OPEN: animAttr = enter ? ANIM_STYLE_OPEN_ENTER : ANIM_STYLE_OPEN_EXIT; break; case FragmentTransaction.TRANSIT_FRAGMENT_CLOSE: animAttr = enter ? ANIM_STYLE_CLOSE_ENTER : ANIM_STYLE_CLOSE_EXIT; break; case FragmentTransaction.TRANSIT_FRAGMENT_FADE: animAttr = enter ? ANIM_STYLE_FADE_ENTER : ANIM_STYLE_FADE_EXIT; break; } return animAttr; } @Override public View onCreateView(View parent, String name, Context context, AttributeSet attrs) { if (!"fragment".equals(name)) { return null; } String fname = attrs.getAttributeValue(null, "class"); TypedArray a = context.obtainStyledAttributes(attrs, FragmentTag.Fragment); if (fname == null) { fname = a.getString(FragmentTag.Fragment_name); } int id = a.getResourceId(FragmentTag.Fragment_id, View.NO_ID); String tag = a.getString(FragmentTag.Fragment_tag); a.recycle(); if (!Fragment.isSupportFragmentClass(mHost.getContext(), fname)) { // Invalid support lib fragment; let the device's framework handle it. // This will allow android.app.Fragments to do the right thing. return null; } int containerId = parent != null ? parent.getId() : 0; if (containerId == View.NO_ID && id == View.NO_ID && tag == null) { throw new IllegalArgumentException(attrs.getPositionDescription() + ": Must specify unique android:id, android:tag, or have a parent with an id for " + fname); } // If we restored from a previous state, we may already have // instantiated this fragment from the state and should use // that instance instead of making a new one. Fragment fragment = id != View.NO_ID ? findFragmentById(id) : null; if (fragment == null && tag != null) { fragment = findFragmentByTag(tag); } if (fragment == null && containerId != View.NO_ID) { fragment = findFragmentById(containerId); } if (FragmentManagerImpl.DEBUG) Log.v(TAG, "onCreateView: id=0x" + Integer.toHexString(id) + " fname=" + fname + " existing=" + fragment); if (fragment == null) { fragment = mContainer.instantiate(context, fname, null); fragment.mFromLayout = true; fragment.mFragmentId = id != 0 ? id : containerId; fragment.mContainerId = containerId; fragment.mTag = tag; fragment.mInLayout = true; fragment.mFragmentManager = this; fragment.mHost = mHost; fragment.onInflate(mHost.getContext(), attrs, fragment.mSavedFragmentState); addFragment(fragment, true); } else if (fragment.mInLayout) { // A fragment already exists and it is not one we restored from // previous state. throw new IllegalArgumentException(attrs.getPositionDescription() + ": Duplicate id 0x" + Integer.toHexString(id) + ", tag " + tag + ", or parent id 0x" + Integer.toHexString(containerId) + " with another fragment for " + fname); } else { // This fragment was retained from a previous instance; get it // going now. fragment.mInLayout = true; fragment.mHost = mHost; // If this fragment is newly instantiated (either right now, or // from last saved state), then give it the attributes to // initialize itself. if (!fragment.mRetaining) { fragment.onInflate(mHost.getContext(), attrs, fragment.mSavedFragmentState); } } // If we haven't finished entering the CREATED state ourselves yet, // push the inflated child fragment along. This will ensureInflatedFragmentView // at the right phase of the lifecycle so that we will have mView populated // for compliant fragments below. if (mCurState < Fragment.CREATED && fragment.mFromLayout) { moveToState(fragment, Fragment.CREATED, 0, 0, false); } else { moveToState(fragment); } if (fragment.mView == null) { throw new IllegalStateException("Fragment " + fname + " did not create a view."); } if (id != 0) { fragment.mView.setId(id); } if (fragment.mView.getTag() == null) { fragment.mView.setTag(tag); } return fragment.mView; } @Override public View onCreateView(String name, Context context, AttributeSet attrs) { return onCreateView(null, name, context, attrs); } LayoutInflater.Factory2 getLayoutInflaterFactory() { return this; } static class FragmentTag { public static final int[] Fragment = { 0x01010003, 0x010100d0, 0x010100d1 }; public static final int Fragment_id = 1; public static final int Fragment_name = 0; public static final int Fragment_tag = 2; private FragmentTag() { } } /** * An add or pop transaction to be scheduled for the UI thread. */ interface OpGenerator { /** * Generate transactions to add to {@code records} and whether or not the transaction is * an add or pop to {@code isRecordPop}. * * records and isRecordPop must be added equally so that each transaction in records * matches the boolean for whether or not it is a pop in isRecordPop. * * @param records A list to add transactions to. * @param isRecordPop A list to add whether or not the transactions added to records is * a pop transaction. * @return true if something was added or false otherwise. */ boolean generateOps(ArrayList<BackStackRecord> records, ArrayList<Boolean> isRecordPop); } /** * A pop operation OpGenerator. This will be run on the UI thread and will generate the * transactions that will be popped if anything can be popped. */ private class PopBackStackState implements OpGenerator { final String mName; final int mId; final int mFlags; PopBackStackState(String name, int id, int flags) { mName = name; mId = id; mFlags = flags; } @Override public boolean generateOps(ArrayList<BackStackRecord> records, ArrayList<Boolean> isRecordPop) { if (mPrimaryNav != null // We have a primary nav fragment && mId < 0 // No valid id (since they're local) && mName == null) { // no name to pop to (since they're local) final FragmentManager childManager = mPrimaryNav.peekChildFragmentManager(); if (childManager != null && childManager.popBackStackImmediate()) { // We didn't add any operations for this FragmentManager even though // a child did do work. return false; } } return popBackStackState(records, isRecordPop, mName, mId, mFlags); } } /** * A listener for a postponed transaction. This waits until * {@link Fragment#startPostponedEnterTransition()} is called or a transaction is started * that interacts with this one, based on interactions with the fragment container. */ static class StartEnterTransitionListener implements Fragment.OnStartEnterTransitionListener { final boolean mIsBack; final BackStackRecord mRecord; private int mNumPostponed; StartEnterTransitionListener(BackStackRecord record, boolean isBack) { mIsBack = isBack; mRecord = record; } /** * Called from {@link Fragment#startPostponedEnterTransition()}, this decreases the * number of Fragments that are postponed. This may cause the transaction to schedule * to finish running and run transitions and animations. */ @Override public void onStartEnterTransition() { mNumPostponed--; if (mNumPostponed != 0) { return; } mRecord.mManager.scheduleCommit(); } /** * Called from {@link Fragment# * setOnStartEnterTransitionListener(Fragment.OnStartEnterTransitionListener)}, this * increases the number of fragments that are postponed as part of this transaction. */ @Override public void startListening() { mNumPostponed++; } /** * @return true if there are no more postponed fragments as part of the transaction. */ public boolean isReady() { return mNumPostponed == 0; } /** * Completes the transaction and start the animations and transitions. This may skip * the transitions if this is called before all fragments have called * {@link Fragment#startPostponedEnterTransition()}. */ public void completeTransaction() { final boolean canceled; canceled = mNumPostponed > 0; FragmentManagerImpl manager = mRecord.mManager; final int numAdded = manager.mAdded.size(); for (int i = 0; i < numAdded; i++) { final Fragment fragment = manager.mAdded.get(i); fragment.setOnStartEnterTransitionListener(null); if (canceled && fragment.isPostponed()) { fragment.startPostponedEnterTransition(); } } mRecord.mManager.completeExecute(mRecord, mIsBack, !canceled, true); } /** * Cancels this transaction instead of completing it. That means that the state isn't * changed, so the pop results in no change to the state. */ public void cancelTransaction() { mRecord.mManager.completeExecute(mRecord, mIsBack, false, false); } } /** * Contains either an animator or animation. One of these should be null. */ private static class AnimationOrAnimator { public final Animation animation; public final Animator animator; AnimationOrAnimator(Animation animation) { this.animation = animation; this.animator = null; if (animation == null) { throw new IllegalStateException("Animation cannot be null"); } } AnimationOrAnimator(Animator animator) { this.animation = null; this.animator = animator; if (animator == null) { throw new IllegalStateException("Animator cannot be null"); } } } /** * Wrap an AnimationListener that can be null. This allows us to chain animation listeners. */ private static class AnimationListenerWrapper implements AnimationListener { private final AnimationListener mWrapped; AnimationListenerWrapper(AnimationListener wrapped) { mWrapped = wrapped; } @CallSuper @Override public void onAnimationStart(Animation animation) { if (mWrapped != null) { mWrapped.onAnimationStart(animation); } } @CallSuper @Override public void onAnimationEnd(Animation animation) { if (mWrapped != null) { mWrapped.onAnimationEnd(animation); } } @CallSuper @Override public void onAnimationRepeat(Animation animation) { if (mWrapped != null) { mWrapped.onAnimationRepeat(animation); } } } /** * Reset the layer type to LAYER_TYPE_NONE at the end of an animation. */ private static class AnimateOnHWLayerIfNeededListener extends AnimationListenerWrapper { View mView; AnimateOnHWLayerIfNeededListener(final View v, AnimationListener listener) { super(listener); mView = v; } @Override @CallSuper public void onAnimationEnd(Animation animation) { // If we're attached to a window, assume we're in the normal performTraversals // drawing path for Animations running. It's not safe to change the layer type // during drawing, so post it to the View to run later. If we're not attached // or we're running on N and above, post it to the view. If we're not on N and // not attached, do it right now since existing platform versions don't run the // hwui renderer for detached views off the UI thread making changing layer type // safe, but posting may not be. // Prior to N posting to a detached view from a non-Looper thread could cause // leaks, since the thread-local run queue on a non-Looper thread would never // be flushed. if (ViewCompat.isAttachedToWindow(mView) || Build.VERSION.SDK_INT >= 24) { mView.post(new Runnable() { @Override public void run() { mView.setLayerType(View.LAYER_TYPE_NONE, null); } }); } else { mView.setLayerType(View.LAYER_TYPE_NONE, null); } super.onAnimationEnd(animation); } } /** * Set the layer type to LAYER_TYPE_HARDWARE while an animator is running. */ private static class AnimatorOnHWLayerIfNeededListener extends AnimatorListenerAdapter { View mView; AnimatorOnHWLayerIfNeededListener(final View v) { mView = v; } @Override public void onAnimationStart(Animator animation) { mView.setLayerType(View.LAYER_TYPE_HARDWARE, null); } @Override public void onAnimationEnd(Animator animation) { mView.setLayerType(View.LAYER_TYPE_NONE, null); animation.removeListener(this); } } /** * We must call endViewTransition() before the animation ends or else the parent doesn't * get nulled out. We use both startViewTransition() and startAnimation() to solve a problem * with Views remaining in the hierarchy as disappearing children after the view has been * removed in some edge cases. */ private static class EndViewTransitionAnimator extends AnimationSet implements Runnable { private final ViewGroup mParent; private final View mChild; private boolean mEnded; private boolean mTransitionEnded; private boolean mAnimating = true; EndViewTransitionAnimator(@NonNull Animation animation, @NonNull ViewGroup parent, @NonNull View child) { super(false); mParent = parent; mChild = child; addAnimation(animation); // We must call endViewTransition() even if the animation was never run or it // is interrupted in a way that can't be detected easily (app put in background) mParent.post(this); } @Override public boolean getTransformation(long currentTime, Transformation t) { mAnimating = true; if (mEnded) { return !mTransitionEnded; } boolean more = super.getTransformation(currentTime, t); if (!more) { mEnded = true; OneShotPreDrawListener.add(mParent, this); } return true; } @Override public boolean getTransformation(long currentTime, Transformation outTransformation, float scale) { mAnimating = true; if (mEnded) { return !mTransitionEnded; } boolean more = super.getTransformation(currentTime, outTransformation, scale); if (!more) { mEnded = true; OneShotPreDrawListener.add(mParent, this); } return true; } @Override public void run() { if (!mEnded && mAnimating) { mAnimating = false; // Called while animating, so we'll check again on next cycle mParent.post(this); } else { mParent.endViewTransition(mChild); mTransitionEnded = true; } } } }
fragment/src/main/java/androidx/fragment/app/FragmentManager.java
/* * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.fragment.app; import static androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP; import android.animation.Animator; import android.animation.AnimatorInflater; import android.animation.AnimatorListenerAdapter; import android.animation.AnimatorSet; import android.animation.PropertyValuesHolder; import android.animation.ValueAnimator; import android.content.Context; import android.content.res.Configuration; import android.content.res.Resources.NotFoundException; import android.content.res.TypedArray; import android.os.Build; import android.os.Bundle; import android.os.Looper; import android.os.Parcel; import android.os.Parcelable; import android.util.AttributeSet; import android.util.Log; import android.util.SparseArray; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.animation.AccelerateInterpolator; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.Animation.AnimationListener; import android.view.animation.AnimationSet; import android.view.animation.AnimationUtils; import android.view.animation.DecelerateInterpolator; import android.view.animation.Interpolator; import android.view.animation.ScaleAnimation; import android.view.animation.Transformation; import androidx.annotation.CallSuper; import androidx.annotation.IdRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RestrictTo; import androidx.annotation.StringRes; import androidx.collection.ArraySet; import androidx.core.util.DebugUtils; import androidx.core.util.LogWriter; import androidx.core.view.ViewCompat; import androidx.lifecycle.ViewModelStore; import java.io.FileDescriptor; import java.io.PrintWriter; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; /** * Static library support version of the framework's {@link android.app.FragmentManager}. * Used to write apps that run on platforms prior to Android 3.0. When running * on Android 3.0 or above, this implementation is still used; it does not try * to switch to the framework's implementation. See the framework {@link FragmentManager} * documentation for a class overview. * * <p>Your activity must derive from {@link FragmentActivity} to use this. From such an activity, * you can acquire the {@link FragmentManager} by calling * {@link FragmentActivity#getSupportFragmentManager}. */ public abstract class FragmentManager { /** * Representation of an entry on the fragment back stack, as created * with {@link FragmentTransaction#addToBackStack(String) * FragmentTransaction.addToBackStack()}. Entries can later be * retrieved with {@link FragmentManager#getBackStackEntryAt(int) * FragmentManager.getBackStackEntryAt()}. * * <p>Note that you should never hold on to a BackStackEntry object; * the identifier as returned by {@link #getId} is the only thing that * will be persisted across activity instances. */ public interface BackStackEntry { /** * Return the unique identifier for the entry. This is the only * representation of the entry that will persist across activity * instances. */ public int getId(); /** * Get the name that was supplied to * {@link FragmentTransaction#addToBackStack(String) * FragmentTransaction.addToBackStack(String)} when creating this entry. */ @Nullable public String getName(); /** * Return the full bread crumb title resource identifier for the entry, * or 0 if it does not have one. */ @StringRes public int getBreadCrumbTitleRes(); /** * Return the short bread crumb title resource identifier for the entry, * or 0 if it does not have one. */ @StringRes public int getBreadCrumbShortTitleRes(); /** * Return the full bread crumb title for the entry, or null if it * does not have one. */ @Nullable public CharSequence getBreadCrumbTitle(); /** * Return the short bread crumb title for the entry, or null if it * does not have one. */ @Nullable public CharSequence getBreadCrumbShortTitle(); } /** * Interface to watch for changes to the back stack. */ public interface OnBackStackChangedListener { /** * Called whenever the contents of the back stack change. */ public void onBackStackChanged(); } /** * Start a series of edit operations on the Fragments associated with * this FragmentManager. * * <p>Note: A fragment transaction can only be created/committed prior * to an activity saving its state. If you try to commit a transaction * after {@link FragmentActivity#onSaveInstanceState FragmentActivity.onSaveInstanceState()} * (and prior to a following {@link FragmentActivity#onStart FragmentActivity.onStart} * or {@link FragmentActivity#onResume FragmentActivity.onResume()}, you will get an error. * This is because the framework takes care of saving your current fragments * in the state, and if changes are made after the state is saved then they * will be lost.</p> */ @NonNull public abstract FragmentTransaction beginTransaction(); /** * @hide -- remove once prebuilts are in. * @deprecated */ @RestrictTo(LIBRARY_GROUP) @Deprecated public FragmentTransaction openTransaction() { return beginTransaction(); } /** * After a {@link FragmentTransaction} is committed with * {@link FragmentTransaction#commit FragmentTransaction.commit()}, it * is scheduled to be executed asynchronously on the process's main thread. * If you want to immediately executing any such pending operations, you * can call this function (only from the main thread) to do so. Note that * all callbacks and other related behavior will be done from within this * call, so be careful about where this is called from. * * <p>If you are committing a single transaction that does not modify the * fragment back stack, strongly consider using * {@link FragmentTransaction#commitNow()} instead. This can help avoid * unwanted side effects when other code in your app has pending committed * transactions that expect different timing.</p> * <p> * This also forces the start of any postponed Transactions where * {@link Fragment#postponeEnterTransition()} has been called. * * @return Returns true if there were any pending transactions to be * executed. */ public abstract boolean executePendingTransactions(); /** * Finds a fragment that was identified by the given id either when inflated * from XML or as the container ID when added in a transaction. This first * searches through fragments that are currently added to the manager's * activity; if no such fragment is found, then all fragments currently * on the back stack associated with this ID are searched. * @return The fragment if found or null otherwise. */ @Nullable public abstract Fragment findFragmentById(@IdRes int id); /** * Finds a fragment that was identified by the given tag either when inflated * from XML or as supplied when added in a transaction. This first * searches through fragments that are currently added to the manager's * activity; if no such fragment is found, then all fragments currently * on the back stack are searched. * @return The fragment if found or null otherwise. */ @Nullable public abstract Fragment findFragmentByTag(@Nullable String tag); /** * Flag for {@link #popBackStack(String, int)} * and {@link #popBackStack(int, int)}: If set, and the name or ID of * a back stack entry has been supplied, then all matching entries will * be consumed until one that doesn't match is found or the bottom of * the stack is reached. Otherwise, all entries up to but not including that entry * will be removed. */ public static final int POP_BACK_STACK_INCLUSIVE = 1<<0; /** * Pop the top state off the back stack. Returns true if there was one * to pop, else false. This function is asynchronous -- it enqueues the * request to pop, but the action will not be performed until the application * returns to its event loop. */ public abstract void popBackStack(); /** * Like {@link #popBackStack()}, but performs the operation immediately * inside of the call. This is like calling {@link #executePendingTransactions()} * afterwards without forcing the start of postponed Transactions. * @return Returns true if there was something popped, else false. */ public abstract boolean popBackStackImmediate(); /** * Pop the last fragment transition from the manager's fragment * back stack. If there is nothing to pop, false is returned. * This function is asynchronous -- it enqueues the * request to pop, but the action will not be performed until the application * returns to its event loop. * * @param name If non-null, this is the name of a previous back state * to look for; if found, all states up to that state will be popped. The * {@link #POP_BACK_STACK_INCLUSIVE} flag can be used to control whether * the named state itself is popped. If null, only the top state is popped. * @param flags Either 0 or {@link #POP_BACK_STACK_INCLUSIVE}. */ public abstract void popBackStack(@Nullable String name, int flags); /** * Like {@link #popBackStack(String, int)}, but performs the operation immediately * inside of the call. This is like calling {@link #executePendingTransactions()} * afterwards without forcing the start of postponed Transactions. * @return Returns true if there was something popped, else false. */ public abstract boolean popBackStackImmediate(@Nullable String name, int flags); /** * Pop all back stack states up to the one with the given identifier. * This function is asynchronous -- it enqueues the * request to pop, but the action will not be performed until the application * returns to its event loop. * * @param id Identifier of the stated to be popped. If no identifier exists, * false is returned. * The identifier is the number returned by * {@link FragmentTransaction#commit() FragmentTransaction.commit()}. The * {@link #POP_BACK_STACK_INCLUSIVE} flag can be used to control whether * the named state itself is popped. * @param flags Either 0 or {@link #POP_BACK_STACK_INCLUSIVE}. */ public abstract void popBackStack(int id, int flags); /** * Like {@link #popBackStack(int, int)}, but performs the operation immediately * inside of the call. This is like calling {@link #executePendingTransactions()} * afterwards without forcing the start of postponed Transactions. * @return Returns true if there was something popped, else false. */ public abstract boolean popBackStackImmediate(int id, int flags); /** * Return the number of entries currently in the back stack. */ public abstract int getBackStackEntryCount(); /** * Return the BackStackEntry at index <var>index</var> in the back stack; * entries start index 0 being the bottom of the stack. */ @NonNull public abstract BackStackEntry getBackStackEntryAt(int index); /** * Add a new listener for changes to the fragment back stack. */ public abstract void addOnBackStackChangedListener( @NonNull OnBackStackChangedListener listener); /** * Remove a listener that was previously added with * {@link #addOnBackStackChangedListener(OnBackStackChangedListener)}. */ public abstract void removeOnBackStackChangedListener( @NonNull OnBackStackChangedListener listener); /** * Put a reference to a fragment in a Bundle. This Bundle can be * persisted as saved state, and when later restoring * {@link #getFragment(Bundle, String)} will return the current * instance of the same fragment. * * @param bundle The bundle in which to put the fragment reference. * @param key The name of the entry in the bundle. * @param fragment The Fragment whose reference is to be stored. */ public abstract void putFragment(@NonNull Bundle bundle, @NonNull String key, @NonNull Fragment fragment); /** * Retrieve the current Fragment instance for a reference previously * placed with {@link #putFragment(Bundle, String, Fragment)}. * * @param bundle The bundle from which to retrieve the fragment reference. * @param key The name of the entry in the bundle. * @return Returns the current Fragment instance that is associated with * the given reference. */ @Nullable public abstract Fragment getFragment(@NonNull Bundle bundle, @NonNull String key); /** * Get a list of all fragments that are currently added to the FragmentManager. * This may include those that are hidden as well as those that are shown. * This will not include any fragments only in the back stack, or fragments that * are detached or removed. * <p> * The order of the fragments in the list is the order in which they were * added or attached. * * @return A list of all fragments that are added to the FragmentManager. */ @NonNull public abstract List<Fragment> getFragments(); /** * Save the current instance state of the given Fragment. This can be * used later when creating a new instance of the Fragment and adding * it to the fragment manager, to have it create itself to match the * current state returned here. Note that there are limits on how * this can be used: * * <ul> * <li>The Fragment must currently be attached to the FragmentManager. * <li>A new Fragment created using this saved state must be the same class * type as the Fragment it was created from. * <li>The saved state can not contain dependencies on other fragments -- * that is it can't use {@link #putFragment(Bundle, String, Fragment)} to * store a fragment reference because that reference may not be valid when * this saved state is later used. Likewise the Fragment's target and * result code are not included in this state. * </ul> * * @param f The Fragment whose state is to be saved. * @return The generated state. This will be null if there was no * interesting state created by the fragment. */ @Nullable public abstract Fragment.SavedState saveFragmentInstanceState(Fragment f); /** * Returns true if the final {@link android.app.Activity#onDestroy() Activity.onDestroy()} * call has been made on the FragmentManager's Activity, so this instance is now dead. */ public abstract boolean isDestroyed(); /** * Registers a {@link FragmentLifecycleCallbacks} to listen to fragment lifecycle events * happening in this FragmentManager. All registered callbacks will be automatically * unregistered when this FragmentManager is destroyed. * * @param cb Callbacks to register * @param recursive true to automatically register this callback for all child FragmentManagers */ public abstract void registerFragmentLifecycleCallbacks(@NonNull FragmentLifecycleCallbacks cb, boolean recursive); /** * Unregisters a previously registered {@link FragmentLifecycleCallbacks}. If the callback * was not previously registered this call has no effect. All registered callbacks will be * automatically unregistered when this FragmentManager is destroyed. * * @param cb Callbacks to unregister */ public abstract void unregisterFragmentLifecycleCallbacks( @NonNull FragmentLifecycleCallbacks cb); /** * Return the currently active primary navigation fragment for this FragmentManager. * The primary navigation fragment is set by fragment transactions using * {@link FragmentTransaction#setPrimaryNavigationFragment(Fragment)}. * * <p>The primary navigation fragment's * {@link Fragment#getChildFragmentManager() child FragmentManager} will be called first * to process delegated navigation actions such as {@link #popBackStack()} if no ID * or transaction name is provided to pop to.</p> * * @return the fragment designated as the primary navigation fragment */ @Nullable public abstract Fragment getPrimaryNavigationFragment(); /** * Print the FragmentManager's state into the given stream. * * @param prefix Text to print at the front of each line. * @param fd The raw file descriptor that the dump is being sent to. * @param writer A PrintWriter to which the dump is to be set. * @param args Additional arguments to the dump request. */ public abstract void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args); /** * Control whether the framework's internal fragment manager debugging * logs are turned on. If enabled, you will see output in logcat as * the framework performs fragment operations. */ public static void enableDebugLogging(boolean enabled) { FragmentManagerImpl.DEBUG = enabled; } /** * Returns {@code true} if the FragmentManager's state has already been saved * by its host. Any operations that would change saved state should not be performed * if this method returns true. For example, any popBackStack() method, such as * {@link #popBackStackImmediate()} or any FragmentTransaction using * {@link FragmentTransaction#commit()} instead of * {@link FragmentTransaction#commitAllowingStateLoss()} will change * the state and will result in an error. * * @return true if this FragmentManager's state has already been saved by its host */ public abstract boolean isStateSaved(); /** * Callback interface for listening to fragment state changes that happen * within a given FragmentManager. */ public abstract static class FragmentLifecycleCallbacks { /** * Called right before the fragment's {@link Fragment#onAttach(Context)} method is called. * This is a good time to inject any required dependencies or perform other configuration * for the fragment before any of the fragment's lifecycle methods are invoked. * * @param fm Host FragmentManager * @param f Fragment changing state * @param context Context that the Fragment is being attached to */ public void onFragmentPreAttached(@NonNull FragmentManager fm, @NonNull Fragment f, @NonNull Context context) {} /** * Called after the fragment has been attached to its host. Its host will have had * <code>onAttachFragment</code> called before this call happens. * * @param fm Host FragmentManager * @param f Fragment changing state * @param context Context that the Fragment was attached to */ public void onFragmentAttached(@NonNull FragmentManager fm, @NonNull Fragment f, @NonNull Context context) {} /** * Called right before the fragment's {@link Fragment#onCreate(Bundle)} method is called. * This is a good time to inject any required dependencies or perform other configuration * for the fragment. * * @param fm Host FragmentManager * @param f Fragment changing state * @param savedInstanceState Saved instance bundle from a previous instance */ public void onFragmentPreCreated(@NonNull FragmentManager fm, @NonNull Fragment f, @Nullable Bundle savedInstanceState) {} /** * Called after the fragment has returned from the FragmentManager's call to * {@link Fragment#onCreate(Bundle)}. This will only happen once for any given * fragment instance, though the fragment may be attached and detached multiple times. * * @param fm Host FragmentManager * @param f Fragment changing state * @param savedInstanceState Saved instance bundle from a previous instance */ public void onFragmentCreated(@NonNull FragmentManager fm, @NonNull Fragment f, @Nullable Bundle savedInstanceState) {} /** * Called after the fragment has returned from the FragmentManager's call to * {@link Fragment#onActivityCreated(Bundle)}. This will only happen once for any given * fragment instance, though the fragment may be attached and detached multiple times. * * @param fm Host FragmentManager * @param f Fragment changing state * @param savedInstanceState Saved instance bundle from a previous instance */ public void onFragmentActivityCreated(@NonNull FragmentManager fm, @NonNull Fragment f, @Nullable Bundle savedInstanceState) {} /** * Called after the fragment has returned a non-null view from the FragmentManager's * request to {@link Fragment#onCreateView(LayoutInflater, ViewGroup, Bundle)}. * * @param fm Host FragmentManager * @param f Fragment that created and owns the view * @param v View returned by the fragment * @param savedInstanceState Saved instance bundle from a previous instance */ public void onFragmentViewCreated(@NonNull FragmentManager fm, @NonNull Fragment f, @NonNull View v, @Nullable Bundle savedInstanceState) {} /** * Called after the fragment has returned from the FragmentManager's call to * {@link Fragment#onStart()}. * * @param fm Host FragmentManager * @param f Fragment changing state */ public void onFragmentStarted(@NonNull FragmentManager fm, @NonNull Fragment f) {} /** * Called after the fragment has returned from the FragmentManager's call to * {@link Fragment#onResume()}. * * @param fm Host FragmentManager * @param f Fragment changing state */ public void onFragmentResumed(@NonNull FragmentManager fm, @NonNull Fragment f) {} /** * Called after the fragment has returned from the FragmentManager's call to * {@link Fragment#onPause()}. * * @param fm Host FragmentManager * @param f Fragment changing state */ public void onFragmentPaused(@NonNull FragmentManager fm, @NonNull Fragment f) {} /** * Called after the fragment has returned from the FragmentManager's call to * {@link Fragment#onStop()}. * * @param fm Host FragmentManager * @param f Fragment changing state */ public void onFragmentStopped(@NonNull FragmentManager fm, @NonNull Fragment f) {} /** * Called after the fragment has returned from the FragmentManager's call to * {@link Fragment#onSaveInstanceState(Bundle)}. * * @param fm Host FragmentManager * @param f Fragment changing state * @param outState Saved state bundle for the fragment */ public void onFragmentSaveInstanceState(@NonNull FragmentManager fm, @NonNull Fragment f, @NonNull Bundle outState) {} /** * Called after the fragment has returned from the FragmentManager's call to * {@link Fragment#onDestroyView()}. * * @param fm Host FragmentManager * @param f Fragment changing state */ public void onFragmentViewDestroyed(@NonNull FragmentManager fm, @NonNull Fragment f) {} /** * Called after the fragment has returned from the FragmentManager's call to * {@link Fragment#onDestroy()}. * * @param fm Host FragmentManager * @param f Fragment changing state */ public void onFragmentDestroyed(@NonNull FragmentManager fm, @NonNull Fragment f) {} /** * Called after the fragment has returned from the FragmentManager's call to * {@link Fragment#onDetach()}. * * @param fm Host FragmentManager * @param f Fragment changing state */ public void onFragmentDetached(@NonNull FragmentManager fm, @NonNull Fragment f) {} } } final class FragmentManagerState implements Parcelable { FragmentState[] mActive; int[] mAdded; BackStackState[] mBackStack; int mPrimaryNavActiveIndex = -1; int mNextFragmentIndex; public FragmentManagerState() { } public FragmentManagerState(Parcel in) { mActive = in.createTypedArray(FragmentState.CREATOR); mAdded = in.createIntArray(); mBackStack = in.createTypedArray(BackStackState.CREATOR); mPrimaryNavActiveIndex = in.readInt(); mNextFragmentIndex = in.readInt(); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeTypedArray(mActive, flags); dest.writeIntArray(mAdded); dest.writeTypedArray(mBackStack, flags); dest.writeInt(mPrimaryNavActiveIndex); dest.writeInt(mNextFragmentIndex); } public static final Parcelable.Creator<FragmentManagerState> CREATOR = new Parcelable.Creator<FragmentManagerState>() { @Override public FragmentManagerState createFromParcel(Parcel in) { return new FragmentManagerState(in); } @Override public FragmentManagerState[] newArray(int size) { return new FragmentManagerState[size]; } }; } /** * Container for fragments associated with an activity. */ final class FragmentManagerImpl extends FragmentManager implements LayoutInflater.Factory2 { static boolean DEBUG = false; static final String TAG = "FragmentManager"; static final String TARGET_REQUEST_CODE_STATE_TAG = "android:target_req_state"; static final String TARGET_STATE_TAG = "android:target_state"; static final String VIEW_STATE_TAG = "android:view_state"; static final String USER_VISIBLE_HINT_TAG = "android:user_visible_hint"; private static final class FragmentLifecycleCallbacksHolder { final FragmentLifecycleCallbacks mCallback; final boolean mRecursive; FragmentLifecycleCallbacksHolder(FragmentLifecycleCallbacks callback, boolean recursive) { mCallback = callback; mRecursive = recursive; } } ArrayList<OpGenerator> mPendingActions; boolean mExecutingActions; int mNextFragmentIndex = 0; final ArrayList<Fragment> mAdded = new ArrayList<>(); SparseArray<Fragment> mActive; ArrayList<BackStackRecord> mBackStack; ArrayList<Fragment> mCreatedMenus; // Must be accessed while locked. ArrayList<BackStackRecord> mBackStackIndices; ArrayList<Integer> mAvailBackStackIndices; ArrayList<OnBackStackChangedListener> mBackStackChangeListeners; private final CopyOnWriteArrayList<FragmentLifecycleCallbacksHolder> mLifecycleCallbacks = new CopyOnWriteArrayList<>(); int mCurState = Fragment.INITIALIZING; FragmentHostCallback mHost; FragmentContainer mContainer; Fragment mParent; @Nullable Fragment mPrimaryNav; static Field sAnimationListenerField = null; boolean mNeedMenuInvalidate; boolean mStateSaved; boolean mStopped; boolean mDestroyed; String mNoTransactionsBecause; boolean mHavePendingDeferredStart; // Temporary vars for removing redundant operations in BackStackRecords: ArrayList<BackStackRecord> mTmpRecords; ArrayList<Boolean> mTmpIsPop; ArrayList<Fragment> mTmpAddedFragments; // Temporary vars for state save and restore. Bundle mStateBundle = null; SparseArray<Parcelable> mStateArray = null; // Postponed transactions. ArrayList<StartEnterTransitionListener> mPostponedTransactions; // Saved FragmentManagerNonConfig during saveAllState() and cleared in noteStateNotSaved() FragmentManagerNonConfig mSavedNonConfig; Runnable mExecCommit = new Runnable() { @Override public void run() { execPendingActions(); } }; static boolean modifiesAlpha(AnimationOrAnimator anim) { if (anim.animation instanceof AlphaAnimation) { return true; } else if (anim.animation instanceof AnimationSet) { List<Animation> anims = ((AnimationSet) anim.animation).getAnimations(); for (int i = 0; i < anims.size(); i++) { if (anims.get(i) instanceof AlphaAnimation) { return true; } } return false; } else { return modifiesAlpha(anim.animator); } } static boolean modifiesAlpha(Animator anim) { if (anim == null) { return false; } if (anim instanceof ValueAnimator) { ValueAnimator valueAnim = (ValueAnimator) anim; PropertyValuesHolder[] values = valueAnim.getValues(); for (int i = 0; i < values.length; i++) { if (("alpha").equals(values[i].getPropertyName())) { return true; } } } else if (anim instanceof AnimatorSet) { List<Animator> animList = ((AnimatorSet) anim).getChildAnimations(); for (int i = 0; i < animList.size(); i++) { if (modifiesAlpha(animList.get(i))) { return true; } } } return false; } static boolean shouldRunOnHWLayer(View v, AnimationOrAnimator anim) { if (v == null || anim == null) { return false; } return Build.VERSION.SDK_INT >= 19 && v.getLayerType() == View.LAYER_TYPE_NONE && ViewCompat.hasOverlappingRendering(v) && modifiesAlpha(anim); } private void throwException(RuntimeException ex) { Log.e(TAG, ex.getMessage()); Log.e(TAG, "Activity state:"); LogWriter logw = new LogWriter(TAG); PrintWriter pw = new PrintWriter(logw); if (mHost != null) { try { mHost.onDump(" ", null, pw, new String[] { }); } catch (Exception e) { Log.e(TAG, "Failed dumping state", e); } } else { try { dump(" ", null, pw, new String[] { }); } catch (Exception e) { Log.e(TAG, "Failed dumping state", e); } } throw ex; } @Override public FragmentTransaction beginTransaction() { return new BackStackRecord(this); } @Override public boolean executePendingTransactions() { boolean updates = execPendingActions(); forcePostponedTransactions(); return updates; } @Override public void popBackStack() { enqueueAction(new PopBackStackState(null, -1, 0), false); } @Override public boolean popBackStackImmediate() { checkStateLoss(); return popBackStackImmediate(null, -1, 0); } @Override public void popBackStack(@Nullable final String name, final int flags) { enqueueAction(new PopBackStackState(name, -1, flags), false); } @Override public boolean popBackStackImmediate(@Nullable String name, int flags) { checkStateLoss(); return popBackStackImmediate(name, -1, flags); } @Override public void popBackStack(final int id, final int flags) { if (id < 0) { throw new IllegalArgumentException("Bad id: " + id); } enqueueAction(new PopBackStackState(null, id, flags), false); } @Override public boolean popBackStackImmediate(int id, int flags) { checkStateLoss(); execPendingActions(); if (id < 0) { throw new IllegalArgumentException("Bad id: " + id); } return popBackStackImmediate(null, id, flags); } /** * Used by all public popBackStackImmediate methods, this executes pending transactions and * returns true if the pop action did anything, regardless of what other pending * transactions did. * * @return true if the pop operation did anything or false otherwise. */ private boolean popBackStackImmediate(String name, int id, int flags) { execPendingActions(); ensureExecReady(true); if (mPrimaryNav != null // We have a primary nav fragment && id < 0 // No valid id (since they're local) && name == null) { // no name to pop to (since they're local) final FragmentManager childManager = mPrimaryNav.peekChildFragmentManager(); if (childManager != null && childManager.popBackStackImmediate()) { // We did something, just not to this specific FragmentManager. Return true. return true; } } boolean executePop = popBackStackState(mTmpRecords, mTmpIsPop, name, id, flags); if (executePop) { mExecutingActions = true; try { removeRedundantOperationsAndExecute(mTmpRecords, mTmpIsPop); } finally { cleanupExec(); } } doPendingDeferredStart(); burpActive(); return executePop; } @Override public int getBackStackEntryCount() { return mBackStack != null ? mBackStack.size() : 0; } @Override public BackStackEntry getBackStackEntryAt(int index) { return mBackStack.get(index); } @Override public void addOnBackStackChangedListener(OnBackStackChangedListener listener) { if (mBackStackChangeListeners == null) { mBackStackChangeListeners = new ArrayList<OnBackStackChangedListener>(); } mBackStackChangeListeners.add(listener); } @Override public void removeOnBackStackChangedListener(OnBackStackChangedListener listener) { if (mBackStackChangeListeners != null) { mBackStackChangeListeners.remove(listener); } } @Override public void putFragment(Bundle bundle, String key, Fragment fragment) { if (fragment.mIndex < 0) { throwException(new IllegalStateException("Fragment " + fragment + " is not currently in the FragmentManager")); } bundle.putInt(key, fragment.mIndex); } @Override @Nullable public Fragment getFragment(Bundle bundle, String key) { int index = bundle.getInt(key, -1); if (index == -1) { return null; } Fragment f = mActive.get(index); if (f == null) { throwException(new IllegalStateException("Fragment no longer exists for key " + key + ": index " + index)); } return f; } @Override public List<Fragment> getFragments() { if (mAdded.isEmpty()) { return Collections.emptyList(); } synchronized (mAdded) { return (List<Fragment>) mAdded.clone(); } } /** * This is used by FragmentController to get the Active fragments. * * @return A list of active fragments in the fragment manager, including those that are in the * back stack. */ List<Fragment> getActiveFragments() { if (mActive == null) { return null; } final int count = mActive.size(); ArrayList<Fragment> fragments = new ArrayList<>(count); for (int i = 0; i < count; i++) { fragments.add(mActive.valueAt(i)); } return fragments; } /** * Used by FragmentController to get the number of Active Fragments. * * @return The number of active fragments. */ int getActiveFragmentCount() { if (mActive == null) { return 0; } return mActive.size(); } @Override @Nullable public Fragment.SavedState saveFragmentInstanceState(Fragment fragment) { if (fragment.mIndex < 0) { throwException( new IllegalStateException("Fragment " + fragment + " is not currently in the FragmentManager")); } if (fragment.mState > Fragment.INITIALIZING) { Bundle result = saveFragmentBasicState(fragment); return result != null ? new Fragment.SavedState(result) : null; } return null; } @Override public boolean isDestroyed() { return mDestroyed; } @Override public String toString() { StringBuilder sb = new StringBuilder(128); sb.append("FragmentManager{"); sb.append(Integer.toHexString(System.identityHashCode(this))); sb.append(" in "); if (mParent != null) { DebugUtils.buildShortClassTag(mParent, sb); } else { DebugUtils.buildShortClassTag(mHost, sb); } sb.append("}}"); return sb.toString(); } @Override public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) { String innerPrefix = prefix + " "; int N; if (mActive != null) { N = mActive.size(); if (N > 0) { writer.print(prefix); writer.print("Active Fragments in "); writer.print(Integer.toHexString(System.identityHashCode(this))); writer.println(":"); for (int i=0; i<N; i++) { Fragment f = mActive.valueAt(i); writer.print(prefix); writer.print(" #"); writer.print(i); writer.print(": "); writer.println(f); if (f != null) { f.dump(innerPrefix, fd, writer, args); } } } } N = mAdded.size(); if (N > 0) { writer.print(prefix); writer.println("Added Fragments:"); for (int i = 0; i < N; i++) { Fragment f = mAdded.get(i); writer.print(prefix); writer.print(" #"); writer.print(i); writer.print(": "); writer.println(f.toString()); } } if (mCreatedMenus != null) { N = mCreatedMenus.size(); if (N > 0) { writer.print(prefix); writer.println("Fragments Created Menus:"); for (int i=0; i<N; i++) { Fragment f = mCreatedMenus.get(i); writer.print(prefix); writer.print(" #"); writer.print(i); writer.print(": "); writer.println(f.toString()); } } } if (mBackStack != null) { N = mBackStack.size(); if (N > 0) { writer.print(prefix); writer.println("Back Stack:"); for (int i=0; i<N; i++) { BackStackRecord bs = mBackStack.get(i); writer.print(prefix); writer.print(" #"); writer.print(i); writer.print(": "); writer.println(bs.toString()); bs.dump(innerPrefix, fd, writer, args); } } } synchronized (this) { if (mBackStackIndices != null) { N = mBackStackIndices.size(); if (N > 0) { writer.print(prefix); writer.println("Back Stack Indices:"); for (int i=0; i<N; i++) { BackStackRecord bs = mBackStackIndices.get(i); writer.print(prefix); writer.print(" #"); writer.print(i); writer.print(": "); writer.println(bs); } } } if (mAvailBackStackIndices != null && mAvailBackStackIndices.size() > 0) { writer.print(prefix); writer.print("mAvailBackStackIndices: "); writer.println(Arrays.toString(mAvailBackStackIndices.toArray())); } } if (mPendingActions != null) { N = mPendingActions.size(); if (N > 0) { writer.print(prefix); writer.println("Pending Actions:"); for (int i=0; i<N; i++) { OpGenerator r = mPendingActions.get(i); writer.print(prefix); writer.print(" #"); writer.print(i); writer.print(": "); writer.println(r); } } } writer.print(prefix); writer.println("FragmentManager misc state:"); writer.print(prefix); writer.print(" mHost="); writer.println(mHost); writer.print(prefix); writer.print(" mContainer="); writer.println(mContainer); if (mParent != null) { writer.print(prefix); writer.print(" mParent="); writer.println(mParent); } writer.print(prefix); writer.print(" mCurState="); writer.print(mCurState); writer.print(" mStateSaved="); writer.print(mStateSaved); writer.print(" mStopped="); writer.print(mStopped); writer.print(" mDestroyed="); writer.println(mDestroyed); if (mNeedMenuInvalidate) { writer.print(prefix); writer.print(" mNeedMenuInvalidate="); writer.println(mNeedMenuInvalidate); } if (mNoTransactionsBecause != null) { writer.print(prefix); writer.print(" mNoTransactionsBecause="); writer.println(mNoTransactionsBecause); } } static final Interpolator DECELERATE_QUINT = new DecelerateInterpolator(2.5f); static final Interpolator DECELERATE_CUBIC = new DecelerateInterpolator(1.5f); static final Interpolator ACCELERATE_QUINT = new AccelerateInterpolator(2.5f); static final Interpolator ACCELERATE_CUBIC = new AccelerateInterpolator(1.5f); static final int ANIM_DUR = 220; static AnimationOrAnimator makeOpenCloseAnimation(Context context, float startScale, float endScale, float startAlpha, float endAlpha) { AnimationSet set = new AnimationSet(false); ScaleAnimation scale = new ScaleAnimation(startScale, endScale, startScale, endScale, Animation.RELATIVE_TO_SELF, .5f, Animation.RELATIVE_TO_SELF, .5f); scale.setInterpolator(DECELERATE_QUINT); scale.setDuration(ANIM_DUR); set.addAnimation(scale); AlphaAnimation alpha = new AlphaAnimation(startAlpha, endAlpha); alpha.setInterpolator(DECELERATE_CUBIC); alpha.setDuration(ANIM_DUR); set.addAnimation(alpha); return new AnimationOrAnimator(set); } static AnimationOrAnimator makeFadeAnimation(Context context, float start, float end) { AlphaAnimation anim = new AlphaAnimation(start, end); anim.setInterpolator(DECELERATE_CUBIC); anim.setDuration(ANIM_DUR); return new AnimationOrAnimator(anim); } AnimationOrAnimator loadAnimation(Fragment fragment, int transit, boolean enter, int transitionStyle) { int nextAnim = fragment.getNextAnim(); Animation animation = fragment.onCreateAnimation(transit, enter, nextAnim); if (animation != null) { return new AnimationOrAnimator(animation); } Animator animator = fragment.onCreateAnimator(transit, enter, nextAnim); if (animator != null) { return new AnimationOrAnimator(animator); } if (nextAnim != 0) { String dir = mHost.getContext().getResources().getResourceTypeName(nextAnim); boolean isAnim = "anim".equals(dir); boolean successfulLoad = false; if (isAnim) { // try AnimationUtils first try { animation = AnimationUtils.loadAnimation(mHost.getContext(), nextAnim); if (animation != null) { return new AnimationOrAnimator(animation); } // A null animation may be returned and that is acceptable successfulLoad = true; // succeeded in loading animation, but it is null } catch (NotFoundException e) { throw e; // Rethrow it -- the resource should be found if it is provided. } catch (RuntimeException e) { // Other exceptions can occur when loading an Animator from AnimationUtils. } } if (!successfulLoad) { // try Animator try { animator = AnimatorInflater.loadAnimator(mHost.getContext(), nextAnim); if (animator != null) { return new AnimationOrAnimator(animator); } } catch (RuntimeException e) { if (isAnim) { // Rethrow it -- we already tried AnimationUtils and it failed. throw e; } // Otherwise, it is probably an animation resource animation = AnimationUtils.loadAnimation(mHost.getContext(), nextAnim); if (animation != null) { return new AnimationOrAnimator(animation); } } } } if (transit == 0) { return null; } int styleIndex = transitToStyleIndex(transit, enter); if (styleIndex < 0) { return null; } switch (styleIndex) { case ANIM_STYLE_OPEN_ENTER: return makeOpenCloseAnimation(mHost.getContext(), 1.125f, 1.0f, 0, 1); case ANIM_STYLE_OPEN_EXIT: return makeOpenCloseAnimation(mHost.getContext(), 1.0f, .975f, 1, 0); case ANIM_STYLE_CLOSE_ENTER: return makeOpenCloseAnimation(mHost.getContext(), .975f, 1.0f, 0, 1); case ANIM_STYLE_CLOSE_EXIT: return makeOpenCloseAnimation(mHost.getContext(), 1.0f, 1.075f, 1, 0); case ANIM_STYLE_FADE_ENTER: return makeFadeAnimation(mHost.getContext(), 0, 1); case ANIM_STYLE_FADE_EXIT: return makeFadeAnimation(mHost.getContext(), 1, 0); } // TODO: remove or fix transitionStyle -- it apparently never worked. if (transitionStyle == 0 && mHost.onHasWindowAnimations()) { transitionStyle = mHost.onGetWindowAnimations(); } if (transitionStyle == 0) { return null; } //TypedArray attrs = mActivity.obtainStyledAttributes(transitionStyle, // com.android.internal.R.styleable.FragmentAnimation); //int anim = attrs.getResourceId(styleIndex, 0); //attrs.recycle(); //if (anim == 0) { // return null; //} //return AnimatorInflater.loadAnimator(mActivity, anim); return null; } public void performPendingDeferredStart(Fragment f) { if (f.mDeferStart) { if (mExecutingActions) { // Wait until we're done executing our pending transactions mHavePendingDeferredStart = true; return; } f.mDeferStart = false; moveToState(f, mCurState, 0, 0, false); } } /** * Sets the to be animated view on hardware layer during the animation. Note * that calling this will replace any existing animation listener on the animation * with a new one, as animations do not support more than one listeners. Therefore, * animations that already have listeners should do the layer change operations * in their existing listeners, rather than calling this function. */ private static void setHWLayerAnimListenerIfAlpha(final View v, AnimationOrAnimator anim) { if (v == null || anim == null) { return; } if (shouldRunOnHWLayer(v, anim)) { if (anim.animator != null) { anim.animator.addListener(new AnimatorOnHWLayerIfNeededListener(v)); } else { AnimationListener originalListener = getAnimationListener(anim.animation); // If there's already a listener set on the animation, we need wrap the new listener // around the existing listener, so that they will both get animation listener // callbacks. v.setLayerType(View.LAYER_TYPE_HARDWARE, null); anim.animation.setAnimationListener(new AnimateOnHWLayerIfNeededListener(v, originalListener)); } } } /** * Returns an existing AnimationListener on an Animation or {@code null} if none exists. */ private static AnimationListener getAnimationListener(Animation animation) { AnimationListener originalListener = null; try { if (sAnimationListenerField == null) { sAnimationListenerField = Animation.class.getDeclaredField("mListener"); sAnimationListenerField.setAccessible(true); } originalListener = (AnimationListener) sAnimationListenerField.get(animation); } catch (NoSuchFieldException e) { Log.e(TAG, "No field with the name mListener is found in Animation class", e); } catch (IllegalAccessException e) { Log.e(TAG, "Cannot access Animation's mListener field", e); } return originalListener; } boolean isStateAtLeast(int state) { return mCurState >= state; } @SuppressWarnings("ReferenceEquality") void moveToState(Fragment f, int newState, int transit, int transitionStyle, boolean keepActive) { // Fragments that are not currently added will sit in the onCreate() state. if ((!f.mAdded || f.mDetached) && newState > Fragment.CREATED) { newState = Fragment.CREATED; } if (f.mRemoving && newState > f.mState) { if (f.mState == Fragment.INITIALIZING && f.isInBackStack()) { // Allow the fragment to be created so that it can be saved later. newState = Fragment.CREATED; } else { // While removing a fragment, we can't change it to a higher state. newState = f.mState; } } // Defer start if requested; don't allow it to move to STARTED or higher // if it's not already started. if (f.mDeferStart && f.mState < Fragment.STARTED && newState > Fragment.ACTIVITY_CREATED) { newState = Fragment.ACTIVITY_CREATED; } if (f.mState <= newState) { // For fragments that are created from a layout, when restoring from // state we don't want to allow them to be created until they are // being reloaded from the layout. if (f.mFromLayout && !f.mInLayout) { return; } if (f.getAnimatingAway() != null || f.getAnimator() != null) { // The fragment is currently being animated... but! Now we // want to move our state back up. Give up on waiting for the // animation, move to whatever the final state should be once // the animation is done, and then we can proceed from there. f.setAnimatingAway(null); f.setAnimator(null); moveToState(f, f.getStateAfterAnimating(), 0, 0, true); } switch (f.mState) { case Fragment.INITIALIZING: if (newState > Fragment.INITIALIZING) { if (DEBUG) Log.v(TAG, "moveto CREATED: " + f); if (f.mSavedFragmentState != null) { f.mSavedFragmentState.setClassLoader(mHost.getContext() .getClassLoader()); f.mSavedViewState = f.mSavedFragmentState.getSparseParcelableArray( FragmentManagerImpl.VIEW_STATE_TAG); f.mTarget = getFragment(f.mSavedFragmentState, FragmentManagerImpl.TARGET_STATE_TAG); if (f.mTarget != null) { f.mTargetRequestCode = f.mSavedFragmentState.getInt( FragmentManagerImpl.TARGET_REQUEST_CODE_STATE_TAG, 0); } if (f.mSavedUserVisibleHint != null) { f.mUserVisibleHint = f.mSavedUserVisibleHint; f.mSavedUserVisibleHint = null; } else { f.mUserVisibleHint = f.mSavedFragmentState.getBoolean( FragmentManagerImpl.USER_VISIBLE_HINT_TAG, true); } if (!f.mUserVisibleHint) { f.mDeferStart = true; if (newState > Fragment.ACTIVITY_CREATED) { newState = Fragment.ACTIVITY_CREATED; } } } f.mHost = mHost; f.mParentFragment = mParent; f.mFragmentManager = mParent != null ? mParent.mChildFragmentManager : mHost.getFragmentManagerImpl(); // If we have a target fragment, push it along to at least CREATED // so that this one can rely on it as an initialized dependency. if (f.mTarget != null) { if (mActive.get(f.mTarget.mIndex) != f.mTarget) { throw new IllegalStateException("Fragment " + f + " declared target fragment " + f.mTarget + " that does not belong to this FragmentManager!"); } if (f.mTarget.mState < Fragment.CREATED) { moveToState(f.mTarget, Fragment.CREATED, 0, 0, true); } } dispatchOnFragmentPreAttached(f, mHost.getContext(), false); f.mCalled = false; f.onAttach(mHost.getContext()); if (!f.mCalled) { throw new SuperNotCalledException("Fragment " + f + " did not call through to super.onAttach()"); } if (f.mParentFragment == null) { mHost.onAttachFragment(f); } else { f.mParentFragment.onAttachFragment(f); } dispatchOnFragmentAttached(f, mHost.getContext(), false); if (!f.mIsCreated) { dispatchOnFragmentPreCreated(f, f.mSavedFragmentState, false); f.performCreate(f.mSavedFragmentState); dispatchOnFragmentCreated(f, f.mSavedFragmentState, false); } else { f.restoreChildFragmentState(f.mSavedFragmentState); f.mState = Fragment.CREATED; } f.mRetaining = false; } // fall through case Fragment.CREATED: // This is outside the if statement below on purpose; we want this to run // even if we do a moveToState from CREATED => *, CREATED => CREATED, and // * => CREATED as part of the case fallthrough above. ensureInflatedFragmentView(f); if (newState > Fragment.CREATED) { if (DEBUG) Log.v(TAG, "moveto ACTIVITY_CREATED: " + f); if (!f.mFromLayout) { ViewGroup container = null; if (f.mContainerId != 0) { if (f.mContainerId == View.NO_ID) { throwException(new IllegalArgumentException( "Cannot create fragment " + f + " for a container view with no id")); } container = (ViewGroup) mContainer.onFindViewById(f.mContainerId); if (container == null && !f.mRestored) { String resName; try { resName = f.getResources().getResourceName(f.mContainerId); } catch (NotFoundException e) { resName = "unknown"; } throwException(new IllegalArgumentException( "No view found for id 0x" + Integer.toHexString(f.mContainerId) + " (" + resName + ") for fragment " + f)); } } f.mContainer = container; f.performCreateView(f.performGetLayoutInflater( f.mSavedFragmentState), container, f.mSavedFragmentState); if (f.mView != null) { f.mInnerView = f.mView; f.mView.setSaveFromParentEnabled(false); if (container != null) { container.addView(f.mView); } if (f.mHidden) { f.mView.setVisibility(View.GONE); } f.onViewCreated(f.mView, f.mSavedFragmentState); dispatchOnFragmentViewCreated(f, f.mView, f.mSavedFragmentState, false); // Only animate the view if it is visible. This is done after // dispatchOnFragmentViewCreated in case visibility is changed f.mIsNewlyAdded = (f.mView.getVisibility() == View.VISIBLE) && f.mContainer != null; } else { f.mInnerView = null; } } f.performActivityCreated(f.mSavedFragmentState); dispatchOnFragmentActivityCreated(f, f.mSavedFragmentState, false); if (f.mView != null) { f.restoreViewState(f.mSavedFragmentState); } f.mSavedFragmentState = null; } // fall through case Fragment.ACTIVITY_CREATED: if (newState > Fragment.ACTIVITY_CREATED) { if (DEBUG) Log.v(TAG, "moveto STARTED: " + f); f.performStart(); dispatchOnFragmentStarted(f, false); } // fall through case Fragment.STARTED: if (newState > Fragment.STARTED) { if (DEBUG) Log.v(TAG, "moveto RESUMED: " + f); f.performResume(); dispatchOnFragmentResumed(f, false); f.mSavedFragmentState = null; f.mSavedViewState = null; } } } else if (f.mState > newState) { switch (f.mState) { case Fragment.RESUMED: if (newState < Fragment.RESUMED) { if (DEBUG) Log.v(TAG, "movefrom RESUMED: " + f); f.performPause(); dispatchOnFragmentPaused(f, false); } // fall through case Fragment.STARTED: if (newState < Fragment.STARTED) { if (DEBUG) Log.v(TAG, "movefrom STARTED: " + f); f.performStop(); dispatchOnFragmentStopped(f, false); } // fall through case Fragment.ACTIVITY_CREATED: if (newState < Fragment.ACTIVITY_CREATED) { if (DEBUG) Log.v(TAG, "movefrom ACTIVITY_CREATED: " + f); if (f.mView != null) { // Need to save the current view state if not // done already. if (mHost.onShouldSaveFragmentState(f) && f.mSavedViewState == null) { saveFragmentViewState(f); } } f.performDestroyView(); dispatchOnFragmentViewDestroyed(f, false); if (f.mView != null && f.mContainer != null) { // Stop any current animations: f.mContainer.endViewTransition(f.mView); f.mView.clearAnimation(); AnimationOrAnimator anim = null; if (mCurState > Fragment.INITIALIZING && !mDestroyed && f.mView.getVisibility() == View.VISIBLE && f.mPostponedAlpha >= 0) { anim = loadAnimation(f, transit, false, transitionStyle); } f.mPostponedAlpha = 0; if (anim != null) { animateRemoveFragment(f, anim, newState); } f.mContainer.removeView(f.mView); } f.mContainer = null; f.mView = null; // Set here to ensure that Observers are called after // the Fragment's view is set to null f.mViewLifecycleOwner = null; f.mViewLifecycleOwnerLiveData.setValue(null); f.mInnerView = null; f.mInLayout = false; } // fall through case Fragment.CREATED: if (newState < Fragment.CREATED) { if (mDestroyed) { // The fragment's containing activity is // being destroyed, but this fragment is // currently animating away. Stop the // animation right now -- it is not needed, // and we can't wait any more on destroying // the fragment. if (f.getAnimatingAway() != null) { View v = f.getAnimatingAway(); f.setAnimatingAway(null); v.clearAnimation(); } else if (f.getAnimator() != null) { Animator animator = f.getAnimator(); f.setAnimator(null); animator.cancel(); } } if (f.getAnimatingAway() != null || f.getAnimator() != null) { // We are waiting for the fragment's view to finish // animating away. Just make a note of the state // the fragment now should move to once the animation // is done. f.setStateAfterAnimating(newState); newState = Fragment.CREATED; } else { if (DEBUG) Log.v(TAG, "movefrom CREATED: " + f); if (!f.mRetaining) { f.performDestroy(); dispatchOnFragmentDestroyed(f, false); } else { f.mState = Fragment.INITIALIZING; } f.performDetach(); dispatchOnFragmentDetached(f, false); if (!keepActive) { if (!f.mRetaining) { makeInactive(f); } else { f.mHost = null; f.mParentFragment = null; f.mFragmentManager = null; } } } } } } if (f.mState != newState) { Log.w(TAG, "moveToState: Fragment state for " + f + " not updated inline; " + "expected state " + newState + " found " + f.mState); f.mState = newState; } } /** * Animates the removal of a fragment with the given animator or animation. After animating, * the fragment's view will be removed from the hierarchy. * * @param fragment The fragment to animate out * @param anim The animator or animation to run on the fragment's view * @param newState The final state after animating. */ private void animateRemoveFragment(@NonNull final Fragment fragment, @NonNull AnimationOrAnimator anim, final int newState) { final View viewToAnimate = fragment.mView; final ViewGroup container = fragment.mContainer; container.startViewTransition(viewToAnimate); fragment.setStateAfterAnimating(newState); if (anim.animation != null) { Animation animation = new EndViewTransitionAnimator(anim.animation, container, viewToAnimate); fragment.setAnimatingAway(fragment.mView); AnimationListener listener = getAnimationListener(animation); animation.setAnimationListener(new AnimationListenerWrapper(listener) { @Override public void onAnimationEnd(Animation animation) { super.onAnimationEnd(animation); // onAnimationEnd() comes during draw(), so there can still be some // draw events happening after this call. We don't want to detach // the view until after the onAnimationEnd() container.post(new Runnable() { @Override public void run() { if (fragment.getAnimatingAway() != null) { fragment.setAnimatingAway(null); moveToState(fragment, fragment.getStateAfterAnimating(), 0, 0, false); } } }); } }); setHWLayerAnimListenerIfAlpha(viewToAnimate, anim); fragment.mView.startAnimation(animation); } else { Animator animator = anim.animator; fragment.setAnimator(anim.animator); animator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator anim) { container.endViewTransition(viewToAnimate); // If an animator ends immediately, we can just pretend there is no animation. // When that happens the the fragment's view won't have been removed yet. Animator animator = fragment.getAnimator(); fragment.setAnimator(null); if (animator != null && container.indexOfChild(viewToAnimate) < 0) { moveToState(fragment, fragment.getStateAfterAnimating(), 0, 0, false); } } }); animator.setTarget(fragment.mView); setHWLayerAnimListenerIfAlpha(fragment.mView, anim); animator.start(); } } void moveToState(Fragment f) { moveToState(f, mCurState, 0, 0, false); } void ensureInflatedFragmentView(Fragment f) { if (f.mFromLayout && !f.mPerformedCreateView) { f.performCreateView(f.performGetLayoutInflater( f.mSavedFragmentState), null, f.mSavedFragmentState); if (f.mView != null) { f.mInnerView = f.mView; f.mView.setSaveFromParentEnabled(false); if (f.mHidden) f.mView.setVisibility(View.GONE); f.onViewCreated(f.mView, f.mSavedFragmentState); dispatchOnFragmentViewCreated(f, f.mView, f.mSavedFragmentState, false); } else { f.mInnerView = null; } } } /** * Fragments that have been shown or hidden don't have their visibility changed or * animations run during the {@link #showFragment(Fragment)} or {@link #hideFragment(Fragment)} * calls. After fragments are brought to their final state in * {@link #moveFragmentToExpectedState(Fragment)} the fragments that have been shown or * hidden must have their visibility changed and their animations started here. * * @param fragment The fragment with mHiddenChanged = true that should change its View's * visibility and start the show or hide animation. */ void completeShowHideFragment(final Fragment fragment) { if (fragment.mView != null) { AnimationOrAnimator anim = loadAnimation(fragment, fragment.getNextTransition(), !fragment.mHidden, fragment.getNextTransitionStyle()); if (anim != null && anim.animator != null) { anim.animator.setTarget(fragment.mView); if (fragment.mHidden) { if (fragment.isHideReplaced()) { fragment.setHideReplaced(false); } else { final ViewGroup container = fragment.mContainer; final View animatingView = fragment.mView; container.startViewTransition(animatingView); // Delay the actual hide operation until the animation finishes, // otherwise the fragment will just immediately disappear anim.animator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { container.endViewTransition(animatingView); animation.removeListener(this); if (fragment.mView != null) { fragment.mView.setVisibility(View.GONE); } } }); } } else { fragment.mView.setVisibility(View.VISIBLE); } setHWLayerAnimListenerIfAlpha(fragment.mView, anim); anim.animator.start(); } else { if (anim != null) { setHWLayerAnimListenerIfAlpha(fragment.mView, anim); fragment.mView.startAnimation(anim.animation); anim.animation.start(); } final int visibility = fragment.mHidden && !fragment.isHideReplaced() ? View.GONE : View.VISIBLE; fragment.mView.setVisibility(visibility); if (fragment.isHideReplaced()) { fragment.setHideReplaced(false); } } } if (fragment.mAdded && fragment.mHasMenu && fragment.mMenuVisible) { mNeedMenuInvalidate = true; } fragment.mHiddenChanged = false; fragment.onHiddenChanged(fragment.mHidden); } /** * Moves a fragment to its expected final state or the fragment manager's state, depending * on whether the fragment manager's state is raised properly. * * @param f The fragment to change. */ void moveFragmentToExpectedState(Fragment f) { if (f == null) { return; } int nextState = mCurState; if (f.mRemoving) { if (f.isInBackStack()) { nextState = Math.min(nextState, Fragment.CREATED); } else { nextState = Math.min(nextState, Fragment.INITIALIZING); } } moveToState(f, nextState, f.getNextTransition(), f.getNextTransitionStyle(), false); if (f.mView != null) { // Move the view if it is out of order Fragment underFragment = findFragmentUnder(f); if (underFragment != null) { final View underView = underFragment.mView; // make sure this fragment is in the right order. final ViewGroup container = f.mContainer; int underIndex = container.indexOfChild(underView); int viewIndex = container.indexOfChild(f.mView); if (viewIndex < underIndex) { container.removeViewAt(viewIndex); container.addView(f.mView, underIndex); } } if (f.mIsNewlyAdded && f.mContainer != null) { // Make it visible and run the animations if (f.mPostponedAlpha > 0f) { f.mView.setAlpha(f.mPostponedAlpha); } f.mPostponedAlpha = 0f; f.mIsNewlyAdded = false; // run animations: AnimationOrAnimator anim = loadAnimation(f, f.getNextTransition(), true, f.getNextTransitionStyle()); if (anim != null) { setHWLayerAnimListenerIfAlpha(f.mView, anim); if (anim.animation != null) { f.mView.startAnimation(anim.animation); } else { anim.animator.setTarget(f.mView); anim.animator.start(); } } } } if (f.mHiddenChanged) { completeShowHideFragment(f); } } /** * Changes the state of the fragment manager to {@code newState}. If the fragment manager * changes state or {@code always} is {@code true}, any fragments within it have their * states updated as well. * * @param newState The new state for the fragment manager * @param always If {@code true}, all fragments update their state, even * if {@code newState} matches the current fragment manager's state. */ void moveToState(int newState, boolean always) { if (mHost == null && newState != Fragment.INITIALIZING) { throw new IllegalStateException("No activity"); } if (!always && newState == mCurState) { return; } mCurState = newState; if (mActive != null) { // Must add them in the proper order. mActive fragments may be out of order final int numAdded = mAdded.size(); for (int i = 0; i < numAdded; i++) { Fragment f = mAdded.get(i); moveFragmentToExpectedState(f); } // Now iterate through all active fragments. These will include those that are removed // and detached. final int numActive = mActive.size(); for (int i = 0; i < numActive; i++) { Fragment f = mActive.valueAt(i); if (f != null && (f.mRemoving || f.mDetached) && !f.mIsNewlyAdded) { moveFragmentToExpectedState(f); } } startPendingDeferredFragments(); if (mNeedMenuInvalidate && mHost != null && mCurState == Fragment.RESUMED) { mHost.onSupportInvalidateOptionsMenu(); mNeedMenuInvalidate = false; } } } void startPendingDeferredFragments() { if (mActive == null) return; for (int i=0; i<mActive.size(); i++) { Fragment f = mActive.valueAt(i); if (f != null) { performPendingDeferredStart(f); } } } void makeActive(Fragment f) { if (f.mIndex >= 0) { return; } f.setIndex(mNextFragmentIndex++, mParent); if (mActive == null) { mActive = new SparseArray<>(); } mActive.put(f.mIndex, f); if (DEBUG) Log.v(TAG, "Allocated fragment index " + f); } void makeInactive(Fragment f) { if (f.mIndex < 0) { return; } if (DEBUG) Log.v(TAG, "Freeing fragment index " + f); // Don't remove yet. That happens in burpActive(). This prevents // concurrent modification while iterating over mActive mActive.put(f.mIndex, null); f.initState(); } public void addFragment(Fragment fragment, boolean moveToStateNow) { if (DEBUG) Log.v(TAG, "add: " + fragment); makeActive(fragment); if (!fragment.mDetached) { if (mAdded.contains(fragment)) { throw new IllegalStateException("Fragment already added: " + fragment); } synchronized (mAdded) { mAdded.add(fragment); } fragment.mAdded = true; fragment.mRemoving = false; if (fragment.mView == null) { fragment.mHiddenChanged = false; } if (fragment.mHasMenu && fragment.mMenuVisible) { mNeedMenuInvalidate = true; } if (moveToStateNow) { moveToState(fragment); } } } public void removeFragment(Fragment fragment) { if (DEBUG) Log.v(TAG, "remove: " + fragment + " nesting=" + fragment.mBackStackNesting); final boolean inactive = !fragment.isInBackStack(); if (!fragment.mDetached || inactive) { synchronized (mAdded) { mAdded.remove(fragment); } if (fragment.mHasMenu && fragment.mMenuVisible) { mNeedMenuInvalidate = true; } fragment.mAdded = false; fragment.mRemoving = true; } } /** * Marks a fragment as hidden to be later animated in with * {@link #completeShowHideFragment(Fragment)}. * * @param fragment The fragment to be shown. */ public void hideFragment(Fragment fragment) { if (DEBUG) Log.v(TAG, "hide: " + fragment); if (!fragment.mHidden) { fragment.mHidden = true; // Toggle hidden changed so that if a fragment goes through show/hide/show // it doesn't go through the animation. fragment.mHiddenChanged = !fragment.mHiddenChanged; } } /** * Marks a fragment as shown to be later animated in with * {@link #completeShowHideFragment(Fragment)}. * * @param fragment The fragment to be shown. */ public void showFragment(Fragment fragment) { if (DEBUG) Log.v(TAG, "show: " + fragment); if (fragment.mHidden) { fragment.mHidden = false; // Toggle hidden changed so that if a fragment goes through show/hide/show // it doesn't go through the animation. fragment.mHiddenChanged = !fragment.mHiddenChanged; } } public void detachFragment(Fragment fragment) { if (DEBUG) Log.v(TAG, "detach: " + fragment); if (!fragment.mDetached) { fragment.mDetached = true; if (fragment.mAdded) { // We are not already in back stack, so need to remove the fragment. if (DEBUG) Log.v(TAG, "remove from detach: " + fragment); synchronized (mAdded) { mAdded.remove(fragment); } if (fragment.mHasMenu && fragment.mMenuVisible) { mNeedMenuInvalidate = true; } fragment.mAdded = false; } } } public void attachFragment(Fragment fragment) { if (DEBUG) Log.v(TAG, "attach: " + fragment); if (fragment.mDetached) { fragment.mDetached = false; if (!fragment.mAdded) { if (mAdded.contains(fragment)) { throw new IllegalStateException("Fragment already added: " + fragment); } if (DEBUG) Log.v(TAG, "add from attach: " + fragment); synchronized (mAdded) { mAdded.add(fragment); } fragment.mAdded = true; if (fragment.mHasMenu && fragment.mMenuVisible) { mNeedMenuInvalidate = true; } } } } @Override @Nullable public Fragment findFragmentById(int id) { // First look through added fragments. for (int i = mAdded.size() - 1; i >= 0; i--) { Fragment f = mAdded.get(i); if (f != null && f.mFragmentId == id) { return f; } } if (mActive != null) { // Now for any known fragment. for (int i=mActive.size()-1; i>=0; i--) { Fragment f = mActive.valueAt(i); if (f != null && f.mFragmentId == id) { return f; } } } return null; } @Override @Nullable public Fragment findFragmentByTag(@Nullable String tag) { if (tag != null) { // First look through added fragments. for (int i=mAdded.size()-1; i>=0; i--) { Fragment f = mAdded.get(i); if (f != null && tag.equals(f.mTag)) { return f; } } } if (mActive != null && tag != null) { // Now for any known fragment. for (int i=mActive.size()-1; i>=0; i--) { Fragment f = mActive.valueAt(i); if (f != null && tag.equals(f.mTag)) { return f; } } } return null; } public Fragment findFragmentByWho(String who) { if (mActive != null && who != null) { for (int i=mActive.size()-1; i>=0; i--) { Fragment f = mActive.valueAt(i); if (f != null && (f=f.findFragmentByWho(who)) != null) { return f; } } } return null; } private void checkStateLoss() { if (isStateSaved()) { throw new IllegalStateException( "Can not perform this action after onSaveInstanceState"); } if (mNoTransactionsBecause != null) { throw new IllegalStateException( "Can not perform this action inside of " + mNoTransactionsBecause); } } @Override public boolean isStateSaved() { // See saveAllState() for the explanation of this. We do this for // all platform versions, to keep our behavior more consistent between // them. return mStateSaved || mStopped; } /** * Adds an action to the queue of pending actions. * * @param action the action to add * @param allowStateLoss whether to allow loss of state information * @throws IllegalStateException if the activity has been destroyed */ public void enqueueAction(OpGenerator action, boolean allowStateLoss) { if (!allowStateLoss) { checkStateLoss(); } synchronized (this) { if (mDestroyed || mHost == null) { if (allowStateLoss) { // This FragmentManager isn't attached, so drop the entire transaction. return; } throw new IllegalStateException("Activity has been destroyed"); } if (mPendingActions == null) { mPendingActions = new ArrayList<>(); } mPendingActions.add(action); scheduleCommit(); } } /** * Schedules the execution when one hasn't been scheduled already. This should happen * the first time {@link #enqueueAction(OpGenerator, boolean)} is called or when * a postponed transaction has been started with * {@link Fragment#startPostponedEnterTransition()} */ @SuppressWarnings("WeakerAccess") /* synthetic access */ void scheduleCommit() { synchronized (this) { boolean postponeReady = mPostponedTransactions != null && !mPostponedTransactions.isEmpty(); boolean pendingReady = mPendingActions != null && mPendingActions.size() == 1; if (postponeReady || pendingReady) { mHost.getHandler().removeCallbacks(mExecCommit); mHost.getHandler().post(mExecCommit); } } } public int allocBackStackIndex(BackStackRecord bse) { synchronized (this) { if (mAvailBackStackIndices == null || mAvailBackStackIndices.size() <= 0) { if (mBackStackIndices == null) { mBackStackIndices = new ArrayList<BackStackRecord>(); } int index = mBackStackIndices.size(); if (DEBUG) Log.v(TAG, "Setting back stack index " + index + " to " + bse); mBackStackIndices.add(bse); return index; } else { int index = mAvailBackStackIndices.remove(mAvailBackStackIndices.size()-1); if (DEBUG) Log.v(TAG, "Adding back stack index " + index + " with " + bse); mBackStackIndices.set(index, bse); return index; } } } public void setBackStackIndex(int index, BackStackRecord bse) { synchronized (this) { if (mBackStackIndices == null) { mBackStackIndices = new ArrayList<BackStackRecord>(); } int N = mBackStackIndices.size(); if (index < N) { if (DEBUG) Log.v(TAG, "Setting back stack index " + index + " to " + bse); mBackStackIndices.set(index, bse); } else { while (N < index) { mBackStackIndices.add(null); if (mAvailBackStackIndices == null) { mAvailBackStackIndices = new ArrayList<Integer>(); } if (DEBUG) Log.v(TAG, "Adding available back stack index " + N); mAvailBackStackIndices.add(N); N++; } if (DEBUG) Log.v(TAG, "Adding back stack index " + index + " with " + bse); mBackStackIndices.add(bse); } } } public void freeBackStackIndex(int index) { synchronized (this) { mBackStackIndices.set(index, null); if (mAvailBackStackIndices == null) { mAvailBackStackIndices = new ArrayList<Integer>(); } if (DEBUG) Log.v(TAG, "Freeing back stack index " + index); mAvailBackStackIndices.add(index); } } /** * Broken out from exec*, this prepares for gathering and executing operations. * * @param allowStateLoss true if state loss should be ignored or false if it should be * checked. */ private void ensureExecReady(boolean allowStateLoss) { if (mExecutingActions) { throw new IllegalStateException("FragmentManager is already executing transactions"); } if (mHost == null) { throw new IllegalStateException("Fragment host has been destroyed"); } if (Looper.myLooper() != mHost.getHandler().getLooper()) { throw new IllegalStateException("Must be called from main thread of fragment host"); } if (!allowStateLoss) { checkStateLoss(); } if (mTmpRecords == null) { mTmpRecords = new ArrayList<>(); mTmpIsPop = new ArrayList<>(); } mExecutingActions = true; try { executePostponedTransaction(null, null); } finally { mExecutingActions = false; } } public void execSingleAction(OpGenerator action, boolean allowStateLoss) { if (allowStateLoss && (mHost == null || mDestroyed)) { // This FragmentManager isn't attached, so drop the entire transaction. return; } ensureExecReady(allowStateLoss); if (action.generateOps(mTmpRecords, mTmpIsPop)) { mExecutingActions = true; try { removeRedundantOperationsAndExecute(mTmpRecords, mTmpIsPop); } finally { cleanupExec(); } } doPendingDeferredStart(); burpActive(); } /** * Broken out of exec*, this cleans up the mExecutingActions and the temporary structures * used in executing operations. */ private void cleanupExec() { mExecutingActions = false; mTmpIsPop.clear(); mTmpRecords.clear(); } /** * Only call from main thread! */ public boolean execPendingActions() { ensureExecReady(true); boolean didSomething = false; while (generateOpsForPendingActions(mTmpRecords, mTmpIsPop)) { mExecutingActions = true; try { removeRedundantOperationsAndExecute(mTmpRecords, mTmpIsPop); } finally { cleanupExec(); } didSomething = true; } doPendingDeferredStart(); burpActive(); return didSomething; } /** * Complete the execution of transactions that have previously been postponed, but are * now ready. */ private void executePostponedTransaction(ArrayList<BackStackRecord> records, ArrayList<Boolean> isRecordPop) { int numPostponed = mPostponedTransactions == null ? 0 : mPostponedTransactions.size(); for (int i = 0; i < numPostponed; i++) { StartEnterTransitionListener listener = mPostponedTransactions.get(i); if (records != null && !listener.mIsBack) { int index = records.indexOf(listener.mRecord); if (index != -1 && isRecordPop.get(index)) { listener.cancelTransaction(); continue; } } if (listener.isReady() || (records != null && listener.mRecord.interactsWith(records, 0, records.size()))) { mPostponedTransactions.remove(i); i--; numPostponed--; int index; if (records != null && !listener.mIsBack && (index = records.indexOf(listener.mRecord)) != -1 && isRecordPop.get(index)) { // This is popping a postponed transaction listener.cancelTransaction(); } else { listener.completeTransaction(); } } } } /** * Remove redundant BackStackRecord operations and executes them. This method merges operations * of proximate records that allow reordering. See * {@link FragmentTransaction#setReorderingAllowed(boolean)}. * <p> * For example, a transaction that adds to the back stack and then another that pops that * back stack record will be optimized to remove the unnecessary operation. * <p> * Likewise, two transactions committed that are executed at the same time will be optimized * to remove the redundant operations as well as two pop operations executed together. * * @param records The records pending execution * @param isRecordPop The direction that these records are being run. */ private void removeRedundantOperationsAndExecute(ArrayList<BackStackRecord> records, ArrayList<Boolean> isRecordPop) { if (records == null || records.isEmpty()) { return; } if (isRecordPop == null || records.size() != isRecordPop.size()) { throw new IllegalStateException("Internal error with the back stack records"); } // Force start of any postponed transactions that interact with scheduled transactions: executePostponedTransaction(records, isRecordPop); final int numRecords = records.size(); int startIndex = 0; for (int recordNum = 0; recordNum < numRecords; recordNum++) { final boolean canReorder = records.get(recordNum).mReorderingAllowed; if (!canReorder) { // execute all previous transactions if (startIndex != recordNum) { executeOpsTogether(records, isRecordPop, startIndex, recordNum); } // execute all pop operations that don't allow reordering together or // one add operation int reorderingEnd = recordNum + 1; if (isRecordPop.get(recordNum)) { while (reorderingEnd < numRecords && isRecordPop.get(reorderingEnd) && !records.get(reorderingEnd).mReorderingAllowed) { reorderingEnd++; } } executeOpsTogether(records, isRecordPop, recordNum, reorderingEnd); startIndex = reorderingEnd; recordNum = reorderingEnd - 1; } } if (startIndex != numRecords) { executeOpsTogether(records, isRecordPop, startIndex, numRecords); } } /** * Executes a subset of a list of BackStackRecords, all of which either allow reordering or * do not allow ordering. * @param records A list of BackStackRecords that are to be executed * @param isRecordPop The direction that these records are being run. * @param startIndex The index of the first record in <code>records</code> to be executed * @param endIndex One more than the final record index in <code>records</code> to executed. */ private void executeOpsTogether(ArrayList<BackStackRecord> records, ArrayList<Boolean> isRecordPop, int startIndex, int endIndex) { final boolean allowReordering = records.get(startIndex).mReorderingAllowed; boolean addToBackStack = false; if (mTmpAddedFragments == null) { mTmpAddedFragments = new ArrayList<>(); } else { mTmpAddedFragments.clear(); } mTmpAddedFragments.addAll(mAdded); Fragment oldPrimaryNav = getPrimaryNavigationFragment(); for (int recordNum = startIndex; recordNum < endIndex; recordNum++) { final BackStackRecord record = records.get(recordNum); final boolean isPop = isRecordPop.get(recordNum); if (!isPop) { oldPrimaryNav = record.expandOps(mTmpAddedFragments, oldPrimaryNav); } else { oldPrimaryNav = record.trackAddedFragmentsInPop(mTmpAddedFragments, oldPrimaryNav); } addToBackStack = addToBackStack || record.mAddToBackStack; } mTmpAddedFragments.clear(); if (!allowReordering) { FragmentTransition.startTransitions(this, records, isRecordPop, startIndex, endIndex, false); } executeOps(records, isRecordPop, startIndex, endIndex); int postponeIndex = endIndex; if (allowReordering) { ArraySet<Fragment> addedFragments = new ArraySet<>(); addAddedFragments(addedFragments); postponeIndex = postponePostponableTransactions(records, isRecordPop, startIndex, endIndex, addedFragments); makeRemovedFragmentsInvisible(addedFragments); } if (postponeIndex != startIndex && allowReordering) { // need to run something now FragmentTransition.startTransitions(this, records, isRecordPop, startIndex, postponeIndex, true); moveToState(mCurState, true); } for (int recordNum = startIndex; recordNum < endIndex; recordNum++) { final BackStackRecord record = records.get(recordNum); final boolean isPop = isRecordPop.get(recordNum); if (isPop && record.mIndex >= 0) { freeBackStackIndex(record.mIndex); record.mIndex = -1; } record.runOnCommitRunnables(); } if (addToBackStack) { reportBackStackChanged(); } } /** * Any fragments that were removed because they have been postponed should have their views * made invisible by setting their alpha to 0. * * @param fragments The fragments that were added during operation execution. Only the ones * that are no longer added will have their alpha changed. */ private void makeRemovedFragmentsInvisible(ArraySet<Fragment> fragments) { final int numAdded = fragments.size(); for (int i = 0; i < numAdded; i++) { final Fragment fragment = fragments.valueAt(i); if (!fragment.mAdded) { final View view = fragment.getView(); fragment.mPostponedAlpha = view.getAlpha(); view.setAlpha(0f); } } } /** * Examine all transactions and determine which ones are marked as postponed. Those will * have their operations rolled back and moved to the end of the record list (up to endIndex). * It will also add the postponed transaction to the queue. * * @param records A list of BackStackRecords that should be checked. * @param isRecordPop The direction that these records are being run. * @param startIndex The index of the first record in <code>records</code> to be checked * @param endIndex One more than the final record index in <code>records</code> to be checked. * @return The index of the first postponed transaction or endIndex if no transaction was * postponed. */ private int postponePostponableTransactions(ArrayList<BackStackRecord> records, ArrayList<Boolean> isRecordPop, int startIndex, int endIndex, ArraySet<Fragment> added) { int postponeIndex = endIndex; for (int i = endIndex - 1; i >= startIndex; i--) { final BackStackRecord record = records.get(i); final boolean isPop = isRecordPop.get(i); boolean isPostponed = record.isPostponed() && !record.interactsWith(records, i + 1, endIndex); if (isPostponed) { if (mPostponedTransactions == null) { mPostponedTransactions = new ArrayList<>(); } StartEnterTransitionListener listener = new StartEnterTransitionListener(record, isPop); mPostponedTransactions.add(listener); record.setOnStartPostponedListener(listener); // roll back the transaction if (isPop) { record.executeOps(); } else { record.executePopOps(false); } // move to the end postponeIndex--; if (i != postponeIndex) { records.remove(i); records.add(postponeIndex, record); } // different views may be visible now addAddedFragments(added); } } return postponeIndex; } /** * When a postponed transaction is ready to be started, this completes the transaction, * removing, hiding, or showing views as well as starting the animations and transitions. * <p> * {@code runtransitions} is set to false when the transaction postponement was interrupted * abnormally -- normally by a new transaction being started that affects the postponed * transaction. * * @param record The transaction to run * @param isPop true if record is popping or false if it is adding * @param runTransitions true if the fragment transition should be run or false otherwise. * @param moveToState true if the state should be changed after executing the operations. * This is false when the transaction is canceled when a postponed * transaction is popped. */ @SuppressWarnings("WeakerAccess") /* synthetic access */ void completeExecute(BackStackRecord record, boolean isPop, boolean runTransitions, boolean moveToState) { if (isPop) { record.executePopOps(moveToState); } else { record.executeOps(); } ArrayList<BackStackRecord> records = new ArrayList<>(1); ArrayList<Boolean> isRecordPop = new ArrayList<>(1); records.add(record); isRecordPop.add(isPop); if (runTransitions) { FragmentTransition.startTransitions(this, records, isRecordPop, 0, 1, true); } if (moveToState) { moveToState(mCurState, true); } if (mActive != null) { final int numActive = mActive.size(); for (int i = 0; i < numActive; i++) { // Allow added fragments to be removed during the pop since we aren't going // to move them to the final state with moveToState(mCurState). Fragment fragment = mActive.valueAt(i); if (fragment != null && fragment.mView != null && fragment.mIsNewlyAdded && record.interactsWith(fragment.mContainerId)) { if (fragment.mPostponedAlpha > 0) { fragment.mView.setAlpha(fragment.mPostponedAlpha); } if (moveToState) { fragment.mPostponedAlpha = 0; } else { fragment.mPostponedAlpha = -1; fragment.mIsNewlyAdded = false; } } } } } /** * Find a fragment within the fragment's container whose View should be below the passed * fragment. {@code null} is returned when the fragment has no View or if there should be * no fragment with a View below the given fragment. * * As an example, if mAdded has two Fragments with Views sharing the same container: * FragmentA * FragmentB * * Then, when processing FragmentB, FragmentA will be returned. If, however, FragmentA * had no View, null would be returned. * * @param f The fragment that may be on top of another fragment. * @return The fragment with a View under f, if one exists or null if f has no View or * there are no fragments with Views in the same container. */ private Fragment findFragmentUnder(Fragment f) { final ViewGroup container = f.mContainer; final View view = f.mView; if (container == null || view == null) { return null; } final int fragmentIndex = mAdded.indexOf(f); for (int i = fragmentIndex - 1; i >= 0; i--) { Fragment underFragment = mAdded.get(i); if (underFragment.mContainer == container && underFragment.mView != null) { // Found the fragment under this one return underFragment; } } return null; } /** * Run the operations in the BackStackRecords, either to push or pop. * * @param records The list of records whose operations should be run. * @param isRecordPop The direction that these records are being run. * @param startIndex The index of the first entry in records to run. * @param endIndex One past the index of the final entry in records to run. */ private static void executeOps(ArrayList<BackStackRecord> records, ArrayList<Boolean> isRecordPop, int startIndex, int endIndex) { for (int i = startIndex; i < endIndex; i++) { final BackStackRecord record = records.get(i); final boolean isPop = isRecordPop.get(i); if (isPop) { record.bumpBackStackNesting(-1); // Only execute the add operations at the end of // all transactions. boolean moveToState = i == (endIndex - 1); record.executePopOps(moveToState); } else { record.bumpBackStackNesting(1); record.executeOps(); } } } /** * Ensure that fragments that are added are moved to at least the CREATED state. * Any newly-added Views are inserted into {@code added} so that the Transaction can be * postponed with {@link Fragment#postponeEnterTransition()}. They will later be made * invisible (by setting their alpha to 0) if they have been removed when postponed. */ private void addAddedFragments(ArraySet<Fragment> added) { if (mCurState < Fragment.CREATED) { return; } // We want to leave the fragment in the started state final int state = Math.min(mCurState, Fragment.STARTED); final int numAdded = mAdded.size(); for (int i = 0; i < numAdded; i++) { Fragment fragment = mAdded.get(i); if (fragment.mState < state) { moveToState(fragment, state, fragment.getNextAnim(), fragment.getNextTransition(), false); if (fragment.mView != null && !fragment.mHidden && fragment.mIsNewlyAdded) { added.add(fragment); } } } } /** * Starts all postponed transactions regardless of whether they are ready or not. */ private void forcePostponedTransactions() { if (mPostponedTransactions != null) { while (!mPostponedTransactions.isEmpty()) { mPostponedTransactions.remove(0).completeTransaction(); } } } /** * Ends the animations of fragments so that they immediately reach the end state. * This is used prior to saving the state so that the correct state is saved. */ private void endAnimatingAwayFragments() { final int numFragments = mActive == null ? 0 : mActive.size(); for (int i = 0; i < numFragments; i++) { Fragment fragment = mActive.valueAt(i); if (fragment != null) { if (fragment.getAnimatingAway() != null) { // Give up waiting for the animation and just end it. final int stateAfterAnimating = fragment.getStateAfterAnimating(); final View animatingAway = fragment.getAnimatingAway(); Animation animation = animatingAway.getAnimation(); if (animation != null) { animation.cancel(); // force-clear the animation, as Animation#cancel() doesn't work prior to N, // and will instead cause the animation to infinitely loop animatingAway.clearAnimation(); } fragment.setAnimatingAway(null); moveToState(fragment, stateAfterAnimating, 0, 0, false); } else if (fragment.getAnimator() != null) { fragment.getAnimator().end(); } } } } /** * Adds all records in the pending actions to records and whether they are add or pop * operations to isPop. After executing, the pending actions will be empty. * * @param records All pending actions will generate BackStackRecords added to this. * This contains the transactions, in order, to execute. * @param isPop All pending actions will generate booleans to add to this. This contains * an entry for each entry in records to indicate whether or not it is a * pop action. */ private boolean generateOpsForPendingActions(ArrayList<BackStackRecord> records, ArrayList<Boolean> isPop) { boolean didSomething = false; synchronized (this) { if (mPendingActions == null || mPendingActions.size() == 0) { return false; } final int numActions = mPendingActions.size(); for (int i = 0; i < numActions; i++) { didSomething |= mPendingActions.get(i).generateOps(records, isPop); } mPendingActions.clear(); mHost.getHandler().removeCallbacks(mExecCommit); } return didSomething; } void doPendingDeferredStart() { if (mHavePendingDeferredStart) { mHavePendingDeferredStart = false; startPendingDeferredFragments(); } } void reportBackStackChanged() { if (mBackStackChangeListeners != null) { for (int i=0; i<mBackStackChangeListeners.size(); i++) { mBackStackChangeListeners.get(i).onBackStackChanged(); } } } void addBackStackState(BackStackRecord state) { if (mBackStack == null) { mBackStack = new ArrayList<BackStackRecord>(); } mBackStack.add(state); } @SuppressWarnings("unused") boolean popBackStackState(ArrayList<BackStackRecord> records, ArrayList<Boolean> isRecordPop, String name, int id, int flags) { if (mBackStack == null) { return false; } if (name == null && id < 0 && (flags & POP_BACK_STACK_INCLUSIVE) == 0) { int last = mBackStack.size() - 1; if (last < 0) { return false; } records.add(mBackStack.remove(last)); isRecordPop.add(true); } else { int index = -1; if (name != null || id >= 0) { // If a name or ID is specified, look for that place in // the stack. index = mBackStack.size()-1; while (index >= 0) { BackStackRecord bss = mBackStack.get(index); if (name != null && name.equals(bss.getName())) { break; } if (id >= 0 && id == bss.mIndex) { break; } index--; } if (index < 0) { return false; } if ((flags&POP_BACK_STACK_INCLUSIVE) != 0) { index--; // Consume all following entries that match. while (index >= 0) { BackStackRecord bss = mBackStack.get(index); if ((name != null && name.equals(bss.getName())) || (id >= 0 && id == bss.mIndex)) { index--; continue; } break; } } } if (index == mBackStack.size()-1) { return false; } for (int i = mBackStack.size() - 1; i > index; i--) { records.add(mBackStack.remove(i)); isRecordPop.add(true); } } return true; } FragmentManagerNonConfig retainNonConfig() { setRetaining(mSavedNonConfig); return mSavedNonConfig; } /** * Recurse the FragmentManagerNonConfig fragments and set the mRetaining to true. This * was previously done while saving the non-config state, but that has been moved to * {@link #saveNonConfig()} called from {@link #saveAllState()}. If mRetaining is set too * early, the fragment won't be destroyed when the FragmentManager is destroyed. */ private static void setRetaining(FragmentManagerNonConfig nonConfig) { if (nonConfig == null) { return; } List<Fragment> fragments = nonConfig.getFragments(); if (fragments != null) { for (Fragment fragment : fragments) { fragment.mRetaining = true; } } List<FragmentManagerNonConfig> children = nonConfig.getChildNonConfigs(); if (children != null) { for (FragmentManagerNonConfig child : children) { setRetaining(child); } } } void saveNonConfig() { ArrayList<Fragment> fragments = null; ArrayList<FragmentManagerNonConfig> childFragments = null; ArrayList<ViewModelStore> viewModelStores = null; if (mActive != null) { for (int i=0; i<mActive.size(); i++) { Fragment f = mActive.valueAt(i); if (f != null) { if (f.mRetainInstance) { if (fragments == null) { fragments = new ArrayList<Fragment>(); } fragments.add(f); f.mTargetIndex = f.mTarget != null ? f.mTarget.mIndex : -1; if (DEBUG) Log.v(TAG, "retainNonConfig: keeping retained " + f); } FragmentManagerNonConfig child; if (f.mChildFragmentManager != null) { f.mChildFragmentManager.saveNonConfig(); child = f.mChildFragmentManager.mSavedNonConfig; } else { // f.mChildNonConfig may be not null, when the parent fragment is // in the backstack. child = f.mChildNonConfig; } if (childFragments == null && child != null) { childFragments = new ArrayList<>(mActive.size()); for (int j = 0; j < i; j++) { childFragments.add(null); } } if (childFragments != null) { childFragments.add(child); } if (viewModelStores == null && f.mViewModelStore != null) { viewModelStores = new ArrayList<>(mActive.size()); for (int j = 0; j < i; j++) { viewModelStores.add(null); } } if (viewModelStores != null) { viewModelStores.add(f.mViewModelStore); } } } } if (fragments == null && childFragments == null && viewModelStores == null) { mSavedNonConfig = null; } else { mSavedNonConfig = new FragmentManagerNonConfig(fragments, childFragments, viewModelStores); } } void saveFragmentViewState(Fragment f) { if (f.mInnerView == null) { return; } if (mStateArray == null) { mStateArray = new SparseArray<Parcelable>(); } else { mStateArray.clear(); } f.mInnerView.saveHierarchyState(mStateArray); if (mStateArray.size() > 0) { f.mSavedViewState = mStateArray; mStateArray = null; } } Bundle saveFragmentBasicState(Fragment f) { Bundle result = null; if (mStateBundle == null) { mStateBundle = new Bundle(); } f.performSaveInstanceState(mStateBundle); dispatchOnFragmentSaveInstanceState(f, mStateBundle, false); if (!mStateBundle.isEmpty()) { result = mStateBundle; mStateBundle = null; } if (f.mView != null) { saveFragmentViewState(f); } if (f.mSavedViewState != null) { if (result == null) { result = new Bundle(); } result.putSparseParcelableArray( FragmentManagerImpl.VIEW_STATE_TAG, f.mSavedViewState); } if (!f.mUserVisibleHint) { if (result == null) { result = new Bundle(); } // Only add this if it's not the default value result.putBoolean(FragmentManagerImpl.USER_VISIBLE_HINT_TAG, f.mUserVisibleHint); } return result; } Parcelable saveAllState() { // Make sure all pending operations have now been executed to get // our state update-to-date. forcePostponedTransactions(); endAnimatingAwayFragments(); execPendingActions(); mStateSaved = true; mSavedNonConfig = null; if (mActive == null || mActive.size() <= 0) { return null; } // First collect all active fragments. int N = mActive.size(); FragmentState[] active = new FragmentState[N]; boolean haveFragments = false; for (int i=0; i<N; i++) { Fragment f = mActive.valueAt(i); if (f != null) { if (f.mIndex < 0) { throwException(new IllegalStateException( "Failure saving state: active " + f + " has cleared index: " + f.mIndex)); } haveFragments = true; FragmentState fs = new FragmentState(f); active[i] = fs; if (f.mState > Fragment.INITIALIZING && fs.mSavedFragmentState == null) { fs.mSavedFragmentState = saveFragmentBasicState(f); if (f.mTarget != null) { if (f.mTarget.mIndex < 0) { throwException(new IllegalStateException( "Failure saving state: " + f + " has target not in fragment manager: " + f.mTarget)); } if (fs.mSavedFragmentState == null) { fs.mSavedFragmentState = new Bundle(); } putFragment(fs.mSavedFragmentState, FragmentManagerImpl.TARGET_STATE_TAG, f.mTarget); if (f.mTargetRequestCode != 0) { fs.mSavedFragmentState.putInt( FragmentManagerImpl.TARGET_REQUEST_CODE_STATE_TAG, f.mTargetRequestCode); } } } else { fs.mSavedFragmentState = f.mSavedFragmentState; } if (DEBUG) Log.v(TAG, "Saved state of " + f + ": " + fs.mSavedFragmentState); } } if (!haveFragments) { if (DEBUG) Log.v(TAG, "saveAllState: no fragments!"); return null; } int[] added = null; BackStackState[] backStack = null; // Build list of currently added fragments. N = mAdded.size(); if (N > 0) { added = new int[N]; for (int i = 0; i < N; i++) { added[i] = mAdded.get(i).mIndex; if (added[i] < 0) { throwException(new IllegalStateException( "Failure saving state: active " + mAdded.get(i) + " has cleared index: " + added[i])); } if (DEBUG) { Log.v(TAG, "saveAllState: adding fragment #" + i + ": " + mAdded.get(i)); } } } // Now save back stack. if (mBackStack != null) { N = mBackStack.size(); if (N > 0) { backStack = new BackStackState[N]; for (int i=0; i<N; i++) { backStack[i] = new BackStackState(mBackStack.get(i)); if (DEBUG) Log.v(TAG, "saveAllState: adding back stack #" + i + ": " + mBackStack.get(i)); } } } FragmentManagerState fms = new FragmentManagerState(); fms.mActive = active; fms.mAdded = added; fms.mBackStack = backStack; if (mPrimaryNav != null) { fms.mPrimaryNavActiveIndex = mPrimaryNav.mIndex; } fms.mNextFragmentIndex = mNextFragmentIndex; saveNonConfig(); return fms; } void restoreAllState(Parcelable state, FragmentManagerNonConfig nonConfig) { // If there is no saved state at all, then there can not be // any nonConfig fragments either, so that is that. if (state == null) return; FragmentManagerState fms = (FragmentManagerState)state; if (fms.mActive == null) return; List<FragmentManagerNonConfig> childNonConfigs = null; List<ViewModelStore> viewModelStores = null; // First re-attach any non-config instances we are retaining back // to their saved state, so we don't try to instantiate them again. if (nonConfig != null) { List<Fragment> nonConfigFragments = nonConfig.getFragments(); childNonConfigs = nonConfig.getChildNonConfigs(); viewModelStores = nonConfig.getViewModelStores(); final int count = nonConfigFragments != null ? nonConfigFragments.size() : 0; for (int i = 0; i < count; i++) { Fragment f = nonConfigFragments.get(i); if (DEBUG) Log.v(TAG, "restoreAllState: re-attaching retained " + f); int index = 0; // index into fms.mActive while (index < fms.mActive.length && fms.mActive[index].mIndex != f.mIndex) { index++; } if (index == fms.mActive.length) { throwException(new IllegalStateException("Could not find active fragment " + "with index " + f.mIndex)); } FragmentState fs = fms.mActive[index]; fs.mInstance = f; f.mSavedViewState = null; f.mBackStackNesting = 0; f.mInLayout = false; f.mAdded = false; f.mTarget = null; if (fs.mSavedFragmentState != null) { fs.mSavedFragmentState.setClassLoader(mHost.getContext().getClassLoader()); f.mSavedViewState = fs.mSavedFragmentState.getSparseParcelableArray( FragmentManagerImpl.VIEW_STATE_TAG); f.mSavedFragmentState = fs.mSavedFragmentState; } } } // Build the full list of active fragments, instantiating them from // their saved state. mActive = new SparseArray<>(fms.mActive.length); for (int i=0; i<fms.mActive.length; i++) { FragmentState fs = fms.mActive[i]; if (fs != null) { FragmentManagerNonConfig childNonConfig = null; if (childNonConfigs != null && i < childNonConfigs.size()) { childNonConfig = childNonConfigs.get(i); } ViewModelStore viewModelStore = null; if (viewModelStores != null && i < viewModelStores.size()) { viewModelStore = viewModelStores.get(i); } Fragment f = fs.instantiate(mHost, mContainer, mParent, childNonConfig, viewModelStore); if (DEBUG) Log.v(TAG, "restoreAllState: active #" + i + ": " + f); mActive.put(f.mIndex, f); // Now that the fragment is instantiated (or came from being // retained above), clear mInstance in case we end up re-restoring // from this FragmentState again. fs.mInstance = null; } } // Update the target of all retained fragments. if (nonConfig != null) { List<Fragment> nonConfigFragments = nonConfig.getFragments(); final int count = nonConfigFragments != null ? nonConfigFragments.size() : 0; for (int i = 0; i < count; i++) { Fragment f = nonConfigFragments.get(i); if (f.mTargetIndex >= 0) { f.mTarget = mActive.get(f.mTargetIndex); if (f.mTarget == null) { Log.w(TAG, "Re-attaching retained fragment " + f + " target no longer exists: " + f.mTargetIndex); } } } } // Build the list of currently added fragments. mAdded.clear(); if (fms.mAdded != null) { for (int i=0; i<fms.mAdded.length; i++) { Fragment f = mActive.get(fms.mAdded[i]); if (f == null) { throwException(new IllegalStateException( "No instantiated fragment for index #" + fms.mAdded[i])); } f.mAdded = true; if (DEBUG) Log.v(TAG, "restoreAllState: added #" + i + ": " + f); if (mAdded.contains(f)) { throw new IllegalStateException("Already added!"); } synchronized (mAdded) { mAdded.add(f); } } } // Build the back stack. if (fms.mBackStack != null) { mBackStack = new ArrayList<BackStackRecord>(fms.mBackStack.length); for (int i=0; i<fms.mBackStack.length; i++) { BackStackRecord bse = fms.mBackStack[i].instantiate(this); if (DEBUG) { Log.v(TAG, "restoreAllState: back stack #" + i + " (index " + bse.mIndex + "): " + bse); LogWriter logw = new LogWriter(TAG); PrintWriter pw = new PrintWriter(logw); bse.dump(" ", pw, false); pw.close(); } mBackStack.add(bse); if (bse.mIndex >= 0) { setBackStackIndex(bse.mIndex, bse); } } } else { mBackStack = null; } if (fms.mPrimaryNavActiveIndex >= 0) { mPrimaryNav = mActive.get(fms.mPrimaryNavActiveIndex); } this.mNextFragmentIndex = fms.mNextFragmentIndex; } /** * To prevent list modification errors, mActive sets values to null instead of * removing them when the Fragment becomes inactive. This cleans up the list at the * end of executing the transactions. */ private void burpActive() { if (mActive != null) { for (int i = mActive.size() - 1; i >= 0; i--) { if (mActive.valueAt(i) == null) { mActive.delete(mActive.keyAt(i)); } } } } public void attachController(FragmentHostCallback host, FragmentContainer container, Fragment parent) { if (mHost != null) throw new IllegalStateException("Already attached"); mHost = host; mContainer = container; mParent = parent; } public void noteStateNotSaved() { mSavedNonConfig = null; mStateSaved = false; mStopped = false; final int addedCount = mAdded.size(); for (int i = 0; i < addedCount; i++) { Fragment fragment = mAdded.get(i); if (fragment != null) { fragment.noteStateNotSaved(); } } } public void dispatchCreate() { mStateSaved = false; mStopped = false; dispatchStateChange(Fragment.CREATED); } public void dispatchActivityCreated() { mStateSaved = false; mStopped = false; dispatchStateChange(Fragment.ACTIVITY_CREATED); } public void dispatchStart() { mStateSaved = false; mStopped = false; dispatchStateChange(Fragment.STARTED); } public void dispatchResume() { mStateSaved = false; mStopped = false; dispatchStateChange(Fragment.RESUMED); } public void dispatchPause() { dispatchStateChange(Fragment.STARTED); } public void dispatchStop() { mStopped = true; dispatchStateChange(Fragment.ACTIVITY_CREATED); } public void dispatchDestroyView() { dispatchStateChange(Fragment.CREATED); } public void dispatchDestroy() { mDestroyed = true; execPendingActions(); dispatchStateChange(Fragment.INITIALIZING); mHost = null; mContainer = null; mParent = null; } private void dispatchStateChange(int nextState) { try { mExecutingActions = true; moveToState(nextState, false); } finally { mExecutingActions = false; } execPendingActions(); } public void dispatchMultiWindowModeChanged(boolean isInMultiWindowMode) { for (int i = mAdded.size() - 1; i >= 0; --i) { final Fragment f = mAdded.get(i); if (f != null) { f.performMultiWindowModeChanged(isInMultiWindowMode); } } } public void dispatchPictureInPictureModeChanged(boolean isInPictureInPictureMode) { for (int i = mAdded.size() - 1; i >= 0; --i) { final Fragment f = mAdded.get(i); if (f != null) { f.performPictureInPictureModeChanged(isInPictureInPictureMode); } } } public void dispatchConfigurationChanged(Configuration newConfig) { for (int i = 0; i < mAdded.size(); i++) { Fragment f = mAdded.get(i); if (f != null) { f.performConfigurationChanged(newConfig); } } } public void dispatchLowMemory() { for (int i = 0; i < mAdded.size(); i++) { Fragment f = mAdded.get(i); if (f != null) { f.performLowMemory(); } } } public boolean dispatchCreateOptionsMenu(Menu menu, MenuInflater inflater) { if (mCurState < Fragment.CREATED) { return false; } boolean show = false; ArrayList<Fragment> newMenus = null; for (int i = 0; i < mAdded.size(); i++) { Fragment f = mAdded.get(i); if (f != null) { if (f.performCreateOptionsMenu(menu, inflater)) { show = true; if (newMenus == null) { newMenus = new ArrayList<Fragment>(); } newMenus.add(f); } } } if (mCreatedMenus != null) { for (int i=0; i<mCreatedMenus.size(); i++) { Fragment f = mCreatedMenus.get(i); if (newMenus == null || !newMenus.contains(f)) { f.onDestroyOptionsMenu(); } } } mCreatedMenus = newMenus; return show; } public boolean dispatchPrepareOptionsMenu(Menu menu) { if (mCurState < Fragment.CREATED) { return false; } boolean show = false; for (int i = 0; i < mAdded.size(); i++) { Fragment f = mAdded.get(i); if (f != null) { if (f.performPrepareOptionsMenu(menu)) { show = true; } } } return show; } public boolean dispatchOptionsItemSelected(MenuItem item) { if (mCurState < Fragment.CREATED) { return false; } for (int i = 0; i < mAdded.size(); i++) { Fragment f = mAdded.get(i); if (f != null) { if (f.performOptionsItemSelected(item)) { return true; } } } return false; } public boolean dispatchContextItemSelected(MenuItem item) { if (mCurState < Fragment.CREATED) { return false; } for (int i = 0; i < mAdded.size(); i++) { Fragment f = mAdded.get(i); if (f != null) { if (f.performContextItemSelected(item)) { return true; } } } return false; } public void dispatchOptionsMenuClosed(Menu menu) { if (mCurState < Fragment.CREATED) { return; } for (int i = 0; i < mAdded.size(); i++) { Fragment f = mAdded.get(i); if (f != null) { f.performOptionsMenuClosed(menu); } } } @SuppressWarnings("ReferenceEquality") public void setPrimaryNavigationFragment(Fragment f) { if (f != null && (mActive.get(f.mIndex) != f || (f.mHost != null && f.getFragmentManager() != this))) { throw new IllegalArgumentException("Fragment " + f + " is not an active fragment of FragmentManager " + this); } mPrimaryNav = f; } @Override @Nullable public Fragment getPrimaryNavigationFragment() { return mPrimaryNav; } @Override public void registerFragmentLifecycleCallbacks(FragmentLifecycleCallbacks cb, boolean recursive) { mLifecycleCallbacks.add(new FragmentLifecycleCallbacksHolder(cb, recursive)); } @Override public void unregisterFragmentLifecycleCallbacks(FragmentLifecycleCallbacks cb) { synchronized (mLifecycleCallbacks) { for (int i = 0, N = mLifecycleCallbacks.size(); i < N; i++) { if (mLifecycleCallbacks.get(i).mCallback == cb) { mLifecycleCallbacks.remove(i); break; } } } } void dispatchOnFragmentPreAttached(@NonNull Fragment f, @NonNull Context context, boolean onlyRecursive) { if (mParent != null) { FragmentManager parentManager = mParent.getFragmentManager(); if (parentManager instanceof FragmentManagerImpl) { ((FragmentManagerImpl) parentManager) .dispatchOnFragmentPreAttached(f, context, true); } } for (FragmentLifecycleCallbacksHolder holder : mLifecycleCallbacks) { if (!onlyRecursive || holder.mRecursive) { holder.mCallback.onFragmentPreAttached(this, f, context); } } } void dispatchOnFragmentAttached(@NonNull Fragment f, @NonNull Context context, boolean onlyRecursive) { if (mParent != null) { FragmentManager parentManager = mParent.getFragmentManager(); if (parentManager instanceof FragmentManagerImpl) { ((FragmentManagerImpl) parentManager) .dispatchOnFragmentAttached(f, context, true); } } for (FragmentLifecycleCallbacksHolder holder : mLifecycleCallbacks) { if (!onlyRecursive || holder.mRecursive) { holder.mCallback.onFragmentAttached(this, f, context); } } } void dispatchOnFragmentPreCreated(@NonNull Fragment f, @Nullable Bundle savedInstanceState, boolean onlyRecursive) { if (mParent != null) { FragmentManager parentManager = mParent.getFragmentManager(); if (parentManager instanceof FragmentManagerImpl) { ((FragmentManagerImpl) parentManager) .dispatchOnFragmentPreCreated(f, savedInstanceState, true); } } for (FragmentLifecycleCallbacksHolder holder : mLifecycleCallbacks) { if (!onlyRecursive || holder.mRecursive) { holder.mCallback.onFragmentPreCreated(this, f, savedInstanceState); } } } void dispatchOnFragmentCreated(@NonNull Fragment f, @Nullable Bundle savedInstanceState, boolean onlyRecursive) { if (mParent != null) { FragmentManager parentManager = mParent.getFragmentManager(); if (parentManager instanceof FragmentManagerImpl) { ((FragmentManagerImpl) parentManager) .dispatchOnFragmentCreated(f, savedInstanceState, true); } } for (FragmentLifecycleCallbacksHolder holder : mLifecycleCallbacks) { if (!onlyRecursive || holder.mRecursive) { holder.mCallback.onFragmentCreated(this, f, savedInstanceState); } } } void dispatchOnFragmentActivityCreated(@NonNull Fragment f, @Nullable Bundle savedInstanceState, boolean onlyRecursive) { if (mParent != null) { FragmentManager parentManager = mParent.getFragmentManager(); if (parentManager instanceof FragmentManagerImpl) { ((FragmentManagerImpl) parentManager) .dispatchOnFragmentActivityCreated(f, savedInstanceState, true); } } for (FragmentLifecycleCallbacksHolder holder : mLifecycleCallbacks) { if (!onlyRecursive || holder.mRecursive) { holder.mCallback.onFragmentActivityCreated(this, f, savedInstanceState); } } } void dispatchOnFragmentViewCreated(@NonNull Fragment f, @NonNull View v, @Nullable Bundle savedInstanceState, boolean onlyRecursive) { if (mParent != null) { FragmentManager parentManager = mParent.getFragmentManager(); if (parentManager instanceof FragmentManagerImpl) { ((FragmentManagerImpl) parentManager) .dispatchOnFragmentViewCreated(f, v, savedInstanceState, true); } } for (FragmentLifecycleCallbacksHolder holder : mLifecycleCallbacks) { if (!onlyRecursive || holder.mRecursive) { holder.mCallback.onFragmentViewCreated(this, f, v, savedInstanceState); } } } void dispatchOnFragmentStarted(@NonNull Fragment f, boolean onlyRecursive) { if (mParent != null) { FragmentManager parentManager = mParent.getFragmentManager(); if (parentManager instanceof FragmentManagerImpl) { ((FragmentManagerImpl) parentManager) .dispatchOnFragmentStarted(f, true); } } for (FragmentLifecycleCallbacksHolder holder : mLifecycleCallbacks) { if (!onlyRecursive || holder.mRecursive) { holder.mCallback.onFragmentStarted(this, f); } } } void dispatchOnFragmentResumed(@NonNull Fragment f, boolean onlyRecursive) { if (mParent != null) { FragmentManager parentManager = mParent.getFragmentManager(); if (parentManager instanceof FragmentManagerImpl) { ((FragmentManagerImpl) parentManager) .dispatchOnFragmentResumed(f, true); } } for (FragmentLifecycleCallbacksHolder holder : mLifecycleCallbacks) { if (!onlyRecursive || holder.mRecursive) { holder.mCallback.onFragmentResumed(this, f); } } } void dispatchOnFragmentPaused(@NonNull Fragment f, boolean onlyRecursive) { if (mParent != null) { FragmentManager parentManager = mParent.getFragmentManager(); if (parentManager instanceof FragmentManagerImpl) { ((FragmentManagerImpl) parentManager) .dispatchOnFragmentPaused(f, true); } } for (FragmentLifecycleCallbacksHolder holder : mLifecycleCallbacks) { if (!onlyRecursive || holder.mRecursive) { holder.mCallback.onFragmentPaused(this, f); } } } void dispatchOnFragmentStopped(@NonNull Fragment f, boolean onlyRecursive) { if (mParent != null) { FragmentManager parentManager = mParent.getFragmentManager(); if (parentManager instanceof FragmentManagerImpl) { ((FragmentManagerImpl) parentManager) .dispatchOnFragmentStopped(f, true); } } for (FragmentLifecycleCallbacksHolder holder : mLifecycleCallbacks) { if (!onlyRecursive || holder.mRecursive) { holder.mCallback.onFragmentStopped(this, f); } } } void dispatchOnFragmentSaveInstanceState(@NonNull Fragment f, @NonNull Bundle outState, boolean onlyRecursive) { if (mParent != null) { FragmentManager parentManager = mParent.getFragmentManager(); if (parentManager instanceof FragmentManagerImpl) { ((FragmentManagerImpl) parentManager) .dispatchOnFragmentSaveInstanceState(f, outState, true); } } for (FragmentLifecycleCallbacksHolder holder : mLifecycleCallbacks) { if (!onlyRecursive || holder.mRecursive) { holder.mCallback.onFragmentSaveInstanceState(this, f, outState); } } } void dispatchOnFragmentViewDestroyed(@NonNull Fragment f, boolean onlyRecursive) { if (mParent != null) { FragmentManager parentManager = mParent.getFragmentManager(); if (parentManager instanceof FragmentManagerImpl) { ((FragmentManagerImpl) parentManager) .dispatchOnFragmentViewDestroyed(f, true); } } for (FragmentLifecycleCallbacksHolder holder : mLifecycleCallbacks) { if (!onlyRecursive || holder.mRecursive) { holder.mCallback.onFragmentViewDestroyed(this, f); } } } void dispatchOnFragmentDestroyed(@NonNull Fragment f, boolean onlyRecursive) { if (mParent != null) { FragmentManager parentManager = mParent.getFragmentManager(); if (parentManager instanceof FragmentManagerImpl) { ((FragmentManagerImpl) parentManager) .dispatchOnFragmentDestroyed(f, true); } } for (FragmentLifecycleCallbacksHolder holder : mLifecycleCallbacks) { if (!onlyRecursive || holder.mRecursive) { holder.mCallback.onFragmentDestroyed(this, f); } } } void dispatchOnFragmentDetached(@NonNull Fragment f, boolean onlyRecursive) { if (mParent != null) { FragmentManager parentManager = mParent.getFragmentManager(); if (parentManager instanceof FragmentManagerImpl) { ((FragmentManagerImpl) parentManager) .dispatchOnFragmentDetached(f, true); } } for (FragmentLifecycleCallbacksHolder holder : mLifecycleCallbacks) { if (!onlyRecursive || holder.mRecursive) { holder.mCallback.onFragmentDetached(this, f); } } } public static int reverseTransit(int transit) { int rev = 0; switch (transit) { case FragmentTransaction.TRANSIT_FRAGMENT_OPEN: rev = FragmentTransaction.TRANSIT_FRAGMENT_CLOSE; break; case FragmentTransaction.TRANSIT_FRAGMENT_CLOSE: rev = FragmentTransaction.TRANSIT_FRAGMENT_OPEN; break; case FragmentTransaction.TRANSIT_FRAGMENT_FADE: rev = FragmentTransaction.TRANSIT_FRAGMENT_FADE; break; } return rev; } public static final int ANIM_STYLE_OPEN_ENTER = 1; public static final int ANIM_STYLE_OPEN_EXIT = 2; public static final int ANIM_STYLE_CLOSE_ENTER = 3; public static final int ANIM_STYLE_CLOSE_EXIT = 4; public static final int ANIM_STYLE_FADE_ENTER = 5; public static final int ANIM_STYLE_FADE_EXIT = 6; public static int transitToStyleIndex(int transit, boolean enter) { int animAttr = -1; switch (transit) { case FragmentTransaction.TRANSIT_FRAGMENT_OPEN: animAttr = enter ? ANIM_STYLE_OPEN_ENTER : ANIM_STYLE_OPEN_EXIT; break; case FragmentTransaction.TRANSIT_FRAGMENT_CLOSE: animAttr = enter ? ANIM_STYLE_CLOSE_ENTER : ANIM_STYLE_CLOSE_EXIT; break; case FragmentTransaction.TRANSIT_FRAGMENT_FADE: animAttr = enter ? ANIM_STYLE_FADE_ENTER : ANIM_STYLE_FADE_EXIT; break; } return animAttr; } @Override public View onCreateView(View parent, String name, Context context, AttributeSet attrs) { if (!"fragment".equals(name)) { return null; } String fname = attrs.getAttributeValue(null, "class"); TypedArray a = context.obtainStyledAttributes(attrs, FragmentTag.Fragment); if (fname == null) { fname = a.getString(FragmentTag.Fragment_name); } int id = a.getResourceId(FragmentTag.Fragment_id, View.NO_ID); String tag = a.getString(FragmentTag.Fragment_tag); a.recycle(); if (!Fragment.isSupportFragmentClass(mHost.getContext(), fname)) { // Invalid support lib fragment; let the device's framework handle it. // This will allow android.app.Fragments to do the right thing. return null; } int containerId = parent != null ? parent.getId() : 0; if (containerId == View.NO_ID && id == View.NO_ID && tag == null) { throw new IllegalArgumentException(attrs.getPositionDescription() + ": Must specify unique android:id, android:tag, or have a parent with an id for " + fname); } // If we restored from a previous state, we may already have // instantiated this fragment from the state and should use // that instance instead of making a new one. Fragment fragment = id != View.NO_ID ? findFragmentById(id) : null; if (fragment == null && tag != null) { fragment = findFragmentByTag(tag); } if (fragment == null && containerId != View.NO_ID) { fragment = findFragmentById(containerId); } if (FragmentManagerImpl.DEBUG) Log.v(TAG, "onCreateView: id=0x" + Integer.toHexString(id) + " fname=" + fname + " existing=" + fragment); if (fragment == null) { fragment = mContainer.instantiate(context, fname, null); fragment.mFromLayout = true; fragment.mFragmentId = id != 0 ? id : containerId; fragment.mContainerId = containerId; fragment.mTag = tag; fragment.mInLayout = true; fragment.mFragmentManager = this; fragment.mHost = mHost; fragment.onInflate(mHost.getContext(), attrs, fragment.mSavedFragmentState); addFragment(fragment, true); } else if (fragment.mInLayout) { // A fragment already exists and it is not one we restored from // previous state. throw new IllegalArgumentException(attrs.getPositionDescription() + ": Duplicate id 0x" + Integer.toHexString(id) + ", tag " + tag + ", or parent id 0x" + Integer.toHexString(containerId) + " with another fragment for " + fname); } else { // This fragment was retained from a previous instance; get it // going now. fragment.mInLayout = true; fragment.mHost = mHost; // If this fragment is newly instantiated (either right now, or // from last saved state), then give it the attributes to // initialize itself. if (!fragment.mRetaining) { fragment.onInflate(mHost.getContext(), attrs, fragment.mSavedFragmentState); } } // If we haven't finished entering the CREATED state ourselves yet, // push the inflated child fragment along. This will ensureInflatedFragmentView // at the right phase of the lifecycle so that we will have mView populated // for compliant fragments below. if (mCurState < Fragment.CREATED && fragment.mFromLayout) { moveToState(fragment, Fragment.CREATED, 0, 0, false); } else { moveToState(fragment); } if (fragment.mView == null) { throw new IllegalStateException("Fragment " + fname + " did not create a view."); } if (id != 0) { fragment.mView.setId(id); } if (fragment.mView.getTag() == null) { fragment.mView.setTag(tag); } return fragment.mView; } @Override public View onCreateView(String name, Context context, AttributeSet attrs) { return onCreateView(null, name, context, attrs); } LayoutInflater.Factory2 getLayoutInflaterFactory() { return this; } static class FragmentTag { public static final int[] Fragment = { 0x01010003, 0x010100d0, 0x010100d1 }; public static final int Fragment_id = 1; public static final int Fragment_name = 0; public static final int Fragment_tag = 2; private FragmentTag() { } } /** * An add or pop transaction to be scheduled for the UI thread. */ interface OpGenerator { /** * Generate transactions to add to {@code records} and whether or not the transaction is * an add or pop to {@code isRecordPop}. * * records and isRecordPop must be added equally so that each transaction in records * matches the boolean for whether or not it is a pop in isRecordPop. * * @param records A list to add transactions to. * @param isRecordPop A list to add whether or not the transactions added to records is * a pop transaction. * @return true if something was added or false otherwise. */ boolean generateOps(ArrayList<BackStackRecord> records, ArrayList<Boolean> isRecordPop); } /** * A pop operation OpGenerator. This will be run on the UI thread and will generate the * transactions that will be popped if anything can be popped. */ private class PopBackStackState implements OpGenerator { final String mName; final int mId; final int mFlags; PopBackStackState(String name, int id, int flags) { mName = name; mId = id; mFlags = flags; } @Override public boolean generateOps(ArrayList<BackStackRecord> records, ArrayList<Boolean> isRecordPop) { if (mPrimaryNav != null // We have a primary nav fragment && mId < 0 // No valid id (since they're local) && mName == null) { // no name to pop to (since they're local) final FragmentManager childManager = mPrimaryNav.peekChildFragmentManager(); if (childManager != null && childManager.popBackStackImmediate()) { // We didn't add any operations for this FragmentManager even though // a child did do work. return false; } } return popBackStackState(records, isRecordPop, mName, mId, mFlags); } } /** * A listener for a postponed transaction. This waits until * {@link Fragment#startPostponedEnterTransition()} is called or a transaction is started * that interacts with this one, based on interactions with the fragment container. */ static class StartEnterTransitionListener implements Fragment.OnStartEnterTransitionListener { final boolean mIsBack; final BackStackRecord mRecord; private int mNumPostponed; StartEnterTransitionListener(BackStackRecord record, boolean isBack) { mIsBack = isBack; mRecord = record; } /** * Called from {@link Fragment#startPostponedEnterTransition()}, this decreases the * number of Fragments that are postponed. This may cause the transaction to schedule * to finish running and run transitions and animations. */ @Override public void onStartEnterTransition() { mNumPostponed--; if (mNumPostponed != 0) { return; } mRecord.mManager.scheduleCommit(); } /** * Called from {@link Fragment# * setOnStartEnterTransitionListener(Fragment.OnStartEnterTransitionListener)}, this * increases the number of fragments that are postponed as part of this transaction. */ @Override public void startListening() { mNumPostponed++; } /** * @return true if there are no more postponed fragments as part of the transaction. */ public boolean isReady() { return mNumPostponed == 0; } /** * Completes the transaction and start the animations and transitions. This may skip * the transitions if this is called before all fragments have called * {@link Fragment#startPostponedEnterTransition()}. */ public void completeTransaction() { final boolean canceled; canceled = mNumPostponed > 0; FragmentManagerImpl manager = mRecord.mManager; final int numAdded = manager.mAdded.size(); for (int i = 0; i < numAdded; i++) { final Fragment fragment = manager.mAdded.get(i); fragment.setOnStartEnterTransitionListener(null); if (canceled && fragment.isPostponed()) { fragment.startPostponedEnterTransition(); } } mRecord.mManager.completeExecute(mRecord, mIsBack, !canceled, true); } /** * Cancels this transaction instead of completing it. That means that the state isn't * changed, so the pop results in no change to the state. */ public void cancelTransaction() { mRecord.mManager.completeExecute(mRecord, mIsBack, false, false); } } /** * Contains either an animator or animation. One of these should be null. */ private static class AnimationOrAnimator { public final Animation animation; public final Animator animator; AnimationOrAnimator(Animation animation) { this.animation = animation; this.animator = null; if (animation == null) { throw new IllegalStateException("Animation cannot be null"); } } AnimationOrAnimator(Animator animator) { this.animation = null; this.animator = animator; if (animator == null) { throw new IllegalStateException("Animator cannot be null"); } } } /** * Wrap an AnimationListener that can be null. This allows us to chain animation listeners. */ private static class AnimationListenerWrapper implements AnimationListener { private final AnimationListener mWrapped; AnimationListenerWrapper(AnimationListener wrapped) { mWrapped = wrapped; } @CallSuper @Override public void onAnimationStart(Animation animation) { if (mWrapped != null) { mWrapped.onAnimationStart(animation); } } @CallSuper @Override public void onAnimationEnd(Animation animation) { if (mWrapped != null) { mWrapped.onAnimationEnd(animation); } } @CallSuper @Override public void onAnimationRepeat(Animation animation) { if (mWrapped != null) { mWrapped.onAnimationRepeat(animation); } } } /** * Reset the layer type to LAYER_TYPE_NONE at the end of an animation. */ private static class AnimateOnHWLayerIfNeededListener extends AnimationListenerWrapper { View mView; AnimateOnHWLayerIfNeededListener(final View v, AnimationListener listener) { super(listener); mView = v; } @Override @CallSuper public void onAnimationEnd(Animation animation) { // If we're attached to a window, assume we're in the normal performTraversals // drawing path for Animations running. It's not safe to change the layer type // during drawing, so post it to the View to run later. If we're not attached // or we're running on N and above, post it to the view. If we're not on N and // not attached, do it right now since existing platform versions don't run the // hwui renderer for detached views off the UI thread making changing layer type // safe, but posting may not be. // Prior to N posting to a detached view from a non-Looper thread could cause // leaks, since the thread-local run queue on a non-Looper thread would never // be flushed. if (ViewCompat.isAttachedToWindow(mView) || Build.VERSION.SDK_INT >= 24) { mView.post(new Runnable() { @Override public void run() { mView.setLayerType(View.LAYER_TYPE_NONE, null); } }); } else { mView.setLayerType(View.LAYER_TYPE_NONE, null); } super.onAnimationEnd(animation); } } /** * Set the layer type to LAYER_TYPE_HARDWARE while an animator is running. */ private static class AnimatorOnHWLayerIfNeededListener extends AnimatorListenerAdapter { View mView; AnimatorOnHWLayerIfNeededListener(final View v) { mView = v; } @Override public void onAnimationStart(Animator animation) { mView.setLayerType(View.LAYER_TYPE_HARDWARE, null); } @Override public void onAnimationEnd(Animator animation) { mView.setLayerType(View.LAYER_TYPE_NONE, null); animation.removeListener(this); } } /** * We must call endViewTransition() before the animation ends or else the parent doesn't * get nulled out. We use both startViewTransition() and startAnimation() to solve a problem * with Views remaining in the hierarchy as disappearing children after the view has been * removed in some edge cases. */ private static class EndViewTransitionAnimator extends AnimationSet implements Runnable { private final ViewGroup mParent; private final View mChild; private boolean mEnded; private boolean mTransitionEnded; private boolean mAnimating = true; EndViewTransitionAnimator(@NonNull Animation animation, @NonNull ViewGroup parent, @NonNull View child) { super(false); mParent = parent; mChild = child; addAnimation(animation); // We must call endViewTransition() even if the animation was never run or it // is interrupted in a way that can't be detected easily (app put in background) mParent.post(this); } @Override public boolean getTransformation(long currentTime, Transformation t) { mAnimating = true; if (mEnded) { return !mTransitionEnded; } boolean more = super.getTransformation(currentTime, t); if (!more) { mEnded = true; OneShotPreDrawListener.add(mParent, this); } return true; } @Override public boolean getTransformation(long currentTime, Transformation outTransformation, float scale) { mAnimating = true; if (mEnded) { return !mTransitionEnded; } boolean more = super.getTransformation(currentTime, outTransformation, scale); if (!more) { mEnded = true; OneShotPreDrawListener.add(mParent, this); } return true; } @Override public void run() { if (!mEnded && mAnimating) { mAnimating = false; // Called while animating, so we'll check again on next cycle mParent.post(this); } else { mParent.endViewTransition(mChild); mTransitionEnded = true; } } } }
Fix Fragment.popBackStack docs Test: N/A Change-Id: I88c1ba646f21b8f45d8cd09c4b35c621b197f92c
fragment/src/main/java/androidx/fragment/app/FragmentManager.java
Fix Fragment.popBackStack docs
Java
apache-2.0
57df7a713a7d7643b2190ed7dcdab1663b731be5
0
emccode/ecs-cf-service-broker,codedellemc/ecs-cf-service-broker,spiegela/ecs-cf-service-broker
package com.emc.ecs.cloudfoundry.broker.service; import com.emc.ecs.cloudfoundry.broker.EcsManagementClientException; import com.emc.ecs.cloudfoundry.broker.EcsManagementResourceNotFoundException; import com.emc.ecs.cloudfoundry.broker.config.CatalogConfig; import com.emc.ecs.cloudfoundry.broker.model.PlanProxy; import com.emc.ecs.cloudfoundry.broker.model.ServiceDefinitionProxy; import com.emc.ecs.cloudfoundry.broker.repository.ServiceInstanceBinding; import com.emc.ecs.cloudfoundry.broker.repository.ServiceInstanceBindingRepository; import com.emc.ecs.management.sdk.model.UserSecretKey; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.servicebroker.exception.ServiceBrokerException; import org.springframework.cloud.servicebroker.exception.ServiceInstanceBindingExistsException; import org.springframework.cloud.servicebroker.model.*; import org.springframework.cloud.servicebroker.service.ServiceInstanceBindingService; import org.springframework.stereotype.Service; import javax.xml.bind.JAXBException; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import java.util.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Service public class EcsServiceInstanceBindingService implements ServiceInstanceBindingService { private static final String NO_SERVICE_MATCHING_TYPE = "No service matching type: "; private static final String SERVICE_TYPE = "service-type"; private static final String NAMESPACE = "namespace"; private static final String BUCKET = "bucket"; private static final String VOLUME_DRIVER = "nfsv3driver"; private static final String DEFAULT_MOUNT = "/var/vcap/data"; public static final String MOUNT = "mount"; static final Logger LOG = LoggerFactory.getLogger(EcsServiceInstanceBindingService.class); @Autowired private EcsService ecs; @Autowired private CatalogConfig catalog; @Autowired private ServiceInstanceBindingRepository repository; public EcsServiceInstanceBindingService() throws EcsManagementClientException, EcsManagementResourceNotFoundException, URISyntaxException { super(); } @Override public CreateServiceInstanceBindingResponse createServiceInstanceBinding( CreateServiceInstanceBindingRequest request) throws ServiceInstanceBindingExistsException, ServiceBrokerException { LOG.error("Creating service instance binding response"); String instanceId = request.getServiceInstanceId(); String bindingId = request.getBindingId(); String serviceDefinitionId = request.getServiceDefinitionId(); ServiceInstanceBinding binding = new ServiceInstanceBinding(request); Map<String, Object> credentials = new HashMap<>(); Map<String, Object> parameters = request.getParameters(); credentials.put("accessKey", ecs.prefix(bindingId)); try { if (ecs.userExists(bindingId)) throw new ServiceInstanceBindingExistsException(instanceId, bindingId); binding.setBindingId(bindingId); ServiceDefinitionProxy service = ecs .lookupServiceDefinition(serviceDefinitionId); PlanProxy plan = service.findPlan(request.getPlanId()); String serviceType = (String) service.getServiceSettings() .get(SERVICE_TYPE); UserSecretKey userSecret; CreateServiceInstanceAppBindingResponse resp = new CreateServiceInstanceAppBindingResponse(); String s3Url; String endpoint; if (NAMESPACE.equals(serviceType)) { userSecret = ecs.createUser(bindingId, instanceId); LOG.info("Created user with binding id: " + bindingId + ", instanceId: " + instanceId); endpoint = ecs.getNamespaceURL(ecs.prefix(instanceId), service, plan, Optional.ofNullable(parameters)); String userInfo = bindingId + ":" + userSecret.getSecretKey(); URL baseUrl = new URL(endpoint); s3Url = new StringBuilder(baseUrl.getProtocol()) .append("://") .append(ecs.prefix(userInfo)) .append("@") .append(baseUrl.getHost()) .append(":") .append(baseUrl.getPort()) .toString(); } else if (BUCKET.equals(serviceType)) { endpoint = ecs.getObjectEndpoint(); URL baseUrl = new URL(endpoint); userSecret = ecs.createUser(bindingId); LOG.info("Created user with binding id: " + bindingId); List<String> permissions = null; Boolean hasMounts = ecs.getBucketFileEnabled(instanceId); String export = ""; if (parameters != null) { permissions = (List<String>) parameters.get("permissions"); export = (String) parameters.get("export"); } if (permissions != null) { ecs.addUserToBucket(instanceId, bindingId, permissions); LOG.info("Added user to bucket"); } else { ecs.addUserToBucket(instanceId, bindingId); LOG.info("Added user to bucket"); } if (hasMounts) { int unixUid = (int)(2000 + System.currentTimeMillis() % 8000); while (true) { try { ecs.createUserMap(bindingId, unixUid); LOG.info("Created user map. Binding id: " + bindingId + ", unixUid: " + unixUid); break; } catch (EcsManagementClientException e) { if (e.getMessage().contains("Bad request body (1013)")) { unixUid++; } else { throw e; } } } String host = ecs.getNfsMountHost(); if (host == null || host.isEmpty()) { host = baseUrl.getHost(); } String volumeGUID = UUID.randomUUID().toString(); LOG.info("Adding export: " + export + " to bucket: " + instanceId); String absoluteExportPath = ecs.addExportToBucket(instanceId, export); LOG.info("export added."); Map<String, Object> opts = new HashMap<>(); String nfsUrl = new StringBuilder("nfs://") .append(host) .append(absoluteExportPath) .toString(); opts.put("source", nfsUrl); opts.put("uid", String.valueOf(unixUid)); List<VolumeMount> mounts = new ArrayList<>(); mounts.add(new VolumeMount(VOLUME_DRIVER, getContainerDir(parameters, bindingId), VolumeMount.Mode.READ_WRITE, VolumeMount.DeviceType.SHARED, new SharedVolumeDevice(volumeGUID, opts))); binding.setVolumeMounts(mounts); resp = resp.withVolumeMounts(mounts); } credentials.put("bucket", ecs.prefix(instanceId)); String userInfo = bindingId + ":" + userSecret.getSecretKey(); s3Url = new StringBuilder(baseUrl.getProtocol()) .append("://") .append(ecs.prefix(userInfo)) .append("@") .append(baseUrl.getHost()) .append(":") .append(baseUrl.getPort()) .append("/") .append(ecs.prefix(instanceId)) .toString(); } else { throw new EcsManagementClientException( NO_SERVICE_MATCHING_TYPE + serviceType); } credentials.put("s3Url", s3Url); credentials.put("endpoint", endpoint); credentials.put("secretKey", userSecret.getSecretKey()); binding.setCredentials(credentials); repository.save(binding); return resp.withCredentials(credentials); } catch (IOException | JAXBException | EcsManagementClientException e) { throw new ServiceBrokerException(e); } } protected String getContainerDir(Map<String, Object> parameters, String bindingId) { if (parameters != null) { Object o = parameters.get(MOUNT); if (o != null && o instanceof String) { String mount = (String) o; if (!mount.isEmpty()) { LOG.info("mount parameter found returning: " + mount); return mount; } } } LOG.info("using default mount"); return DEFAULT_MOUNT + File.separator + bindingId; } @Override public void deleteServiceInstanceBinding( DeleteServiceInstanceBindingRequest request) throws ServiceBrokerException { String bindingId = request.getBindingId(); String instanceId = request.getServiceInstanceId(); String serviceDefinitionId = request.getServiceDefinitionId(); ServiceDefinitionProxy service = catalog .findServiceDefinition(serviceDefinitionId); String serviceType = (String) service.getServiceSettings() .get(SERVICE_TYPE); try { if (BUCKET.equals(serviceType)) ecs.removeUserFromBucket(instanceId, bindingId); ecs.deleteUser(bindingId); LOG.error("looking up binding: " + bindingId); ServiceInstanceBinding binding = repository.find(bindingId); if (binding == null) { // TODO -- is this gonna blow up? repository.delete(bindingId); return; } LOG.error("binding found: " + bindingId); List<VolumeMount> volumes = binding.getVolumeMounts(); if (volumes == null || volumes.size() == 0) { repository.delete(bindingId); return; } Map<String, Object> mountConfig = ((SharedVolumeDevice) volumes.get(0).getDevice()).getMountConfig(); String unixId = (String) mountConfig.get("uid"); try { LOG.error("Deleting user map of instance Id and Binding Id " + instanceId + " " + bindingId); ecs.deleteUserMap(bindingId, unixId); } catch (EcsManagementClientException e) { LOG.error("Error deleting user map: " + e.getMessage()); } repository.delete(bindingId); } catch (Exception e) { LOG.error("Error deleting binding: " + e); throw new ServiceBrokerException(e); } } }
src/main/java/com/emc/ecs/cloudfoundry/broker/service/EcsServiceInstanceBindingService.java
package com.emc.ecs.cloudfoundry.broker.service; import com.emc.ecs.cloudfoundry.broker.EcsManagementClientException; import com.emc.ecs.cloudfoundry.broker.EcsManagementResourceNotFoundException; import com.emc.ecs.cloudfoundry.broker.config.CatalogConfig; import com.emc.ecs.cloudfoundry.broker.model.PlanProxy; import com.emc.ecs.cloudfoundry.broker.model.ServiceDefinitionProxy; import com.emc.ecs.cloudfoundry.broker.repository.ServiceInstanceBinding; import com.emc.ecs.cloudfoundry.broker.repository.ServiceInstanceBindingRepository; import com.emc.ecs.management.sdk.model.UserSecretKey; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.servicebroker.exception.ServiceBrokerException; import org.springframework.cloud.servicebroker.exception.ServiceInstanceBindingExistsException; import org.springframework.cloud.servicebroker.model.*; import org.springframework.cloud.servicebroker.service.ServiceInstanceBindingService; import org.springframework.stereotype.Service; import javax.xml.bind.JAXBException; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import java.util.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Service public class EcsServiceInstanceBindingService implements ServiceInstanceBindingService { private static final String NO_SERVICE_MATCHING_TYPE = "No service matching type: "; private static final String SERVICE_TYPE = "service-type"; private static final String NAMESPACE = "namespace"; private static final String BUCKET = "bucket"; private static final String VOLUME_DRIVER = "nfsv3driver"; private static final String DEFAULT_MOUNT = "/var/vcap/data"; public static final String MOUNT = "mount"; static final Logger LOG = LoggerFactory.getLogger(EcsServiceInstanceBindingService.class); @Autowired private EcsService ecs; @Autowired private CatalogConfig catalog; @Autowired private ServiceInstanceBindingRepository repository; public EcsServiceInstanceBindingService() throws EcsManagementClientException, EcsManagementResourceNotFoundException, URISyntaxException { super(); } @Override public CreateServiceInstanceBindingResponse createServiceInstanceBinding( CreateServiceInstanceBindingRequest request) throws ServiceInstanceBindingExistsException, ServiceBrokerException { LOG.error("Creating service instance binding response"); String instanceId = request.getServiceInstanceId(); String bindingId = request.getBindingId(); String serviceDefinitionId = request.getServiceDefinitionId(); ServiceInstanceBinding binding = new ServiceInstanceBinding(request); Map<String, Object> credentials = new HashMap<>(); Map<String, Object> parameters = request.getParameters(); credentials.put("accessKey", ecs.prefix(bindingId)); try { if (ecs.userExists(bindingId)) throw new ServiceInstanceBindingExistsException(instanceId, bindingId); binding.setBindingId(bindingId); ServiceDefinitionProxy service = ecs .lookupServiceDefinition(serviceDefinitionId); PlanProxy plan = service.findPlan(request.getPlanId()); String serviceType = (String) service.getServiceSettings() .get(SERVICE_TYPE); UserSecretKey userSecret; CreateServiceInstanceAppBindingResponse resp = new CreateServiceInstanceAppBindingResponse(); String s3Url; String endpoint; if (NAMESPACE.equals(serviceType)) { userSecret = ecs.createUser(bindingId, instanceId); LOG.info("Created user with binding id: " + bindingId + ", instanceId: " + instanceId); endpoint = ecs.getNamespaceURL(ecs.prefix(instanceId), service, plan, Optional.ofNullable(parameters)); String userInfo = bindingId + ":" + userSecret.getSecretKey(); URL baseUrl = new URL(endpoint); s3Url = new StringBuilder(baseUrl.getProtocol()) .append("://") .append(ecs.prefix(userInfo)) .append("@") .append(baseUrl.getHost()) .append(":") .append(baseUrl.getPort()) .toString(); } else if (BUCKET.equals(serviceType)) { endpoint = ecs.getObjectEndpoint(); URL baseUrl = new URL(endpoint); userSecret = ecs.createUser(bindingId); LOG.info("Created user with binding id: " + bindingId); List<String> permissions = null; Boolean hasMounts = ecs.getBucketFileEnabled(instanceId); String export = ""; if (parameters != null) { permissions = (List<String>) parameters.get("permissions"); export = (String) parameters.get("export"); } if (permissions != null) { ecs.addUserToBucket(instanceId, bindingId, permissions); LOG.info("Added user to bucket"); } else { ecs.addUserToBucket(instanceId, bindingId); LOG.info("Added user to bucket"); } if (hasMounts) { int unixUid = (int)(2000 + System.currentTimeMillis() % 8000); while (true) { try { ecs.createUserMap(bindingId, unixUid); LOG.info("Created user map binding id: " + bindingId + ", unixUid: " + unixUid); break; } catch (EcsManagementClientException e) { if (e.getMessage().contains("Bad request body (1013)")) { unixUid++; } else { throw e; } } } String host = ecs.getNfsMountHost(); if (host == null || host.isEmpty()) { host = baseUrl.getHost(); } String volumeGUID = UUID.randomUUID().toString(); LOG.info("Adding export: " + export + " to bucket: " + instanceId); String absoluteExportPath = ecs.addExportToBucket(instanceId, export); LOG.info("export added."); Map<String, Object> opts = new HashMap<>(); String nfsUrl = new StringBuilder("nfs://") .append(host) .append(absoluteExportPath) .toString(); opts.put("source", nfsUrl); opts.put("uid", String.valueOf(unixUid)); List<VolumeMount> mounts = new ArrayList<>(); mounts.add(new VolumeMount(VOLUME_DRIVER, getContainerDir(parameters, bindingId), VolumeMount.Mode.READ_WRITE, VolumeMount.DeviceType.SHARED, new SharedVolumeDevice(volumeGUID, opts))); binding.setVolumeMounts(mounts); resp = resp.withVolumeMounts(mounts); } credentials.put("bucket", ecs.prefix(instanceId)); String userInfo = bindingId + ":" + userSecret.getSecretKey(); s3Url = new StringBuilder(baseUrl.getProtocol()) .append("://") .append(ecs.prefix(userInfo)) .append("@") .append(baseUrl.getHost()) .append(":") .append(baseUrl.getPort()) .append("/") .append(ecs.prefix(instanceId)) .toString(); } else { throw new EcsManagementClientException( NO_SERVICE_MATCHING_TYPE + serviceType); } credentials.put("s3Url", s3Url); credentials.put("endpoint", endpoint); credentials.put("secretKey", userSecret.getSecretKey()); binding.setCredentials(credentials); repository.save(binding); return resp.withCredentials(credentials); } catch (IOException | JAXBException | EcsManagementClientException e) { throw new ServiceBrokerException(e); } } protected String getContainerDir(Map<String, Object> parameters, String bindingId) { if (parameters != null) { Object mount = parameters.get(MOUNT); if (mount != null) { return mount.toString(); } } return DEFAULT_MOUNT + File.separator + bindingId; } @Override public void deleteServiceInstanceBinding( DeleteServiceInstanceBindingRequest request) throws ServiceBrokerException { String bindingId = request.getBindingId(); String instanceId = request.getServiceInstanceId(); String serviceDefinitionId = request.getServiceDefinitionId(); ServiceDefinitionProxy service = catalog .findServiceDefinition(serviceDefinitionId); String serviceType = (String) service.getServiceSettings() .get(SERVICE_TYPE); try { if (BUCKET.equals(serviceType)) ecs.removeUserFromBucket(instanceId, bindingId); ecs.deleteUser(bindingId); LOG.error("looking up binding: " + bindingId); ServiceInstanceBinding binding = repository.find(bindingId); if (binding == null) { // TODO -- is this gonna blow up? repository.delete(bindingId); return; } LOG.error("binding found: " + bindingId); List<VolumeMount> volumes = binding.getVolumeMounts(); if (volumes == null || volumes.size() == 0) { repository.delete(bindingId); return; } Map<String, Object> mountConfig = ((SharedVolumeDevice) volumes.get(0).getDevice()).getMountConfig(); String unixId = (String) mountConfig.get("uid"); try { LOG.error("Deleting user map of instance Id and Binding Id " + instanceId + " " + bindingId); ecs.deleteUserMap(bindingId, unixId); } catch (EcsManagementClientException e) { LOG.error("Error deleting user map: " + e.getMessage()); } repository.delete(bindingId); } catch (Exception e) { LOG.error("Error deleting binding: " + e); throw new ServiceBrokerException(e); } } }
more tweaks to mount config code plus additional logging
src/main/java/com/emc/ecs/cloudfoundry/broker/service/EcsServiceInstanceBindingService.java
more tweaks to mount config code plus additional logging
Java
apache-2.0
4378de59fc9c91585b13875549e4db3c765138d8
0
datanucleus/datanucleus-maven-plugin
/********************************************************************** Copyright (c) 2007 Andy Jefferson and others. 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. Contributors: ... **********************************************************************/ package org.datanucleus.maven; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import org.apache.maven.artifact.Artifact; import org.apache.maven.plugin.MojoExecutionException; import org.codehaus.plexus.util.cli.CommandLineException; import org.codehaus.plexus.util.cli.Commandline; import org.datanucleus.store.schema.SchemaTool; /** * Base for all enhancer-based Maven2 goals. */ public abstract class AbstractEnhancerMojo extends AbstractDataNucleusMojo { private static final String TOOL_NAME_DATANUCLEUS_ENHANCER = "org.datanucleus.enhancer.DataNucleusEnhancer"; /** * @parameter expression="${quiet}" default-value="false" */ protected boolean quiet; /** * @parameter expression="${alwaysDetachable}" default-value="false" */ protected boolean alwaysDetachable; /** * @parameter expression="${generatePK}" default-value="true" */ protected boolean generatePK; /** * @parameter expression="${generateConstructor}" default-value="true" */ protected boolean generateConstructor; /** * @parameter expression="${detachListener}" default-value="false" */ protected boolean detachListener; /** * @parameter expression="${useFileListFile}" default-value="auto" */ protected String useFileListFile; /** * Method to execute the enhancer using the provided artifacts and input files. * @param pluginArtifacts Artifacts to use in CLASSPATH generation * @param files Input files */ @Override protected void executeDataNucleusTool(List pluginArtifacts, List files) throws CommandLineException, MojoExecutionException { enhance(pluginArtifacts, files); } /** * Run the DataNucleus Enhancer using the specified input data. * @param pluginArtifacts for creating classpath for execution. * @param files input file list * @throws CommandLineException if there was an error invoking the DataNucleus Enhancer. * @throws MojoExecutionException */ protected void enhance(List pluginArtifacts, List files) throws CommandLineException, MojoExecutionException { // Generate a set of CLASSPATH entries (avoiding dups) // Put plugin deps first so they are found before any project-specific artifacts List cpEntries = new ArrayList(); for (Iterator it = pluginArtifacts.iterator(); it.hasNext();) { Artifact artifact = (Artifact) it.next(); try { String artifactPath = artifact.getFile().getCanonicalPath(); if (!cpEntries.contains(artifactPath)) { cpEntries.add(artifactPath); } } catch (IOException e) { throw new MojoExecutionException("Error while creating the canonical path for '" + artifact.getFile() + "'.", e); } } Iterator uniqueIter = getUniqueClasspathElements().iterator(); while (uniqueIter.hasNext()) { String entry = (String)uniqueIter.next(); if (!cpEntries.contains(entry)) { cpEntries.add(entry); } } // Set the CLASSPATH of the java process StringBuffer cpBuffer = new StringBuffer(); for (Iterator it = cpEntries.iterator(); it.hasNext();) { cpBuffer.append((String) it.next()); if (it.hasNext()) { cpBuffer.append(File.pathSeparator); } } if (fork) { // Create a CommandLine for execution Commandline cl = new Commandline(); cl.setExecutable("java"); // uncomment the following if you want to debug the enhancer // cl.addArguments(new String[]{"-Xdebug", "-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000"}); cl.createArg().setValue("-cp"); cl.createArg().setValue(cpBuffer.toString()); // Logging - check for Log4j, else JDK1.4 URL log4jURL = getLog4JConfiguration(); if (log4jURL != null) { cl.createArg().setValue("-Dlog4j.configuration=" + log4jURL); } else { URL jdkLogURL = getJdkLogConfiguration(); if (jdkLogURL != null) { cl.createArg().setValue("-Djava.util.logging.config.file=" + jdkLogURL); } } cl.createArg().setValue(TOOL_NAME_DATANUCLEUS_ENHANCER); // allow extensions to prepare Mode specific arguments prepareModeSpecificCommandLineArguments(cl, null); if (quiet) { cl.createArg().setValue("-q"); } else if (verbose) { cl.createArg().setValue("-v"); } boolean usingPU = false; if (persistenceUnitName != null && persistenceUnitName.trim().length() > 0) { usingPU = true; cl.createArg().setLine("-pu " + persistenceUnitName); } cl.createArg().setLine("-api " + api); if (alwaysDetachable) { cl.createArg().setValue("-alwaysDetachable"); } if (!generatePK) { cl.createArg().setLine("-generatePK false"); } if (!generateConstructor) { cl.createArg().setLine("-generateConstructor false"); } if (detachListener) { cl.createArg().setLine("-detachListener true"); } if (!usingPU) { if (determineUseFileListFile()) { File fileListFile = writeFileListFile(files); cl.createArg().setLine("-flf \"" + fileListFile.getAbsolutePath() + '"'); } else { for (Iterator it = files.iterator(); it.hasNext();) { File file = (File) it.next(); cl.createArg().setValue(file.getAbsolutePath()); } } } executeCommandLine(cl); } else { // Execute in the current JVM, so build up list of arguments to the method invoke List args = new ArrayList(); // allow extensions to prepare Mode specific arguments prepareModeSpecificCommandLineArguments(null, args); if (quiet) { args.add("-q"); } else if (verbose) { args.add("-v"); } boolean usingPU = false; if (persistenceUnitName != null && persistenceUnitName.trim().length() > 0) { usingPU = true; args.add("-pu"); args.add(persistenceUnitName); } args.add("-api"); args.add(api); if (alwaysDetachable) { args.add("-alwaysDetachable"); } if (!generatePK) { args.add("-generatePK"); args.add("false"); } if (!generateConstructor) { args.add("-generateConstructor"); args.add("false"); } if (detachListener) { args.add("-detachListener"); args.add("true"); } if (!usingPU) { for (Iterator it = files.iterator(); it.hasNext();) { File file = (File) it.next(); args.add(file.getAbsolutePath()); } } executeInJvm(TOOL_NAME_DATANUCLEUS_ENHANCER, args, cpEntries, quiet); } } /** * Template method that sets up arguments for the {@link SchemaTool} depending upon the <b>mode</b> invoked. * This is expected to be implemented by extensions. * @param cl {@link Commandline} instance to set up arguments for. * @param args Arguments list generated by this call (appended to) */ protected abstract void prepareModeSpecificCommandLineArguments(Commandline cl, List args); /** * Accessor for the name of the class to be invoked. * @return Class name for the Enhancer. */ @Override protected String getToolName() { return TOOL_NAME_DATANUCLEUS_ENHANCER; } protected boolean determineUseFileListFile() { if (useFileListFile != null) { if ("true".equalsIgnoreCase(useFileListFile)) { return true; } else if ("false".equalsIgnoreCase(useFileListFile)) { return false; } else if (!"auto".equalsIgnoreCase(useFileListFile)) { System.err.println("WARNING: useFileListFile is an unknown value! Falling back to default!"); } } // 'auto' means true on Windows and false on other systems. Maybe we'll change this in the // future to always be true as the command line might be limited on other systems, too. // See: http://www.cyberciti.biz/faq/argument-list-too-long-error-solution/ // See: http://serverfault.com/questions/69430/what-is-the-maximum-length-of-a-command-line-in-mac-os-x return File.separatorChar == '\\'; } /** * Writes the given {@code files} into a temporary file. The file is deleted by the enhancer. * @param files the list of files to be written into the file (UTF-8-encoded). Must not be * <code>null</code>. * @return the temporary file. */ private static File writeFileListFile(Collection<File> files) { try { File fileListFile = File.createTempFile("enhancer-", ".flf"); System.out.println("Writing fileListFile: " + fileListFile); FileOutputStream out = new FileOutputStream(fileListFile); try { OutputStreamWriter w = new OutputStreamWriter(out, "UTF-8"); try { for (File file : files) { w.write(file.getAbsolutePath()); // The enhancer uses a BufferedReader, which accepts all types of line feeds (CR, LF, // CRLF). // Therefore a single \n is fine. w.write('\n'); } } finally { w.close(); } } finally { out.close(); } return fileListFile; } catch (IOException e) { throw new RuntimeException(e); } } }
src/java/org/datanucleus/maven/AbstractEnhancerMojo.java
/********************************************************************** Copyright (c) 2007 Andy Jefferson and others. 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. Contributors: ... **********************************************************************/ package org.datanucleus.maven; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import org.apache.maven.artifact.Artifact; import org.apache.maven.plugin.MojoExecutionException; import org.codehaus.plexus.util.cli.CommandLineException; import org.codehaus.plexus.util.cli.Commandline; import org.datanucleus.store.schema.SchemaTool; /** * Base for all enhancer-based Maven2 goals. */ public abstract class AbstractEnhancerMojo extends AbstractDataNucleusMojo { private static final String TOOL_NAME_DATANUCLEUS_ENHANCER = "org.datanucleus.enhancer.DataNucleusEnhancer"; /** * @parameter expression="${quiet}" default-value="false" */ protected boolean quiet; /** * @parameter expression="${alwaysDetachable}" default-value="false" */ protected boolean alwaysDetachable; /** * @parameter expression="${generatePK}" default-value="true" */ protected boolean generatePK; /** * @parameter expression="${generateConstructor}" default-value="true" */ protected boolean generateConstructor; /** * @parameter expression="${detachListener}" default-value="false" */ protected boolean detachListener; /** * @parameter expression="${useFileListFile}" default-value="auto" */ protected String useFileListFile; /** * Method to execute the enhancer using the provided artifacts and input files. * @param pluginArtifacts Artifacts to use in CLASSPATH generation * @param files Input files */ @Override protected void executeDataNucleusTool(List pluginArtifacts, List files) throws CommandLineException, MojoExecutionException { enhance(pluginArtifacts, files); } /** * Run the DataNucleus Enhancer using the specified input data. * @param pluginArtifacts for creating classpath for execution. * @param files input file list * @throws CommandLineException if there was an error invoking the DataNucleus Enhancer. * @throws MojoExecutionException */ protected void enhance(List pluginArtifacts, List files) throws CommandLineException, MojoExecutionException { // Generate a set of CLASSPATH entries (avoiding dups) // Put plugin deps first so they are found before any project-specific artifacts List cpEntries = new ArrayList(); for (Iterator it = pluginArtifacts.iterator(); it.hasNext();) { Artifact artifact = (Artifact) it.next(); try { String artifactPath = artifact.getFile().getCanonicalPath(); if (!cpEntries.contains(artifactPath)) { cpEntries.add(artifactPath); } } catch (IOException e) { throw new MojoExecutionException("Error while creating the canonical path for '" + artifact.getFile() + "'.", e); } } Iterator uniqueIter = getUniqueClasspathElements().iterator(); while (uniqueIter.hasNext()) { String entry = (String)uniqueIter.next(); if (!cpEntries.contains(entry)) { cpEntries.add(entry); } } // Set the CLASSPATH of the java process StringBuffer cpBuffer = new StringBuffer(); for (Iterator it = cpEntries.iterator(); it.hasNext();) { cpBuffer.append((String) it.next()); if (it.hasNext()) { cpBuffer.append(File.pathSeparator); } } if (fork) { // Create a CommandLine for execution Commandline cl = new Commandline(); cl.setExecutable("java"); // uncomment the following if you want to debug the enhancer // cl.addArguments(new String[]{"-Xdebug", "-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000"}); cl.createArg().setValue("-cp"); cl.createArg().setValue(cpBuffer.toString()); // Logging - check for Log4j, else JDK1.4 URL log4jURL = getLog4JConfiguration(); if (log4jURL != null) { cl.createArg().setValue("-Dlog4j.configuration=" + log4jURL); } else { URL jdkLogURL = getJdkLogConfiguration(); if (jdkLogURL != null) { cl.createArg().setValue("-Djava.util.logging.config.file=" + jdkLogURL); } } cl.createArg().setValue(TOOL_NAME_DATANUCLEUS_ENHANCER); // allow extensions to prepare Mode specific arguments prepareModeSpecificCommandLineArguments(cl, null); if (quiet) { cl.createArg().setValue("-q"); } else if (verbose) { cl.createArg().setValue("-v"); } boolean usingPU = false; if (persistenceUnitName != null && persistenceUnitName.trim().length() > 0) { usingPU = true; cl.createArg().setLine("-pu " + persistenceUnitName); } cl.createArg().setLine("-api " + api); if (alwaysDetachable) { cl.createArg().setValue("-alwaysDetachable"); } if (!generatePK) { cl.createArg().setLine("-generatePK false"); } if (!generateConstructor) { cl.createArg().setLine("-generateConstructor false"); } if (detachListener) { cl.createArg().setLine("-detachListener true"); } if (!usingPU) { if (determineUseFileListFile()) { File fileListFile = writeFileListFile(files); cl.createArg().setLine("-flf \"" + fileListFile.getAbsolutePath() + '"'); } else { for (Iterator it = files.iterator(); it.hasNext();) { File file = (File) it.next(); cl.createArg().setValue(file.getAbsolutePath()); } } } executeCommandLine(cl); } else { // Execute in the current JVM, so build up list of arguments to the method invoke List args = new ArrayList(); // allow extensions to prepare Mode specific arguments prepareModeSpecificCommandLineArguments(null, args); if (quiet) { args.add("-q"); } else if (verbose) { args.add("-v"); } boolean usingPU = false; if (persistenceUnitName != null && persistenceUnitName.trim().length() > 0) { usingPU = true; args.add("-pu"); args.add(persistenceUnitName); } args.add("-api"); args.add(api); if (alwaysDetachable) { args.add("-alwaysDetachable"); } if (!generatePK) { args.add("-generatePK"); args.add("false"); } if (!generateConstructor) { args.add("-generateConstructor"); args.add("false"); } if (detachListener) { args.add("-detachListener"); args.add("true"); } if (!usingPU) { for (Iterator it = files.iterator(); it.hasNext();) { File file = (File) it.next(); args.add(file.getAbsolutePath()); } } executeInJvm(TOOL_NAME_DATANUCLEUS_ENHANCER, args, cpEntries, quiet); } } /** * Template method that sets up arguments for the {@link SchemaTool} depending upon the <b>mode</b> invoked. * This is expected to be implemented by extensions. * @param cl {@link Commandline} instance to set up arguments for. * @param args Arguments list generated by this call (appended to) */ protected abstract void prepareModeSpecificCommandLineArguments(Commandline cl, List args); /** * Accessor for the name of the class to be invoked. * @return Class name for the Enhancer. */ @Override protected String getToolName() { return TOOL_NAME_DATANUCLEUS_ENHANCER; } protected boolean determineUseFileListFile() { if (useFileListFile != null) { if ("true".equalsIgnoreCase(useFileListFile)) return true; else if ("false".equalsIgnoreCase(useFileListFile)) return false; else if ("auto".equalsIgnoreCase(useFileListFile)) ; // simply ignore the warning below ;-) else System.err.println("WARNING: useFileListFile is an unknown value! Falling back to default!"); } // 'auto' means true on Windows and false on other systems. Maybe we'll change this in the // future to always be true as the command line might be limited on other systems, too. // See: http://www.cyberciti.biz/faq/argument-list-too-long-error-solution/ // See: http://serverfault.com/questions/69430/what-is-the-maximum-length-of-a-command-line-in-mac-os-x return File.separatorChar == '\\'; } /** * Writes the given {@code files} into a temporary file. The file is deleted by the enhancer. * * @param files the list of files to be written into the file (UTF-8-encoded). Must not be <code>null</code>. * @return the temporary file. */ private static File writeFileListFile(Collection<File> files) { try { File fileListFile = File.createTempFile("enhancer-", ".flf"); System.out.println("Writing fileListFile: " + fileListFile); FileOutputStream out = new FileOutputStream(fileListFile); try { OutputStreamWriter w = new OutputStreamWriter(out, "UTF-8"); try { for (File file : files) { w.write(file.getAbsolutePath()); // The enhancer uses a BufferedReader, which accepts all types of line feeds (CR, LF, CRLF). // Therefore a single \n is fine. w.write('\n'); } } finally { w.close(); } } finally { out.close(); } return fileListFile; } catch (IOException e) { throw new RuntimeException(e); } } }
Fix formatting to use DataNucleus conventions, and get rid of compiler warning
src/java/org/datanucleus/maven/AbstractEnhancerMojo.java
Fix formatting to use DataNucleus conventions, and get rid of compiler warning
Java
apache-2.0
6fc272f9136e9f816696f633c5536d7305026047
0
chrislusf/seaweedfs,chrislusf/seaweedfs,chrislusf/seaweedfs,chrislusf/seaweedfs
package seaweedfs.client; import org.apache.http.Header; import org.apache.http.HeaderElement; import org.apache.http.HttpEntity; import org.apache.http.HttpHeaders; import org.apache.http.client.entity.GzipDecompressingEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.*; public class SeaweedRead { private static final Logger LOG = LoggerFactory.getLogger(SeaweedRead.class); static ChunkCache chunkCache = new ChunkCache(4); // returns bytesRead public static long read(FilerGrpcClient filerGrpcClient, List<VisibleInterval> visibleIntervals, final long position, final byte[] buffer, final int bufferOffset, final int bufferLength, final long fileSize) throws IOException { List<ChunkView> chunkViews = viewFromVisibles(visibleIntervals, position, bufferLength); FilerProto.LookupVolumeRequest.Builder lookupRequest = FilerProto.LookupVolumeRequest.newBuilder(); for (ChunkView chunkView : chunkViews) { String vid = parseVolumeId(chunkView.fileId); lookupRequest.addVolumeIds(vid); } FilerProto.LookupVolumeResponse lookupResponse = filerGrpcClient .getBlockingStub().lookupVolume(lookupRequest.build()); Map<String, FilerProto.Locations> vid2Locations = lookupResponse.getLocationsMapMap(); //TODO parallel this long readCount = 0; long startOffset = position; for (ChunkView chunkView : chunkViews) { if (startOffset < chunkView.logicOffset) { long gap = chunkView.logicOffset - startOffset; LOG.debug("zero [{},{})", startOffset, startOffset + gap); readCount += gap; startOffset += gap; } FilerProto.Locations locations = vid2Locations.get(parseVolumeId(chunkView.fileId)); if (locations == null || locations.getLocationsCount() == 0) { LOG.error("failed to locate {}", chunkView.fileId); // log here! return 0; } int len = readChunkView(startOffset, buffer, bufferOffset + readCount, chunkView, locations); LOG.debug("read [{},{}) {} size {}", startOffset, startOffset + len, chunkView.fileId, chunkView.size); readCount += len; startOffset += len; } long limit = Math.min(bufferOffset + bufferLength, fileSize); if (startOffset < limit) { long gap = limit - startOffset; LOG.debug("zero2 [{},{})", startOffset, startOffset + gap); readCount += gap; startOffset += gap; } return readCount; } private static int readChunkView(long startOffset, byte[] buffer, long bufOffset, ChunkView chunkView, FilerProto.Locations locations) throws IOException { byte[] chunkData = chunkCache.getChunk(chunkView.fileId); if (chunkData == null) { chunkData = doFetchFullChunkData(chunkView, locations); chunkCache.setChunk(chunkView.fileId, chunkData); } int len = (int) chunkView.size; LOG.debug("readChunkView fid:{} chunkData.length:{} chunkView[{};{}) buf[{},{})/{} startOffset:{}", chunkView.fileId, chunkData.length, chunkView.offset, chunkView.offset + chunkView.size, bufOffset, bufOffset + len, buffer.length, startOffset); System.arraycopy(chunkData, (int) (startOffset - chunkView.logicOffset + chunkView.offset), buffer, (int) bufOffset, len); return len; } public static byte[] doFetchFullChunkData(ChunkView chunkView, FilerProto.Locations locations) throws IOException { byte[] data = null; IOException lastException = null; for (long waitTime = 1000L; waitTime < 10 * 1000; waitTime += waitTime / 2) { for (FilerProto.Location location : locations.getLocationsList()) { String url = String.format("http://%s/%s", location.getUrl(), chunkView.fileId); try { data = doFetchOneFullChunkData(chunkView, url); break; } catch (IOException ioe) { LOG.debug("doFetchFullChunkData {} :{}", url, ioe); lastException = ioe; } } if (data != null) { break; } try { Thread.sleep(waitTime); } catch (InterruptedException e) { } } if (data == null && lastException != null) { throw lastException; } LOG.debug("doFetchFullChunkData fid:{} chunkData.length:{}", chunkView.fileId, data.length); return data; } public static byte[] doFetchOneFullChunkData(ChunkView chunkView, String url) throws IOException { HttpGet request = new HttpGet(url); request.setHeader(HttpHeaders.ACCEPT_ENCODING, "gzip"); byte[] data = null; CloseableHttpResponse response = SeaweedUtil.getClosableHttpClient().execute(request); try { HttpEntity entity = response.getEntity(); Header contentEncodingHeader = entity.getContentEncoding(); if (contentEncodingHeader != null) { HeaderElement[] encodings = contentEncodingHeader.getElements(); for (int i = 0; i < encodings.length; i++) { if (encodings[i].getName().equalsIgnoreCase("gzip")) { entity = new GzipDecompressingEntity(entity); break; } } } data = EntityUtils.toByteArray(entity); EntityUtils.consume(entity); } finally { response.close(); request.releaseConnection(); } if (chunkView.cipherKey != null && chunkView.cipherKey.length != 0) { try { data = SeaweedCipher.decrypt(data, chunkView.cipherKey); } catch (Exception e) { throw new IOException("fail to decrypt", e); } } if (chunkView.isCompressed) { data = Gzip.decompress(data); } LOG.debug("doFetchOneFullChunkData url:{} chunkData.length:{}", url, data.length); return data; } protected static List<ChunkView> viewFromVisibles(List<VisibleInterval> visibleIntervals, long offset, long size) { List<ChunkView> views = new ArrayList<>(); long stop = offset + size; for (VisibleInterval chunk : visibleIntervals) { long chunkStart = Math.max(offset, chunk.start); long chunkStop = Math.min(stop, chunk.stop); if (chunkStart < chunkStop) { boolean isFullChunk = chunk.isFullChunk && chunk.start == offset && chunk.stop <= stop; views.add(new ChunkView( chunk.fileId, chunkStart - chunk.start + chunk.chunkOffset, chunkStop - chunkStart, chunkStart, isFullChunk, chunk.cipherKey, chunk.isCompressed )); } } return views; } public static List<VisibleInterval> nonOverlappingVisibleIntervals( final FilerGrpcClient filerGrpcClient, List<FilerProto.FileChunk> chunkList) throws IOException { chunkList = FileChunkManifest.resolveChunkManifest(filerGrpcClient, chunkList); FilerProto.FileChunk[] chunks = chunkList.toArray(new FilerProto.FileChunk[0]); Arrays.sort(chunks, new Comparator<FilerProto.FileChunk>() { @Override public int compare(FilerProto.FileChunk a, FilerProto.FileChunk b) { // if just a.getMtime() - b.getMtime(), it will overflow! if (a.getMtime() < b.getMtime()) { return -1; } else if (a.getMtime() > b.getMtime()) { return 1; } return 0; } }); List<VisibleInterval> visibles = new ArrayList<>(); for (FilerProto.FileChunk chunk : chunks) { List<VisibleInterval> newVisibles = new ArrayList<>(); visibles = mergeIntoVisibles(visibles, newVisibles, chunk); } return visibles; } private static List<VisibleInterval> mergeIntoVisibles(List<VisibleInterval> visibles, List<VisibleInterval> newVisibles, FilerProto.FileChunk chunk) { VisibleInterval newV = new VisibleInterval( chunk.getOffset(), chunk.getOffset() + chunk.getSize(), chunk.getFileId(), chunk.getMtime(), 0, true, chunk.getCipherKey().toByteArray(), chunk.getIsCompressed() ); // easy cases to speed up if (visibles.size() == 0) { visibles.add(newV); return visibles; } if (visibles.get(visibles.size() - 1).stop <= chunk.getOffset()) { visibles.add(newV); return visibles; } for (VisibleInterval v : visibles) { if (v.start < chunk.getOffset() && chunk.getOffset() < v.stop) { newVisibles.add(new VisibleInterval( v.start, chunk.getOffset(), v.fileId, v.modifiedTime, v.chunkOffset, false, v.cipherKey, v.isCompressed )); } long chunkStop = chunk.getOffset() + chunk.getSize(); if (v.start < chunkStop && chunkStop < v.stop) { newVisibles.add(new VisibleInterval( chunkStop, v.stop, v.fileId, v.modifiedTime, v.chunkOffset + (chunkStop - v.start), false, v.cipherKey, v.isCompressed )); } if (chunkStop <= v.start || v.stop <= chunk.getOffset()) { newVisibles.add(v); } } newVisibles.add(newV); // keep everything sorted for (int i = newVisibles.size() - 1; i >= 0; i--) { if (i > 0 && newV.start < newVisibles.get(i - 1).start) { newVisibles.set(i, newVisibles.get(i - 1)); } else { newVisibles.set(i, newV); break; } } return newVisibles; } public static String parseVolumeId(String fileId) { int commaIndex = fileId.lastIndexOf(','); if (commaIndex > 0) { return fileId.substring(0, commaIndex); } return fileId; } public static long fileSize(FilerProto.Entry entry) { return Math.max(totalSize(entry.getChunksList()), entry.getAttributes().getFileSize()); } public static long totalSize(List<FilerProto.FileChunk> chunksList) { long size = 0; for (FilerProto.FileChunk chunk : chunksList) { long t = chunk.getOffset() + chunk.getSize(); if (size < t) { size = t; } } return size; } public static class VisibleInterval { public final long start; public final long stop; public final long modifiedTime; public final String fileId; public final long chunkOffset; public final boolean isFullChunk; public final byte[] cipherKey; public final boolean isCompressed; public VisibleInterval(long start, long stop, String fileId, long modifiedTime, long chunkOffset, boolean isFullChunk, byte[] cipherKey, boolean isCompressed) { this.start = start; this.stop = stop; this.modifiedTime = modifiedTime; this.fileId = fileId; this.chunkOffset = chunkOffset; this.isFullChunk = isFullChunk; this.cipherKey = cipherKey; this.isCompressed = isCompressed; } @Override public String toString() { return "VisibleInterval{" + "start=" + start + ", stop=" + stop + ", modifiedTime=" + modifiedTime + ", fileId='" + fileId + '\'' + ", isFullChunk=" + isFullChunk + ", cipherKey=" + Arrays.toString(cipherKey) + ", isCompressed=" + isCompressed + '}'; } } public static class ChunkView { public final String fileId; public final long offset; public final long size; public final long logicOffset; public final boolean isFullChunk; public final byte[] cipherKey; public final boolean isCompressed; public ChunkView(String fileId, long offset, long size, long logicOffset, boolean isFullChunk, byte[] cipherKey, boolean isCompressed) { this.fileId = fileId; this.offset = offset; this.size = size; this.logicOffset = logicOffset; this.isFullChunk = isFullChunk; this.cipherKey = cipherKey; this.isCompressed = isCompressed; } @Override public String toString() { return "ChunkView{" + "fileId='" + fileId + '\'' + ", offset=" + offset + ", size=" + size + ", logicOffset=" + logicOffset + ", isFullChunk=" + isFullChunk + ", cipherKey=" + Arrays.toString(cipherKey) + ", isCompressed=" + isCompressed + '}'; } } }
other/java/client/src/main/java/seaweedfs/client/SeaweedRead.java
package seaweedfs.client; import org.apache.http.Header; import org.apache.http.HeaderElement; import org.apache.http.HttpEntity; import org.apache.http.HttpHeaders; import org.apache.http.client.entity.GzipDecompressingEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.*; public class SeaweedRead { private static final Logger LOG = LoggerFactory.getLogger(SeaweedRead.class); static ChunkCache chunkCache = new ChunkCache(4); // returns bytesRead public static long read(FilerGrpcClient filerGrpcClient, List<VisibleInterval> visibleIntervals, final long position, final byte[] buffer, final int bufferOffset, final int bufferLength, final long fileSize) throws IOException { List<ChunkView> chunkViews = viewFromVisibles(visibleIntervals, position, bufferLength); FilerProto.LookupVolumeRequest.Builder lookupRequest = FilerProto.LookupVolumeRequest.newBuilder(); for (ChunkView chunkView : chunkViews) { String vid = parseVolumeId(chunkView.fileId); lookupRequest.addVolumeIds(vid); } FilerProto.LookupVolumeResponse lookupResponse = filerGrpcClient .getBlockingStub().lookupVolume(lookupRequest.build()); Map<String, FilerProto.Locations> vid2Locations = lookupResponse.getLocationsMapMap(); //TODO parallel this long readCount = 0; long startOffset = position; for (ChunkView chunkView : chunkViews) { if (startOffset < chunkView.logicOffset) { long gap = chunkView.logicOffset - startOffset; LOG.debug("zero [{},{})", startOffset, startOffset + gap); readCount += gap; startOffset += gap; } FilerProto.Locations locations = vid2Locations.get(parseVolumeId(chunkView.fileId)); if (locations == null || locations.getLocationsCount() == 0) { LOG.error("failed to locate {}", chunkView.fileId); // log here! return 0; } int len = readChunkView(startOffset, buffer, bufferOffset + readCount, chunkView, locations); LOG.debug("read [{},{}) {} size {}", startOffset, startOffset + len, chunkView.fileId, chunkView.size); readCount += len; startOffset += len; } long limit = Math.min(bufferOffset + bufferLength, fileSize); if (startOffset < limit) { long gap = limit - startOffset; LOG.debug("zero2 [{},{})", startOffset, startOffset + gap); readCount += gap; startOffset += gap; } return readCount; } private static int readChunkView(long startOffset, byte[] buffer, long bufOffset, ChunkView chunkView, FilerProto.Locations locations) throws IOException { byte[] chunkData = chunkCache.getChunk(chunkView.fileId); if (chunkData == null) { chunkData = doFetchFullChunkData(chunkView, locations); chunkCache.setChunk(chunkView.fileId, chunkData); } int len = (int) chunkView.size; LOG.debug("readChunkView fid:{} chunkData.length:{} chunkView[{};{}) buf[{},{})/{} startOffset:{}", chunkView.fileId, chunkData.length, chunkView.offset, chunkView.offset+chunkView.size, bufOffset, bufOffset+len, buffer.length, startOffset); System.arraycopy(chunkData, (int) (startOffset - chunkView.logicOffset + chunkView.offset), buffer, (int)bufOffset, len); return len; } public static byte[] doFetchFullChunkData(ChunkView chunkView, FilerProto.Locations locations) throws IOException { byte[] data = null; IOException lastException = null; for (long waitTime = 1000L; waitTime < 10 * 1000; waitTime += waitTime / 2) { for (FilerProto.Location location : locations.getLocationsList()) { String url = String.format("http://%s/%s", location.getUrl(), chunkView.fileId); try { data = doFetchOneFullChunkData(chunkView, url); break; } catch (IOException ioe) { LOG.debug("doFetchFullChunkData {} :{}", url, ioe); lastException = ioe; } } if (data != null) { break; } try { Thread.sleep(waitTime); } catch (InterruptedException e) { } } if (data == null) { throw lastException; } LOG.debug("doFetchFullChunkData fid:{} chunkData.length:{}", chunkView.fileId, data.length); return data; } public static byte[] doFetchOneFullChunkData(ChunkView chunkView, String url) throws IOException { HttpGet request = new HttpGet(url); request.setHeader(HttpHeaders.ACCEPT_ENCODING, "gzip"); byte[] data = null; CloseableHttpResponse response = SeaweedUtil.getClosableHttpClient().execute(request); try { HttpEntity entity = response.getEntity(); Header contentEncodingHeader = entity.getContentEncoding(); if (contentEncodingHeader != null) { HeaderElement[] encodings = contentEncodingHeader.getElements(); for (int i = 0; i < encodings.length; i++) { if (encodings[i].getName().equalsIgnoreCase("gzip")) { entity = new GzipDecompressingEntity(entity); break; } } } data = EntityUtils.toByteArray(entity); EntityUtils.consume(entity); } finally { response.close(); request.releaseConnection(); } if (chunkView.cipherKey != null && chunkView.cipherKey.length != 0) { try { data = SeaweedCipher.decrypt(data, chunkView.cipherKey); } catch (Exception e) { throw new IOException("fail to decrypt", e); } } if (chunkView.isCompressed) { data = Gzip.decompress(data); } LOG.debug("doFetchOneFullChunkData url:{} chunkData.length:{}", url, data.length); return data; } protected static List<ChunkView> viewFromVisibles(List<VisibleInterval> visibleIntervals, long offset, long size) { List<ChunkView> views = new ArrayList<>(); long stop = offset + size; for (VisibleInterval chunk : visibleIntervals) { long chunkStart = Math.max(offset, chunk.start); long chunkStop = Math.min(stop, chunk.stop); if (chunkStart < chunkStop) { boolean isFullChunk = chunk.isFullChunk && chunk.start == offset && chunk.stop <= stop; views.add(new ChunkView( chunk.fileId, chunkStart - chunk.start + chunk.chunkOffset, chunkStop - chunkStart, chunkStart, isFullChunk, chunk.cipherKey, chunk.isCompressed )); } } return views; } public static List<VisibleInterval> nonOverlappingVisibleIntervals( final FilerGrpcClient filerGrpcClient, List<FilerProto.FileChunk> chunkList) throws IOException { chunkList = FileChunkManifest.resolveChunkManifest(filerGrpcClient, chunkList); FilerProto.FileChunk[] chunks = chunkList.toArray(new FilerProto.FileChunk[0]); Arrays.sort(chunks, new Comparator<FilerProto.FileChunk>() { @Override public int compare(FilerProto.FileChunk a, FilerProto.FileChunk b) { // if just a.getMtime() - b.getMtime(), it will overflow! if (a.getMtime() < b.getMtime()) { return -1; } else if (a.getMtime() > b.getMtime()) { return 1; } return 0; } }); List<VisibleInterval> visibles = new ArrayList<>(); for (FilerProto.FileChunk chunk : chunks) { List<VisibleInterval> newVisibles = new ArrayList<>(); visibles = mergeIntoVisibles(visibles, newVisibles, chunk); } return visibles; } private static List<VisibleInterval> mergeIntoVisibles(List<VisibleInterval> visibles, List<VisibleInterval> newVisibles, FilerProto.FileChunk chunk) { VisibleInterval newV = new VisibleInterval( chunk.getOffset(), chunk.getOffset() + chunk.getSize(), chunk.getFileId(), chunk.getMtime(), 0, true, chunk.getCipherKey().toByteArray(), chunk.getIsCompressed() ); // easy cases to speed up if (visibles.size() == 0) { visibles.add(newV); return visibles; } if (visibles.get(visibles.size() - 1).stop <= chunk.getOffset()) { visibles.add(newV); return visibles; } for (VisibleInterval v : visibles) { if (v.start < chunk.getOffset() && chunk.getOffset() < v.stop) { newVisibles.add(new VisibleInterval( v.start, chunk.getOffset(), v.fileId, v.modifiedTime, v.chunkOffset, false, v.cipherKey, v.isCompressed )); } long chunkStop = chunk.getOffset() + chunk.getSize(); if (v.start < chunkStop && chunkStop < v.stop) { newVisibles.add(new VisibleInterval( chunkStop, v.stop, v.fileId, v.modifiedTime, v.chunkOffset + (chunkStop - v.start), false, v.cipherKey, v.isCompressed )); } if (chunkStop <= v.start || v.stop <= chunk.getOffset()) { newVisibles.add(v); } } newVisibles.add(newV); // keep everything sorted for (int i = newVisibles.size() - 1; i >= 0; i--) { if (i > 0 && newV.start < newVisibles.get(i - 1).start) { newVisibles.set(i, newVisibles.get(i - 1)); } else { newVisibles.set(i, newV); break; } } return newVisibles; } public static String parseVolumeId(String fileId) { int commaIndex = fileId.lastIndexOf(','); if (commaIndex > 0) { return fileId.substring(0, commaIndex); } return fileId; } public static long fileSize(FilerProto.Entry entry) { return Math.max(totalSize(entry.getChunksList()), entry.getAttributes().getFileSize()); } public static long totalSize(List<FilerProto.FileChunk> chunksList) { long size = 0; for (FilerProto.FileChunk chunk : chunksList) { long t = chunk.getOffset() + chunk.getSize(); if (size < t) { size = t; } } return size; } public static class VisibleInterval { public final long start; public final long stop; public final long modifiedTime; public final String fileId; public final long chunkOffset; public final boolean isFullChunk; public final byte[] cipherKey; public final boolean isCompressed; public VisibleInterval(long start, long stop, String fileId, long modifiedTime, long chunkOffset, boolean isFullChunk, byte[] cipherKey, boolean isCompressed) { this.start = start; this.stop = stop; this.modifiedTime = modifiedTime; this.fileId = fileId; this.chunkOffset = chunkOffset; this.isFullChunk = isFullChunk; this.cipherKey = cipherKey; this.isCompressed = isCompressed; } @Override public String toString() { return "VisibleInterval{" + "start=" + start + ", stop=" + stop + ", modifiedTime=" + modifiedTime + ", fileId='" + fileId + '\'' + ", isFullChunk=" + isFullChunk + ", cipherKey=" + Arrays.toString(cipherKey) + ", isCompressed=" + isCompressed + '}'; } } public static class ChunkView { public final String fileId; public final long offset; public final long size; public final long logicOffset; public final boolean isFullChunk; public final byte[] cipherKey; public final boolean isCompressed; public ChunkView(String fileId, long offset, long size, long logicOffset, boolean isFullChunk, byte[] cipherKey, boolean isCompressed) { this.fileId = fileId; this.offset = offset; this.size = size; this.logicOffset = logicOffset; this.isFullChunk = isFullChunk; this.cipherKey = cipherKey; this.isCompressed = isCompressed; } @Override public String toString() { return "ChunkView{" + "fileId='" + fileId + '\'' + ", offset=" + offset + ", size=" + size + ", logicOffset=" + logicOffset + ", isFullChunk=" + isFullChunk + ", cipherKey=" + Arrays.toString(cipherKey) + ", isCompressed=" + isCompressed + '}'; } } }
adjust throwing exception
other/java/client/src/main/java/seaweedfs/client/SeaweedRead.java
adjust throwing exception
Java
apache-2.0
b9584b343c3241d9469d729875d6bbc7073dc013
0
andehr/tag-classification-framework
package uk.ac.susx.tag.classificationframework.classifiers; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import it.unimi.dsi.fastutil.ints.*; import it.unimi.dsi.fastutil.objects.ObjectIterator; import uk.ac.susx.tag.classificationframework.datastructures.ProcessedInstance; import uk.ac.susx.tag.classificationframework.featureextraction.pipelines.FeatureExtractionPipeline; import java.io.*; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * Created by thk22 on 03/10/2014. * * NaiveBayes type specific OVR Classifier, inherits from NaiveBayesClassifier rather than OVRClassifier, because it * a) fulfils the contract of a NaiveBayesClassifier and * b) makes life downstream a lot easier * * Essentially it takes n NaiveBayesClassifiers and wraps them into a single new classifier, which is able to pretend to * be a NaiveBayesClassifier and handles all the differences internally. * * It is a schizophrenic creature meant to cause confusion and havoc! * (Thomas, 21.1.2015: It bloody does cause havoc, I didn't look at it for 2 months and it confuses the shit out of me...) * * On the downside of it inheriting from NaiveBayesClassifier rather than OVRClassifer is, it currently duplicates a fair bit of code already implemented in OVRClassifier which is identical to the stuff here. * Options for cleaning up that mess: * a) Dress up in a black tie suit, grab a monocle, a pocket watch and a glass of Brandy, mix with some Enterprise Architect people and philosophise about Java Design Patterns and Best Practices and come up with a super-corporatistic-over-engineered solution. * b) Delete OVRClassifier because its a prime example of pre-mature optimisation. * c) Live with a badly written codebase which is a *dream* to maintain and where future developers (and myself) will curse me and my children and my childrens children, etc, for being an absolute useless and substandard code monkey. * d) Something else. * * Note: Not all of the above statements are true anymore. * * Further Note: I went for option b), deleting the root of all evil, in the hopes of spreading some good karma across the whole project. (I will still keep the literary work above "as is", because its the only piece of documentation in this file) * */ public class NaiveBayesOVRClassifier<T extends NaiveBayesClassifier> extends NaiveBayesClassifier { private static final int OTHER_LABEL = Integer.MAX_VALUE; private static final String OTHER_LABEL_NAME = "__OVR_OTHER_LABEL__"; private Int2ObjectMap<T> ovrLearners; private Class<T> learnerClass; public NaiveBayesOVRClassifier(IntSet labels, Class<T> learnerClass) { super(labels); this.ovrLearners = new Int2ObjectOpenHashMap<>(); this.learnerClass = learnerClass; this.initOVRScheme(); } public NaiveBayesOVRClassifier(IntSet labels, Class<T> learnerClass, Int2ObjectMap<T> ovrLearners) { super(labels); this.ovrLearners = ovrLearners; this.learnerClass = learnerClass; } @Override protected void writeJsonIntSet(JsonWriter writer, FeatureExtractionPipeline pipeline, IntSet set, boolean areFeatures) throws IOException { if (areFeatures) super.writeJsonIntSet(writer, pipeline, set, areFeatures); else { writer.beginArray(); for (int i : set) { String labelString = (i == OTHER_LABEL) ? OTHER_LABEL_NAME : pipeline.labelString(i); writer.value(labelString); } writer.endArray(); } } @Override protected void writeJsonInt2DoubleMap(JsonWriter writer, FeatureExtractionPipeline pipeline, Int2DoubleOpenHashMap map, boolean areFeatures) throws IOException{ if (areFeatures) super.writeJsonInt2DoubleMap(writer, pipeline, map, areFeatures); else { writer.beginObject(); ObjectIterator<Int2DoubleMap.Entry> i = map.int2DoubleEntrySet().fastIterator(); while (i.hasNext()) { Int2DoubleMap.Entry entry = i.next(); String name = (entry.getIntKey() == OTHER_LABEL) ? OTHER_LABEL_NAME : pipeline.labelString(entry.getIntKey()); writer.name(name); writer.value(entry.getDoubleValue()); } writer.endObject(); } } @Override protected void writeJsonInt2ObjectMap(JsonWriter writer, FeatureExtractionPipeline pipeline, Int2ObjectMap<Int2DoubleOpenHashMap> map) throws IOException{ writer.beginObject(); for(Int2ObjectMap.Entry<Int2DoubleOpenHashMap> entry : map.int2ObjectEntrySet()){ String name = (entry.getIntKey() == OTHER_LABEL) ? OTHER_LABEL_NAME : pipeline.labelString(entry.getIntKey()); writer.name(name); writeJsonInt2DoubleMap(writer, pipeline, entry.getValue(), true); } writer.endObject(); } /* The values from all the indivdiual ovrLearners need to be propagated back to the NB Classifier that <this> object represents in order to make the serialisation work properly. Note that the NB Classifier that <this> object represents doesn't actually learn anything, its the ovrLearners it wraps that do the learning. Its a bit confusing to have the structure this way, but having the OVR Wrapper deriving the NB Classifier makes life downstream just so much easier. */ @Override public void writeJson(File out, FeatureExtractionPipeline pipeline) throws IOException { if (labels.size() > 2) { try (JsonWriter writer = new JsonWriter(new OutputStreamWriter(new FileOutputStream(out), "UTF-8"))) { writer.beginArray(); for (Integer l : this.ovrLearners.keySet()) { T ovrLearner = this.ovrLearners.get(l); writer.beginObject(); writer.name(l.toString()); writer.beginObject(); writer.name("labelSmoothing").value(ovrLearner.getLabelSmoothing()); writer.name("featureSmoothing").value(ovrLearner.getFeatureSmoothing()); writer.name("labelMultipliers"); writeJsonInt2DoubleMap(writer, pipeline, ovrLearner.labelMultipliers, false); writer.name("labels"); writeJsonIntSet(writer, pipeline, ovrLearner.labels, false); writer.name("vocab"); writeJsonIntSet(writer, pipeline, ovrLearner.vocab, true); writer.name("docCounts"); writeJsonInt2DoubleMap(writer, pipeline, ovrLearner.docCounts, false); writer.name("labelCounts"); writeJsonInt2DoubleMap(writer, pipeline, ovrLearner.labelCounts, false); writer.name("jointCounts"); writeJsonInt2ObjectMap(writer, pipeline, ovrLearner.jointCounts); writer.name("labelFeatureAlphas"); writeJsonInt2ObjectMap(writer, pipeline, ovrLearner.labelFeatureAlphas); writer.name("featureAlphaTotals"); writeJsonInt2DoubleMap(writer, pipeline, ovrLearner.featureAlphaTotals, false); writer.name("labelAlphas"); writeJsonInt2DoubleMap(writer, pipeline, ovrLearner.labelAlphas, false); writer.name("empiricalLabelPriors").value(ovrLearner.empiricalLabelPriors); writer.endObject(); writer.endObject(); } writer.endArray(); } } else { this.ovrLearners.get(OTHER_LABEL).writeJson(out, pipeline); } /* This works, v1 if (this.labels.size() > 2) { for (int l : this.ovrLearners.keySet()) { // Note, the shared variables (labelSmoothing, featureSmoothing, ...) are overridden with each iteration, this is a known uglyness and will be properly resolved once creativity (and motivation) return into town. T ovrLearner = this.ovrLearners.get(l); super.setLabelSmoothing(ovrLearner.getLabelSmoothing()); super.setFeatureSmoothing(ovrLearner.getFeatureSmoothing()); super.vocab = ovrLearner.vocab; super.empiricalLabelPriors = ovrLearner.empiricalLabelPriors; // Leave empty if empty, otherwise modify if (ovrLearner.labelMultipliers.containsKey(l)) { super.labelMultipliers.put(l, ovrLearner.labelMultipliers.get(l)); } if (ovrLearner.docCounts.containsKey(l)) { super.docCounts.put(l, ovrLearner.docCounts.get(l)); } if (ovrLearner.labelCounts.containsKey(l)) { super.labelCounts.put(l, ovrLearner.labelCounts.get(l)); } if (ovrLearner.jointCounts.containsKey(l)) { super.jointCounts.put(l, ovrLearner.jointCounts.get(l)); } if (ovrLearner.labelFeatureAlphas.containsKey(l)) { super.labelFeatureAlphas.put(l, ovrLearner.labelFeatureAlphas.get(l)); } if (ovrLearner.featureAlphaTotals.containsKey(l)) { super.featureAlphaTotals.put(l, ovrLearner.featureAlphaTotals.get(l)); } if (ovrLearner.labelAlphas.containsKey(l)) { super.labelAlphas.put(l, ovrLearner.labelAlphas.get(l)); } } } else { super.setLabelSmoothing(this.ovrLearners.get(OTHER_LABEL).getLabelSmoothing()); super.setFeatureSmoothing(this.ovrLearners.get(OTHER_LABEL).getFeatureSmoothing()); super.labelMultipliers = this.ovrLearners.get(OTHER_LABEL).labelMultipliers; super.labels = this.ovrLearners.get(OTHER_LABEL).labels; super.vocab = this.ovrLearners.get(OTHER_LABEL).vocab; super.docCounts = this.ovrLearners.get(OTHER_LABEL).docCounts; super.labelCounts = this.ovrLearners.get(OTHER_LABEL).labelCounts; super.jointCounts = this.ovrLearners.get(OTHER_LABEL).jointCounts; super.labelFeatureAlphas = this.ovrLearners.get(OTHER_LABEL).labelFeatureAlphas; super.featureAlphaTotals = this.ovrLearners.get(OTHER_LABEL).featureAlphaTotals; super.labelAlphas = this.ovrLearners.get(OTHER_LABEL).labelAlphas; super.empiricalLabelPriors = this.ovrLearners.get(OTHER_LABEL).empiricalLabelPriors; } super.writeJson(out, pipeline); */ } public static NaiveBayesOVRClassifier readJson(File in, FeatureExtractionPipeline pipeline, Class<? extends NaiveBayesClassifier> learnerClass) throws IOException { IntSet labels = null; // Re-create the OVR business by first reading in the labels and then constructing the OVR Setup from there try (JsonReader reader = new JsonReader(new InputStreamReader(new FileInputStream(in), "UTF-8"))) { reader.beginObject(); while (reader.hasNext()) { String name = reader.nextName(); switch (name) { // Don't worry; this is okay in Java 7 onwards case "labels": labels = NaiveBayesClassifier.readJsonIntSet(reader, pipeline, false); break; } } reader.endObject(); } NaiveBayesOVRClassifier<? extends NaiveBayesClassifier> nbOVR = new NaiveBayesOVRClassifier(labels, learnerClass); if (labels.size() > 2) { } else { // This NB Classifier acts as a proxy NaiveBayesClassifier nb = NaiveBayesClassifier.readJson(in, pipeline); } // TODO: Need to maintain a set of "otherCounts" for every attribute in the JSON to // properly initialise all of the OVR NB models Int2ObjectMap<Int2DoubleOpenHashMap> otherLabelMultipliers = new Int2ObjectOpenHashMap<>(); Int2ObjectMap<Int2DoubleOpenHashMap> otherDocCounts = new Int2ObjectOpenHashMap<>(); Int2ObjectMap<Int2DoubleOpenHashMap> otherLabelCounts = new Int2ObjectOpenHashMap<>(); Int2ObjectMap<Int2ObjectMap<Int2DoubleOpenHashMap>> otherJointCounts = new Int2ObjectOpenHashMap<>(); Int2ObjectMap<Int2ObjectMap<Int2DoubleOpenHashMap>> otherLabelFeatureAlphas = new Int2ObjectOpenHashMap<>(); Int2ObjectMap<Int2DoubleOpenHashMap> otherFeatureAlphaTotals = new Int2ObjectOpenHashMap<>(); Int2ObjectMap<Int2DoubleOpenHashMap> otherLabelAlphas = new Int2ObjectOpenHashMap<>(); for (int l : labels) { try (JsonReader reader = new JsonReader(new InputStreamReader(new FileInputStream(in), "UTF-8"))) { reader.beginObject(); while (reader.hasNext()) { String name = reader.nextName(); switch (name) { // Don't worry; this is okay in Java 7 onwards case "labelSmoothing": nbOVR.ovrLearners.get(l).setLabelSmoothing(reader.nextDouble()); break; case "featureSmoothing": nbOVR.ovrLearners.get(l).setFeatureSmoothing(reader.nextDouble()); break; case "labelMultipliers": { // TODO: Collect counts for other lables Int2DoubleOpenHashMap temp = readJsonInt2DoubleMap(reader, pipeline, false); for (int ll : labels) { if (ll == l) continue; otherLabelMultipliers.get(l).addTo(OTHER_LABEL, temp.get(ll)); } nbOVR.ovrLearners.get(l).labelMultipliers.put(l, temp.get(l)); nbOVR.ovrLearners.get(l).labelMultipliers.put(OTHER_LABEL, otherLabelMultipliers.get(l).get(OTHER_LABEL)); break; } case "labels": nbOVR.ovrLearners.get(l).labels = readJsonIntSet(reader, pipeline, false); break; case "vocab": nbOVR.ovrLearners.get(l).vocab = readJsonIntSet(reader, pipeline, false); break; case "docCounts": { Int2DoubleOpenHashMap temp = readJsonInt2DoubleMap(reader, pipeline, false); for (int ll : labels) { if (ll == l) continue; otherDocCounts.get(l).addTo(OTHER_LABEL, temp.get(ll)); } nbOVR.ovrLearners.get(l).docCounts.put(l, temp.get(l)); nbOVR.ovrLearners.get(l).docCounts.put(OTHER_LABEL, otherDocCounts.get(l).get(OTHER_LABEL)); break; } case "labelCounts": { Int2DoubleOpenHashMap temp = readJsonInt2DoubleMap(reader, pipeline, false); for (int ll : labels) { if (ll == l) continue; otherLabelCounts.get(l).addTo(OTHER_LABEL, temp.get(ll)); } nbOVR.ovrLearners.get(l).labelCounts.put(l, temp.get(l)); nbOVR.ovrLearners.get(l).labelCounts.put(OTHER_LABEL, otherLabelCounts.get(l).get(OTHER_LABEL)); break; } case "jointCounts": { /* Int2DoubleOpenHashMap temp = readJsonInt2DoubleMap(reader, pipeline, false); for (int ll : labels) { if (ll == l) continue; otherJointCounts.get(l).addTo(OTHER_LABEL, temp.get(ll)); } nbOVR.ovrLearners.get(l).jointCounts.put(l, temp.get(l)); nbOVR.ovrLearners.get(l).jointCounts.put(OTHER_LABEL, otherLabelCounts.get(l).get(OTHER_LABEL)); */ break; } case "labelFeatureAlphas": //nb.labelFeatureAlphas = readJsonInt2ObjectMap(reader, pipeline); break; case "featureAlphaTotals":{ Int2DoubleOpenHashMap temp = readJsonInt2DoubleMap(reader, pipeline, false); for (int ll : labels) { if (ll == l) continue; otherFeatureAlphaTotals.get(l).addTo(OTHER_LABEL, temp.get(ll)); } nbOVR.ovrLearners.get(l).featureAlphaTotals.put(l, temp.get(l)); nbOVR.ovrLearners.get(l).featureAlphaTotals.put(OTHER_LABEL, otherFeatureAlphaTotals.get(l).get(OTHER_LABEL)); break; } case "labelAlphas": { Int2DoubleOpenHashMap temp = readJsonInt2DoubleMap(reader, pipeline, false); for (int ll : labels) { if (ll == l) continue; otherLabelAlphas.get(l).addTo(OTHER_LABEL, temp.get(ll)); } nbOVR.ovrLearners.get(l).labelAlphas.put(l, temp.get(l)); nbOVR.ovrLearners.get(l).labelAlphas.put(OTHER_LABEL, otherLabelAlphas.get(l).get(OTHER_LABEL)); break; } case "empiricalLabelPriors": nbOVR.ovrLearners.get(l).empiricalLabelPriors = reader.nextBoolean(); break; } } reader.endObject(); } } return null; } @Override public void setLabelSmoothing(double smoothingValue) { for (int l : this.ovrLearners.keySet()) { this.ovrLearners.get(l).setLabelSmoothing(smoothingValue); } } @Override public void setFeatureSmoothing(double smoothingValue) { for (int l : this.ovrLearners.keySet()) { this.ovrLearners.get(l).setFeatureSmoothing(smoothingValue); } } @Override public void setLabelAlpha(int label, double alpha) { if (this.ovrLearners.keySet().size() > 1) { this.ovrLearners.get(label).setLabelAlpha(label, alpha); } else { this.ovrLearners.get(OTHER_LABEL).setLabelAlpha(label, alpha); } } @Override public Int2DoubleOpenHashMap getLabelAlphas() { Int2DoubleOpenHashMap labelAlphas = null; if (this.ovrLearners.keySet().size() > 1) { labelAlphas = new Int2DoubleOpenHashMap(); for (int l : this.labels) { T ovrLearner = ovrLearners.get(l); labelAlphas.put(l, ovrLearner.labelAlphas.get(l)); } } else { labelAlphas = this.ovrLearners.get(OTHER_LABEL).getLabelAlphas(); } return labelAlphas; } @Override public void setFeatureAlpha(int feature, int label, double alpha) { if (this.ovrLearners.keySet().size() > 1) { for (int l : this.labels) { int targetLabel = (l == label) ? label : OTHER_LABEL; this.ovrLearners.get(l).setFeatureAlpha(feature, targetLabel, alpha); } } else { this.ovrLearners.get(OTHER_LABEL).setFeatureAlpha(feature, label, alpha); } } @Override public Int2DoubleOpenHashMap getLabelMultipliers() { if (this.ovrLearners.keySet().size() > 1) { Int2DoubleOpenHashMap labelMultipliers = new Int2DoubleOpenHashMap(); for (int l : this.labels) { labelMultipliers.putAll(this.ovrLearners.get(l).getLabelMultipliers()); } // Remove OTHER_LABEL labelMultipliers.remove(OTHER_LABEL); return labelMultipliers; } else { return this.ovrLearners.get(OTHER_LABEL).getLabelMultipliers(); } } @Override public Int2ObjectMap<Int2DoubleOpenHashMap> getLabelledFeatures() { // TODO: Check if the statement below is true // As all classifiers have the same labelledFeatures (might be with different labels, but the actual features are the same) // we can just return the labelled features from *any* of the classifiers // TODO: This looks weird and ugly, can we do it differently? Iterator<T> iter = this.ovrLearners.values().iterator(); return iter.next().getLabelledFeatures(); } @Override public void trainOnInstance(int label, int[] features, double labelProbability, double weight) { if (this.ovrLearners.keySet().size() > 1) { /* * The specialist classifier for the given label needs to be positively trained on that instance * * The other classifier need to be negatively trained on that instance (that is with label=OTHER_LABEL) */ for (int l : this.labels) { int targetLabel = (l == label) ? label : OTHER_LABEL; this.ovrLearners.get(l).trainOnInstance(targetLabel, features, labelProbability, weight); } } else { this.ovrLearners.get(OTHER_LABEL).trainOnInstance(label, features, labelProbability, weight); } } @Override public void unlabelFeature(int feature, int label) { if (this.ovrLearners.keySet().size() > 1) { for (int l : this.labels) { int targetLabel = (l == label) ? label : OTHER_LABEL; this.ovrLearners.get(l).unlabelFeature(feature, targetLabel); } } else { this.ovrLearners.get(OTHER_LABEL).unlabelFeature(feature, label); } } @Override public void setLabelMultiplier(int label, double multiplier) { int targetLabel = (this.ovrLearners.keySet().size() > 1) ? label : OTHER_LABEL; this.ovrLearners.get(targetLabel).setLabelMultiplier(label, multiplier); } @Override public double likelihood(int feature, int label) { return (this.ovrLearners.keySet().size() > 1) ? this.ovrLearners.get(label).likelihood(feature, label) : this.ovrLearners.get(OTHER_LABEL).likelihood(feature, label); } @Override public void train(Iterable<ProcessedInstance> labelledDocuments, Iterable<ProcessedInstance> unlabelledDocuments) { if (this.labels.size() > 2) { this.trainOVRSemiSupervised(labelledDocuments, unlabelledDocuments); } else { this.trainBinarySemiSupervised(labelledDocuments, unlabelledDocuments); } } @Override public void train(Iterable<ProcessedInstance> labelledDocuments) { if (this.labels.size() > 2) { this.trainOVRSupervised(labelledDocuments); } else { this.trainBinarySupervised(labelledDocuments); } } @Override public IntSet getLabels() { return this.labels; } @Override public IntSet getVocab() { // All learners have the same vocab, so we just return the vocab of the first one return (this.ovrLearners.size() > 0 ? this.ovrLearners.get(0).getVocab() : null); } public Int2ObjectMap<T> getOvrLearners() { return this.ovrLearners; } @Override public Int2DoubleOpenHashMap logpriorPlusLoglikelihood(int[] features) { Int2DoubleOpenHashMap jll = new Int2DoubleOpenHashMap(); for (T learner : this.ovrLearners.values()) { jll.putAll(learner.logpriorPlusLoglikelihood(features)); } // Remove other label again jll.remove(OTHER_LABEL); return jll; } @Override public Int2DoubleMap labelPriors() { Int2DoubleMap priors = new Int2DoubleOpenHashMap(); for (T learner : this.ovrLearners.values()) { priors.putAll(learner.labelPriors()); } // Remove OTHER_LABEL priors.remove(OTHER_LABEL); return priors; } public Int2DoubleOpenHashMap predict(int[] features) { Int2DoubleOpenHashMap prediction = new Int2DoubleOpenHashMap(); for (T learner : this.ovrLearners.values()) { prediction.putAll(learner.predict(features)); } // Remove other label, so all that remains are the predictions for the existing labels prediction.remove(OTHER_LABEL); return prediction; } public int bestLabel(int[] features) { Int2DoubleMap prediction = this.predict(features); double maxPrediction = Double.MIN_VALUE; int bestLabel = -1; for (int key : prediction.keySet()) { if (prediction.get(key) > maxPrediction) { maxPrediction = prediction.get(key); bestLabel = key; } } return bestLabel; } private void trainBinarySupervised(Iterable<ProcessedInstance> labelledDocs) { this.ovrLearners.get(OTHER_LABEL).train(labelledDocs); } private void trainBinarySemiSupervised(Iterable<ProcessedInstance> labelledDocs, Iterable<ProcessedInstance> unlabelledDocuments) { this.ovrLearners.get(OTHER_LABEL).train(labelledDocs, unlabelledDocuments); } private void trainOVRSupervised(Iterable<ProcessedInstance> labelledDocs) { for (int l : this.labels) { T currLearner = this.ovrLearners.get(l); currLearner.train(this.binariseLabelledDocuments(labelledDocs, l)); } } private void trainOVRSemiSupervised(Iterable<ProcessedInstance> labelledDocs, Iterable<ProcessedInstance> unlabelledDocs) { for (int l : this.labels) { T currLearner = this.ovrLearners.get(l); currLearner.train(this.binariseLabelledDocuments(labelledDocs, l), unlabelledDocs); } } private Iterable<ProcessedInstance> binariseLabelledDocuments(Iterable<ProcessedInstance> labelledDocs, int currLabel) { List<ProcessedInstance> binarisedDocs = new ArrayList<>(); for (ProcessedInstance p : labelledDocs) { binarisedDocs.add(new ProcessedInstance((p.getLabel() == currLabel ? p.getLabel() : OTHER_LABEL), p.features, p.source)); } return binarisedDocs; } private void initOVRScheme() { try { Class[] typeArgs = {IntSet.class}; Constructor<T> constructor = this.learnerClass.getConstructor(typeArgs); if (this.labels.size() > 2) { for (int l : this.labels) { int[] binarisedLabels = {l, OTHER_LABEL}; Object[] args = {new IntOpenHashSet(binarisedLabels)}; this.ovrLearners.put(l, constructor.newInstance(args)); } } else { Object[] args = {this.labels}; this.ovrLearners.put(OTHER_LABEL, constructor.newInstance(args)); } } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } } }
src/main/java/uk/ac/susx/tag/classificationframework/classifiers/NaiveBayesOVRClassifier.java
package uk.ac.susx.tag.classificationframework.classifiers; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import it.unimi.dsi.fastutil.ints.*; import it.unimi.dsi.fastutil.objects.ObjectIterator; import uk.ac.susx.tag.classificationframework.datastructures.ProcessedInstance; import uk.ac.susx.tag.classificationframework.featureextraction.pipelines.FeatureExtractionPipeline; import java.io.*; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * Created by thk22 on 03/10/2014. * * NaiveBayes type specific OVR Classifier, inherits from NaiveBayesClassifier rather than OVRClassifier, because it * a) fulfils the contract of a NaiveBayesClassifier and * b) makes life downstream a lot easier * * Essentially it takes n NaiveBayesClassifiers and wraps them into a single new classifier, which is able to pretend to * be a NaiveBayesClassifier and handles all the differences internally. * * It is a schizophrenic creature meant to cause confusion and havoc! * (Thomas, 21.1.2015: It bloody does cause havoc, I didn't look at it for 2 months and it confuses the shit out of me...) * * On the downside of it inheriting from NaiveBayesClassifier rather than OVRClassifer is, it currently duplicates a fair bit of code already implemented in OVRClassifier which is identical to the stuff here. * Options for cleaning up that mess: * a) Dress up in a black tie suit, grab a monocle, a pocket watch and a glass of Brandy, mix with some Enterprise Architect people and philosophise about Java Design Patterns and Best Practices and come up with a super-corporatistic-over-engineered solution. * b) Delete OVRClassifier because its a prime example of pre-mature optimisation. * c) Live with a badly written codebase which is a *dream* to maintain and where future developers (and myself) will curse me and my children and my childrens children, etc, for being an absolute useless and substandard code monkey. * d) Something else. * * Note: Not all of the above statements are true anymore. * * Further Note: I went for option b), deleting the root of all evil, in the hopes of spreading some good karma across the whole project. (I will still keep the literary work above "as is", because its the only piece of documentation in this file) * */ public class NaiveBayesOVRClassifier<T extends NaiveBayesClassifier> extends NaiveBayesClassifier { private static final int OTHER_LABEL = Integer.MAX_VALUE; private static final String OTHER_LABEL_NAME = "__OVR_OTHER_LABEL__"; private Int2ObjectMap<T> ovrLearners; private Class<T> learnerClass; public NaiveBayesOVRClassifier(IntSet labels, Class<T> learnerClass) { super(labels); this.ovrLearners = new Int2ObjectOpenHashMap<>(); this.learnerClass = learnerClass; this.initOVRScheme(); } public NaiveBayesOVRClassifier(IntSet labels, Class<T> learnerClass, Int2ObjectMap<T> ovrLearners) { super(labels); this.ovrLearners = ovrLearners; this.learnerClass = learnerClass; } @Override protected void writeJsonIntSet(JsonWriter writer, FeatureExtractionPipeline pipeline, IntSet set, boolean areFeatures) throws IOException { if (areFeatures) super.writeJsonIntSet(writer, pipeline, set, areFeatures); else { writer.beginArray(); for (int i : set) { String labelString = (i == OTHER_LABEL) ? OTHER_LABEL_NAME : pipeline.labelString(i); writer.value(labelString); } writer.endArray(); } } @Override protected void writeJsonInt2DoubleMap(JsonWriter writer, FeatureExtractionPipeline pipeline, Int2DoubleOpenHashMap map, boolean areFeatures) throws IOException{ if (areFeatures) super.writeJsonInt2DoubleMap(writer, pipeline, map, areFeatures); else { writer.beginObject(); ObjectIterator<Int2DoubleMap.Entry> i = map.int2DoubleEntrySet().fastIterator(); while (i.hasNext()) { Int2DoubleMap.Entry entry = i.next(); String name = (entry.getIntKey() == OTHER_LABEL) ? OTHER_LABEL_NAME : pipeline.labelString(entry.getIntKey()); writer.name(name); writer.value(entry.getDoubleValue()); } writer.endObject(); } } @Override protected void writeJsonInt2ObjectMap(JsonWriter writer, FeatureExtractionPipeline pipeline, Int2ObjectMap<Int2DoubleOpenHashMap> map) throws IOException{ writer.beginObject(); for(Int2ObjectMap.Entry<Int2DoubleOpenHashMap> entry : map.int2ObjectEntrySet()){ String name = (entry.getIntKey() == OTHER_LABEL) ? OTHER_LABEL_NAME : pipeline.labelString(entry.getIntKey()); writer.name(name); writeJsonInt2DoubleMap(writer, pipeline, entry.getValue(), true); } writer.endObject(); } /* The values from all the indivdiual ovrLearners need to be propagated back to the NB Classifier that <this> object represents in order to make the serialisation work properly. Note that the NB Classifier that <this> object represents doesn't actually learn anything, its the ovrLearners it wraps that do the learning. Its a bit confusing to have the structure this way, but having the OVR Wrapper deriving the NB Classifier makes life downstream just so much easier. */ @Override public void writeJson(File out, FeatureExtractionPipeline pipeline) throws IOException { try (JsonWriter writer = new JsonWriter(new OutputStreamWriter(new FileOutputStream(out), "UTF-8"))) { writer.beginArray(); for (Integer l : this.ovrLearners.keySet()) { T ovrLearner = this.ovrLearners.get(l); writer.beginObject(); writer.name(l.toString()); writer.beginObject(); writer.name("labelSmoothing").value(ovrLearner.getLabelSmoothing()); writer.name("featureSmoothing").value(ovrLearner.getFeatureSmoothing()); writer.name("labelMultipliers"); writeJsonInt2DoubleMap(writer, pipeline, ovrLearner.labelMultipliers, false); writer.name("labels"); writeJsonIntSet(writer, pipeline, ovrLearner.labels, false); // TODO: needs its own writeJsonIntSet method writer.name("vocab"); writeJsonIntSet(writer, pipeline, ovrLearner.vocab, true); writer.name("docCounts"); writeJsonInt2DoubleMap(writer, pipeline, ovrLearner.docCounts, false); writer.name("labelCounts"); writeJsonInt2DoubleMap(writer, pipeline, ovrLearner.labelCounts, false); writer.name("jointCounts"); writeJsonInt2ObjectMap(writer, pipeline, ovrLearner.jointCounts); writer.name("labelFeatureAlphas"); writeJsonInt2ObjectMap(writer, pipeline, ovrLearner.labelFeatureAlphas); writer.name("featureAlphaTotals"); writeJsonInt2DoubleMap(writer, pipeline, ovrLearner.featureAlphaTotals, false); writer.name("labelAlphas"); writeJsonInt2DoubleMap(writer, pipeline, ovrLearner.labelAlphas, false); writer.name("empiricalLabelPriors").value(ovrLearner.empiricalLabelPriors); writer.endObject(); writer.endObject(); } writer.endArray(); } /* This works, v1 if (this.labels.size() > 2) { for (int l : this.ovrLearners.keySet()) { // Note, the shared variables (labelSmoothing, featureSmoothing, ...) are overridden with each iteration, this is a known uglyness and will be properly resolved once creativity (and motivation) return into town. T ovrLearner = this.ovrLearners.get(l); super.setLabelSmoothing(ovrLearner.getLabelSmoothing()); super.setFeatureSmoothing(ovrLearner.getFeatureSmoothing()); super.vocab = ovrLearner.vocab; super.empiricalLabelPriors = ovrLearner.empiricalLabelPriors; // Leave empty if empty, otherwise modify if (ovrLearner.labelMultipliers.containsKey(l)) { super.labelMultipliers.put(l, ovrLearner.labelMultipliers.get(l)); } if (ovrLearner.docCounts.containsKey(l)) { super.docCounts.put(l, ovrLearner.docCounts.get(l)); } if (ovrLearner.labelCounts.containsKey(l)) { super.labelCounts.put(l, ovrLearner.labelCounts.get(l)); } if (ovrLearner.jointCounts.containsKey(l)) { super.jointCounts.put(l, ovrLearner.jointCounts.get(l)); } if (ovrLearner.labelFeatureAlphas.containsKey(l)) { super.labelFeatureAlphas.put(l, ovrLearner.labelFeatureAlphas.get(l)); } if (ovrLearner.featureAlphaTotals.containsKey(l)) { super.featureAlphaTotals.put(l, ovrLearner.featureAlphaTotals.get(l)); } if (ovrLearner.labelAlphas.containsKey(l)) { super.labelAlphas.put(l, ovrLearner.labelAlphas.get(l)); } } } else { super.setLabelSmoothing(this.ovrLearners.get(OTHER_LABEL).getLabelSmoothing()); super.setFeatureSmoothing(this.ovrLearners.get(OTHER_LABEL).getFeatureSmoothing()); super.labelMultipliers = this.ovrLearners.get(OTHER_LABEL).labelMultipliers; super.labels = this.ovrLearners.get(OTHER_LABEL).labels; super.vocab = this.ovrLearners.get(OTHER_LABEL).vocab; super.docCounts = this.ovrLearners.get(OTHER_LABEL).docCounts; super.labelCounts = this.ovrLearners.get(OTHER_LABEL).labelCounts; super.jointCounts = this.ovrLearners.get(OTHER_LABEL).jointCounts; super.labelFeatureAlphas = this.ovrLearners.get(OTHER_LABEL).labelFeatureAlphas; super.featureAlphaTotals = this.ovrLearners.get(OTHER_LABEL).featureAlphaTotals; super.labelAlphas = this.ovrLearners.get(OTHER_LABEL).labelAlphas; super.empiricalLabelPriors = this.ovrLearners.get(OTHER_LABEL).empiricalLabelPriors; } super.writeJson(out, pipeline); */ } public static NaiveBayesOVRClassifier readJson(File in, FeatureExtractionPipeline pipeline, Class<? extends NaiveBayesClassifier> learnerClass) throws IOException { IntSet labels = null; // Re-create the OVR business by first reading in the labels and then constructing the OVR Setup from there try (JsonReader reader = new JsonReader(new InputStreamReader(new FileInputStream(in), "UTF-8"))) { reader.beginObject(); while (reader.hasNext()) { String name = reader.nextName(); switch (name) { // Don't worry; this is okay in Java 7 onwards case "labels": labels = NaiveBayesClassifier.readJsonIntSet(reader, pipeline, false); break; } } reader.endObject(); } NaiveBayesOVRClassifier<? extends NaiveBayesClassifier> nbOVR = new NaiveBayesOVRClassifier(labels, learnerClass); if (labels.size() > 2) { } else { // This NB Classifier acts as a proxy NaiveBayesClassifier nb = NaiveBayesClassifier.readJson(in, pipeline); } // TODO: Need to maintain a set of "otherCounts" for every attribute in the JSON to // properly initialise all of the OVR NB models Int2ObjectMap<Int2DoubleOpenHashMap> otherLabelMultipliers = new Int2ObjectOpenHashMap<>(); Int2ObjectMap<Int2DoubleOpenHashMap> otherDocCounts = new Int2ObjectOpenHashMap<>(); Int2ObjectMap<Int2DoubleOpenHashMap> otherLabelCounts = new Int2ObjectOpenHashMap<>(); Int2ObjectMap<Int2ObjectMap<Int2DoubleOpenHashMap>> otherJointCounts = new Int2ObjectOpenHashMap<>(); Int2ObjectMap<Int2ObjectMap<Int2DoubleOpenHashMap>> otherLabelFeatureAlphas = new Int2ObjectOpenHashMap<>(); Int2ObjectMap<Int2DoubleOpenHashMap> otherFeatureAlphaTotals = new Int2ObjectOpenHashMap<>(); Int2ObjectMap<Int2DoubleOpenHashMap> otherLabelAlphas = new Int2ObjectOpenHashMap<>(); for (int l : labels) { try (JsonReader reader = new JsonReader(new InputStreamReader(new FileInputStream(in), "UTF-8"))) { reader.beginObject(); while (reader.hasNext()) { String name = reader.nextName(); switch (name) { // Don't worry; this is okay in Java 7 onwards case "labelSmoothing": nbOVR.ovrLearners.get(l).setLabelSmoothing(reader.nextDouble()); break; case "featureSmoothing": nbOVR.ovrLearners.get(l).setFeatureSmoothing(reader.nextDouble()); break; case "labelMultipliers": { // TODO: Collect counts for other lables Int2DoubleOpenHashMap temp = readJsonInt2DoubleMap(reader, pipeline, false); for (int ll : labels) { if (ll == l) continue; otherLabelMultipliers.get(l).addTo(OTHER_LABEL, temp.get(ll)); } nbOVR.ovrLearners.get(l).labelMultipliers.put(l, temp.get(l)); nbOVR.ovrLearners.get(l).labelMultipliers.put(OTHER_LABEL, otherLabelMultipliers.get(l).get(OTHER_LABEL)); break; } case "labels": nbOVR.ovrLearners.get(l).labels = readJsonIntSet(reader, pipeline, false); break; case "vocab": nbOVR.ovrLearners.get(l).vocab = readJsonIntSet(reader, pipeline, false); break; case "docCounts": { Int2DoubleOpenHashMap temp = readJsonInt2DoubleMap(reader, pipeline, false); for (int ll : labels) { if (ll == l) continue; otherDocCounts.get(l).addTo(OTHER_LABEL, temp.get(ll)); } nbOVR.ovrLearners.get(l).docCounts.put(l, temp.get(l)); nbOVR.ovrLearners.get(l).docCounts.put(OTHER_LABEL, otherDocCounts.get(l).get(OTHER_LABEL)); break; } case "labelCounts": { Int2DoubleOpenHashMap temp = readJsonInt2DoubleMap(reader, pipeline, false); for (int ll : labels) { if (ll == l) continue; otherLabelCounts.get(l).addTo(OTHER_LABEL, temp.get(ll)); } nbOVR.ovrLearners.get(l).labelCounts.put(l, temp.get(l)); nbOVR.ovrLearners.get(l).labelCounts.put(OTHER_LABEL, otherLabelCounts.get(l).get(OTHER_LABEL)); break; } case "jointCounts": { /* Int2DoubleOpenHashMap temp = readJsonInt2DoubleMap(reader, pipeline, false); for (int ll : labels) { if (ll == l) continue; otherJointCounts.get(l).addTo(OTHER_LABEL, temp.get(ll)); } nbOVR.ovrLearners.get(l).jointCounts.put(l, temp.get(l)); nbOVR.ovrLearners.get(l).jointCounts.put(OTHER_LABEL, otherLabelCounts.get(l).get(OTHER_LABEL)); */ break; } case "labelFeatureAlphas": //nb.labelFeatureAlphas = readJsonInt2ObjectMap(reader, pipeline); break; case "featureAlphaTotals":{ Int2DoubleOpenHashMap temp = readJsonInt2DoubleMap(reader, pipeline, false); for (int ll : labels) { if (ll == l) continue; otherFeatureAlphaTotals.get(l).addTo(OTHER_LABEL, temp.get(ll)); } nbOVR.ovrLearners.get(l).featureAlphaTotals.put(l, temp.get(l)); nbOVR.ovrLearners.get(l).featureAlphaTotals.put(OTHER_LABEL, otherFeatureAlphaTotals.get(l).get(OTHER_LABEL)); break; } case "labelAlphas": { Int2DoubleOpenHashMap temp = readJsonInt2DoubleMap(reader, pipeline, false); for (int ll : labels) { if (ll == l) continue; otherLabelAlphas.get(l).addTo(OTHER_LABEL, temp.get(ll)); } nbOVR.ovrLearners.get(l).labelAlphas.put(l, temp.get(l)); nbOVR.ovrLearners.get(l).labelAlphas.put(OTHER_LABEL, otherLabelAlphas.get(l).get(OTHER_LABEL)); break; } case "empiricalLabelPriors": nbOVR.ovrLearners.get(l).empiricalLabelPriors = reader.nextBoolean(); break; } } reader.endObject(); } } return null; } @Override public void setLabelSmoothing(double smoothingValue) { for (int l : this.ovrLearners.keySet()) { this.ovrLearners.get(l).setLabelSmoothing(smoothingValue); } } @Override public void setFeatureSmoothing(double smoothingValue) { for (int l : this.ovrLearners.keySet()) { this.ovrLearners.get(l).setFeatureSmoothing(smoothingValue); } } @Override public void setLabelAlpha(int label, double alpha) { if (this.ovrLearners.keySet().size() > 1) { this.ovrLearners.get(label).setLabelAlpha(label, alpha); } else { this.ovrLearners.get(OTHER_LABEL).setLabelAlpha(label, alpha); } } @Override public Int2DoubleOpenHashMap getLabelAlphas() { Int2DoubleOpenHashMap labelAlphas = null; if (this.ovrLearners.keySet().size() > 1) { labelAlphas = new Int2DoubleOpenHashMap(); for (int l : this.labels) { T ovrLearner = ovrLearners.get(l); labelAlphas.put(l, ovrLearner.labelAlphas.get(l)); } } else { labelAlphas = this.ovrLearners.get(OTHER_LABEL).getLabelAlphas(); } return labelAlphas; } @Override public void setFeatureAlpha(int feature, int label, double alpha) { if (this.ovrLearners.keySet().size() > 1) { for (int l : this.labels) { int targetLabel = (l == label) ? label : OTHER_LABEL; this.ovrLearners.get(l).setFeatureAlpha(feature, targetLabel, alpha); } } else { this.ovrLearners.get(OTHER_LABEL).setFeatureAlpha(feature, label, alpha); } } @Override public Int2DoubleOpenHashMap getLabelMultipliers() { if (this.ovrLearners.keySet().size() > 1) { Int2DoubleOpenHashMap labelMultipliers = new Int2DoubleOpenHashMap(); for (int l : this.labels) { labelMultipliers.putAll(this.ovrLearners.get(l).getLabelMultipliers()); } // Remove OTHER_LABEL labelMultipliers.remove(OTHER_LABEL); return labelMultipliers; } else { return this.ovrLearners.get(OTHER_LABEL).getLabelMultipliers(); } } @Override public Int2ObjectMap<Int2DoubleOpenHashMap> getLabelledFeatures() { // TODO: Check if the statement below is true // As all classifiers have the same labelledFeatures (might be with different labels, but the actual features are the same) // we can just return the labelled features from *any* of the classifiers // TODO: This looks weird and ugly, can we do it differently? Iterator<T> iter = this.ovrLearners.values().iterator(); return iter.next().getLabelledFeatures(); } @Override public void trainOnInstance(int label, int[] features, double labelProbability, double weight) { if (this.ovrLearners.keySet().size() > 1) { /* * The specialist classifier for the given label needs to be positively trained on that instance * * The other classifier need to be negatively trained on that instance (that is with label=OTHER_LABEL) */ for (int l : this.labels) { int targetLabel = (l == label) ? label : OTHER_LABEL; this.ovrLearners.get(l).trainOnInstance(targetLabel, features, labelProbability, weight); } } else { this.ovrLearners.get(OTHER_LABEL).trainOnInstance(label, features, labelProbability, weight); } } @Override public void unlabelFeature(int feature, int label) { if (this.ovrLearners.keySet().size() > 1) { for (int l : this.labels) { int targetLabel = (l == label) ? label : OTHER_LABEL; this.ovrLearners.get(l).unlabelFeature(feature, targetLabel); } } else { this.ovrLearners.get(OTHER_LABEL).unlabelFeature(feature, label); } } @Override public void setLabelMultiplier(int label, double multiplier) { int targetLabel = (this.ovrLearners.keySet().size() > 1) ? label : OTHER_LABEL; this.ovrLearners.get(targetLabel).setLabelMultiplier(label, multiplier); } @Override public double likelihood(int feature, int label) { return (this.ovrLearners.keySet().size() > 1) ? this.ovrLearners.get(label).likelihood(feature, label) : this.ovrLearners.get(OTHER_LABEL).likelihood(feature, label); } @Override public void train(Iterable<ProcessedInstance> labelledDocuments, Iterable<ProcessedInstance> unlabelledDocuments) { if (this.labels.size() > 2) { this.trainOVRSemiSupervised(labelledDocuments, unlabelledDocuments); } else { this.trainBinarySemiSupervised(labelledDocuments, unlabelledDocuments); } } @Override public void train(Iterable<ProcessedInstance> labelledDocuments) { if (this.labels.size() > 2) { this.trainOVRSupervised(labelledDocuments); } else { this.trainBinarySupervised(labelledDocuments); } } @Override public IntSet getLabels() { return this.labels; } @Override public IntSet getVocab() { // All learners have the same vocab, so we just return the vocab of the first one return (this.ovrLearners.size() > 0 ? this.ovrLearners.get(0).getVocab() : null); } public Int2ObjectMap<T> getOvrLearners() { return this.ovrLearners; } @Override public Int2DoubleOpenHashMap logpriorPlusLoglikelihood(int[] features) { Int2DoubleOpenHashMap jll = new Int2DoubleOpenHashMap(); for (T learner : this.ovrLearners.values()) { jll.putAll(learner.logpriorPlusLoglikelihood(features)); } // Remove other label again jll.remove(OTHER_LABEL); return jll; } @Override public Int2DoubleMap labelPriors() { Int2DoubleMap priors = new Int2DoubleOpenHashMap(); for (T learner : this.ovrLearners.values()) { priors.putAll(learner.labelPriors()); } // Remove OTHER_LABEL priors.remove(OTHER_LABEL); return priors; } public Int2DoubleOpenHashMap predict(int[] features) { Int2DoubleOpenHashMap prediction = new Int2DoubleOpenHashMap(); for (T learner : this.ovrLearners.values()) { prediction.putAll(learner.predict(features)); } // Remove other label, so all that remains are the predictions for the existing labels prediction.remove(OTHER_LABEL); return prediction; } public int bestLabel(int[] features) { Int2DoubleMap prediction = this.predict(features); double maxPrediction = Double.MIN_VALUE; int bestLabel = -1; for (int key : prediction.keySet()) { if (prediction.get(key) > maxPrediction) { maxPrediction = prediction.get(key); bestLabel = key; } } return bestLabel; } private void trainBinarySupervised(Iterable<ProcessedInstance> labelledDocs) { this.ovrLearners.get(OTHER_LABEL).train(labelledDocs); } private void trainBinarySemiSupervised(Iterable<ProcessedInstance> labelledDocs, Iterable<ProcessedInstance> unlabelledDocuments) { this.ovrLearners.get(OTHER_LABEL).train(labelledDocs, unlabelledDocuments); } private void trainOVRSupervised(Iterable<ProcessedInstance> labelledDocs) { for (int l : this.labels) { T currLearner = this.ovrLearners.get(l); currLearner.train(this.binariseLabelledDocuments(labelledDocs, l)); } } private void trainOVRSemiSupervised(Iterable<ProcessedInstance> labelledDocs, Iterable<ProcessedInstance> unlabelledDocs) { for (int l : this.labels) { T currLearner = this.ovrLearners.get(l); currLearner.train(this.binariseLabelledDocuments(labelledDocs, l), unlabelledDocs); } } private Iterable<ProcessedInstance> binariseLabelledDocuments(Iterable<ProcessedInstance> labelledDocs, int currLabel) { List<ProcessedInstance> binarisedDocs = new ArrayList<>(); for (ProcessedInstance p : labelledDocs) { binarisedDocs.add(new ProcessedInstance((p.getLabel() == currLabel ? p.getLabel() : OTHER_LABEL), p.features, p.source)); } return binarisedDocs; } private void initOVRScheme() { try { Class[] typeArgs = {IntSet.class}; Constructor<T> constructor = this.learnerClass.getConstructor(typeArgs); if (this.labels.size() > 2) { for (int l : this.labels) { int[] binarisedLabels = {l, OTHER_LABEL}; Object[] args = {new IntOpenHashSet(binarisedLabels)}; this.ovrLearners.put(l, constructor.newInstance(args)); } } else { Object[] args = {this.labels}; this.ovrLearners.put(OTHER_LABEL, constructor.newInstance(args)); } } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } } }
fix for the 2 label case in the writeJson method
src/main/java/uk/ac/susx/tag/classificationframework/classifiers/NaiveBayesOVRClassifier.java
fix for the 2 label case in the writeJson method
Java
apache-2.0
716e8db229c528b27152782cccc59ea348b36209
0
killbill/killbill-api,maguero/killbill-api,killbill/killbill-api,maguero/killbill-api
/* * Copyright 2010-2013 Ning, Inc. * Copyright 2014 Groupon, Inc * Copyright 2014 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.payment.api; import java.util.List; import java.util.UUID; public interface PaymentMethodPlugin { /** * @return the id in Kill Bill */ public UUID getKbPaymentMethodId(); /** * @return the id from the plugin */ public String getExternalPaymentMethodId(); /** * @return whether plugin sees that PM as being the default */ public boolean isDefaultPaymentMethod(); /** * @return the list of custom properties set by the plugin */ public List<PluginProperty> getProperties(); }
src/main/java/org/killbill/billing/payment/api/PaymentMethodPlugin.java
/* * Copyright 2010-2013 Ning, Inc. * Copyright 2014 Groupon, Inc * Copyright 2014 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.payment.api; import java.util.List; import java.util.UUID; public interface PaymentMethodPlugin { /** * @return the id in Kill Bill */ public UUID getKbPaymentMethodId(); /** * @return the id from the plugin */ public String getExternalPaymentMethodId(); /** * @return whether plugin sees that PM as being the default */ public boolean isDefaultPaymentMethod(); /** * @return the list of custom properties set by the plugin */ public List<PluginProperty> getProperties(); /** * @return the payment method type name if applicable */ public String getType(); /** * @return the credit card name if applicable */ public String getCCName(); /** * @return the credit card type if applicable */ public String getCCType(); /** * @return the credit card expiration month */ public String getCCExpirationMonth(); /** * @return the credit card expiration year */ public String getCCExpirationYear(); /** * @return the credit card last 4 numbers */ public String getCCLast4(); /** * @return the address line 1 */ public String getAddress1(); /** * @return the address line 2 */ public String getAddress2(); /** * @return the city */ public String getCity(); /** * @return the state */ public String getState(); /** * @return the zip */ public String getZip(); /** * @return the country */ public String getCountry(); }
payment: remove CC specific details in PaymentMethodPlugin Signed-off-by: Pierre-Alexandre Meyer <[email protected]>
src/main/java/org/killbill/billing/payment/api/PaymentMethodPlugin.java
payment: remove CC specific details in PaymentMethodPlugin
Java
apache-2.0
2bfa2d13202b68203d13229729f0597257d75d11
0
slapperwan/gh4a,slapperwan/gh4a
package com.gh4a.fragment; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.MatrixCursor; import android.database.MergeCursor; import android.net.Uri; import android.os.Bundle; import android.support.annotation.LayoutRes; import android.support.annotation.Nullable; import android.support.annotation.StringRes; import android.support.v4.widget.CursorAdapter; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.SearchView; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.FilterQueryProvider; import android.widget.ImageView; import android.widget.Spinner; import android.widget.SpinnerAdapter; import android.widget.TextView; import com.gh4a.R; import com.gh4a.ServiceFactory; import com.gh4a.activities.FileViewerActivity; import com.gh4a.activities.RepositoryActivity; import com.gh4a.activities.UserActivity; import com.gh4a.adapter.RootAdapter; import com.gh4a.adapter.SearchAdapter; import com.gh4a.db.SuggestionsProvider; import com.gh4a.utils.ApiHelpers; import com.gh4a.utils.RxUtils; import com.gh4a.utils.StringUtils; import com.gh4a.utils.UiUtils; import com.meisolsson.githubsdk.model.Page; import com.meisolsson.githubsdk.model.Repository; import com.meisolsson.githubsdk.model.SearchCode; import com.meisolsson.githubsdk.model.TextMatch; import com.meisolsson.githubsdk.model.User; import com.meisolsson.githubsdk.service.search.SearchService; import io.reactivex.Single; import retrofit2.Response; public class SearchFragment extends PagedDataBaseFragment<Object> implements SearchView.OnQueryTextListener, SearchView.OnCloseListener, SearchView.OnSuggestionListener, FilterQueryProvider, AdapterView.OnItemSelectedListener, SearchAdapter.Callback { public static SearchFragment newInstance(int initialType, String initialQuery) { SearchFragment f = new SearchFragment(); Bundle args = new Bundle(); args.putInt("search_type", initialType); args.putString("initial_search", initialQuery); f.setArguments(args); return f; } private static final int SEARCH_TYPE_NONE = -1; public static final int SEARCH_TYPE_REPO = 0; public static final int SEARCH_TYPE_USER = 1; public static final int SEARCH_TYPE_CODE = 2; private static final int[][] HINT_AND_EMPTY_TEXTS = { { R.string.search_hint_repo, R.string.no_search_repos_found }, { R.string.search_hint_user, R.string.no_search_users_found }, { R.string.search_hint_code, R.string.no_search_code_found } }; private static final String[] SUGGESTION_PROJECTION = { SuggestionsProvider.Columns._ID, SuggestionsProvider.Columns.SUGGESTION }; private static final String SUGGESTION_SELECTION = SuggestionsProvider.Columns.TYPE + " = ? AND " + SuggestionsProvider.Columns.SUGGESTION + " LIKE ?"; private static final String SUGGESTION_ORDER = SuggestionsProvider.Columns.DATE + " DESC"; private static final String STATE_KEY_QUERY = "query"; private static final String STATE_KEY_SEARCH_TYPE = "search_type"; private SearchAdapter mAdapter; private Spinner mSearchType; private SearchView mSearch; private int mInitialSearchType; private int mSelectedSearchType = SEARCH_TYPE_NONE; private String mQuery; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); if (savedInstanceState != null) { mQuery = savedInstanceState.getString(STATE_KEY_QUERY); mInitialSearchType = savedInstanceState.getInt(STATE_KEY_SEARCH_TYPE, SEARCH_TYPE_NONE); } else { Bundle args = getArguments(); mInitialSearchType = args.getInt("search_type", SEARCH_TYPE_REPO); mQuery = args.getString("initial_search"); } } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.search, menu); mSearchType = (Spinner) menu.findItem(R.id.type).getActionView(); mSearchType.setAdapter(new SearchTypeAdapter(mSearchType.getContext(), getActivity())); mSearchType.setOnItemSelectedListener(this); if (mInitialSearchType != SEARCH_TYPE_NONE) { mSearchType.setSelection(mInitialSearchType); mInitialSearchType = SEARCH_TYPE_NONE; } SuggestionAdapter adapter = new SuggestionAdapter(getActivity()); adapter.setFilterQueryProvider(this); mSearch = (SearchView) menu.findItem(R.id.search).getActionView(); mSearch.setIconifiedByDefault(true); mSearch.requestFocus(); mSearch.onActionViewExpanded(); mSearch.setIconified(false); mSearch.setOnQueryTextListener(this); mSearch.setOnCloseListener(this); mSearch.setOnSuggestionListener(this); mSearch.setSuggestionsAdapter(adapter); if (mQuery != null) { mSearch.setQuery(mQuery, false); } updateSelectedSearchType(); super.onCreateOptionsMenu(menu, inflater); } @Override public void onSaveInstanceState(Bundle outState) { outState.putInt(STATE_KEY_SEARCH_TYPE, mSelectedSearchType); outState.putString(STATE_KEY_QUERY, mQuery); super.onSaveInstanceState(outState); } @Override protected RootAdapter<Object, ? extends RecyclerView.ViewHolder> onCreateAdapter() { mAdapter = new SearchAdapter(getActivity(), this); return mAdapter; } @Override protected Single<Response<Page<Object>>> loadPage(int page, boolean bypassCache) { if (TextUtils.isEmpty(mQuery) || mQuery.equals(getArguments().getString("initial_search"))) { return Single.just(Response.success(new ApiHelpers.DummyPage<>())); } int type = mInitialSearchType != SEARCH_TYPE_NONE ? mInitialSearchType : mSelectedSearchType; switch (type) { case SEARCH_TYPE_REPO: return makeRepoSearchSingle(page, bypassCache); case SEARCH_TYPE_USER: return makeUserSearchSingle(page, bypassCache); case SEARCH_TYPE_CODE: return makeCodeSearchSingle(page, bypassCache); } throw new IllegalStateException("Unexpected search type " + mSelectedSearchType); } @Override protected int getEmptyTextResId() { return 0; // will be updated later } @Override public void onItemClick(Object item) { if (item instanceof Repository) { Repository repository = (Repository) item; startActivity(RepositoryActivity.makeIntent(getActivity(), repository)); } else if (item instanceof SearchCode) { openFileViewer((SearchCode) item, -1); } else { User user = (User) item; startActivity(UserActivity.makeIntent(getActivity(), user)); } } @Override public boolean onQueryTextSubmit(String query) { mQuery = query; if (!StringUtils.isBlank(query)) { final ContentResolver cr = getActivity().getContentResolver(); final ContentValues cv = new ContentValues(); cv.put(SuggestionsProvider.Columns.TYPE, mSelectedSearchType); cv.put(SuggestionsProvider.Columns.SUGGESTION, query); cv.put(SuggestionsProvider.Columns.DATE, System.currentTimeMillis()); new Thread() { @Override public void run() { cr.insert(SuggestionsProvider.Columns.CONTENT_URI, cv); } }.start(); } loadResults(); return true; } @Override public boolean onQueryTextChange(String newText) { mQuery = newText; return true; } @Override public boolean onClose() { if (mAdapter != null) { mAdapter.clear(); } mQuery = null; return true; } @Override public boolean onSuggestionSelect(int position) { return false; } @Override public boolean onSuggestionClick(int position) { Cursor cursor = mSearch.getSuggestionsAdapter().getCursor(); if (cursor.moveToPosition(position)) { if (position == cursor.getCount() - 1) { final int type = mSelectedSearchType; final ContentResolver cr = getActivity().getContentResolver(); new Thread() { @Override public void run() { cr.delete(SuggestionsProvider.Columns.CONTENT_URI, SuggestionsProvider.Columns.TYPE + " = ?", new String[] { String.valueOf(type) }); } }.start(); } else { mQuery = cursor.getString(1); mSearch.setQuery(mQuery, false); } } return true; } @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { updateSelectedSearchType(); } @Override public void onNothingSelected(AdapterView<?> parent) { updateSelectedSearchType(); } @Override public void onSearchFragmentClick(SearchCode result, int matchIndex) { openFileViewer(result, matchIndex); } @Override public Cursor runQuery(CharSequence query) { if (TextUtils.isEmpty(query)) { return null; } return getContext().getContentResolver().query(SuggestionsProvider.Columns.CONTENT_URI, SUGGESTION_PROJECTION, SUGGESTION_SELECTION, new String[] { String.valueOf(mSelectedSearchType), query + "%" }, SUGGESTION_ORDER); } private void openFileViewer(SearchCode result, int matchIndex) { Repository repo = result.repository(); Uri uri = Uri.parse(result.url()); String ref = uri.getQueryParameter("ref"); TextMatch textMatch = matchIndex >= 0 ? result.textMatches().get(matchIndex) : null; startActivity(FileViewerActivity.makeIntentWithSearchMatch(getActivity(), repo.owner().login(), repo.name(), ref, result.path(), textMatch)); } private void loadResults() { mSearch.clearFocus(); onRefresh(); } private void updateSelectedSearchType() { int newType = mSearchType.getSelectedItemPosition(); if (newType == mSelectedSearchType) { return; } mSelectedSearchType = newType; mAdapter.setMode(newType); int[] hintAndEmptyTextResIds = HINT_AND_EMPTY_TEXTS[newType]; mSearch.setQueryHint(getString(hintAndEmptyTextResIds[0])); updateEmptyText(hintAndEmptyTextResIds[1]); updateEmptyState(); resetSubject(); // force re-filtering of the view mSearch.setQuery(mQuery, false); } private void updateEmptyText(@StringRes int emptyTextResId) { TextView emptyView = getView().findViewById(android.R.id.empty); emptyView.setText(emptyTextResId); } private Single<Response<Page<Object>>> makeRepoSearchSingle(long page, boolean bypassCache) { SearchService service = ServiceFactory.get(SearchService.class, bypassCache); String params = mQuery + " fork:true"; return service.searchRepositories(params, null, null, page) .compose(result -> RxUtils.<Repository, Object>searchPageAdapter(result, item -> item)) // With that status code, Github wants to tell us there are no // repositories to search in. Just pretend no error and return // an empty list in that case. .compose(RxUtils.mapFailureToValue(422, Response.success(new ApiHelpers.DummyPage<>()))); } private Single<Response<Page<Object>>> makeUserSearchSingle(long page, boolean bypassCache) { final SearchService service = ServiceFactory.get(SearchService.class, bypassCache); return service.searchUsers(mQuery, null, null, page) .compose(result -> RxUtils.<User, Object>searchPageAdapter(result, item -> item)); } private Single<Response<Page<Object>>> makeCodeSearchSingle(long page, boolean bypassCache) { SearchService service = ServiceFactory.get(SearchService.class, bypassCache, "application/vnd.github.v3.text-match+json", null, null); return service.searchCode(mQuery, null, null, page) .compose(result -> RxUtils.<SearchCode, Object>searchPageAdapter(result, item -> item)); } private static class SearchTypeAdapter extends BaseAdapter implements SpinnerAdapter { private final Context mContext; private final LayoutInflater mInflater; private final LayoutInflater mPopupInflater; private final int[][] mResources = new int[][] { { R.string.search_type_repo, R.drawable.icon_repositories_dark, R.attr.searchRepoIcon, 0 }, { R.string.search_type_user, R.drawable.search_users_dark, R.attr.searchUserIcon, 0 }, { R.string.search_type_code, R.drawable.search_code_dark, R.attr.searchCodeIcon, 0 } }; private SearchTypeAdapter(Context context, Context popupContext) { mContext = context; mInflater = LayoutInflater.from(context); mPopupInflater = LayoutInflater.from(popupContext); for (int i = 0; i < mResources.length; i++) { mResources[i][3] = UiUtils.resolveDrawable(popupContext, mResources[i][2]); } } @Override public int getCount() { return mResources.length; } @Override public CharSequence getItem(int position) { return mContext.getString(mResources[position][0]); } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = mInflater.inflate(R.layout.search_type_small, null); } ImageView icon = convertView.findViewById(R.id.icon); icon.setImageResource(mResources[position][1]); return convertView; } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = mPopupInflater.inflate(R.layout.search_type_popup, null); } ImageView icon = convertView.findViewById(R.id.icon); icon.setImageResource(mResources[position][3]); TextView label = convertView.findViewById(R.id.label); label.setText(mResources[position][0]); return convertView; } } private static class SuggestionAdapter extends CursorAdapter { private final LayoutInflater mInflater; public SuggestionAdapter(Context context) { super(context, null, false); mInflater = LayoutInflater.from(context); } @Override public Cursor swapCursor(Cursor newCursor) { if (newCursor != null && newCursor.getCount() > 0) { MatrixCursor clearRowCursor = new MatrixCursor(SUGGESTION_PROJECTION); clearRowCursor.addRow(new Object[] { Long.MAX_VALUE, mContext.getString(R.string.clear_suggestions) }); newCursor = new MergeCursor(new Cursor[] { newCursor, clearRowCursor }); } return super.swapCursor(newCursor); } @Override public int getItemViewType(int position) { return isClearRow(position) ? 1 : 0; } @Override public int getViewTypeCount() { return 2; } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { @LayoutRes int layoutResId = isClearRow(cursor.getPosition()) ? R.layout.row_suggestion_clear : R.layout.row_suggestion; return mInflater.inflate(layoutResId, parent, false); } @Override public void bindView(View view, Context context, Cursor cursor) { TextView textView = (TextView) view; int columnIndex = cursor.getColumnIndexOrThrow(SuggestionsProvider.Columns.SUGGESTION); textView.setText(cursor.getString(columnIndex)); } private boolean isClearRow(int position) { return position == getCount() - 1; } } }
app/src/main/java/com/gh4a/fragment/SearchFragment.java
package com.gh4a.fragment; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.MatrixCursor; import android.database.MergeCursor; import android.net.Uri; import android.os.Bundle; import android.support.annotation.LayoutRes; import android.support.annotation.Nullable; import android.support.annotation.StringRes; import android.support.v4.widget.CursorAdapter; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.SearchView; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.FilterQueryProvider; import android.widget.ImageView; import android.widget.Spinner; import android.widget.SpinnerAdapter; import android.widget.TextView; import com.gh4a.R; import com.gh4a.ServiceFactory; import com.gh4a.activities.FileViewerActivity; import com.gh4a.activities.RepositoryActivity; import com.gh4a.activities.UserActivity; import com.gh4a.adapter.RootAdapter; import com.gh4a.adapter.SearchAdapter; import com.gh4a.db.SuggestionsProvider; import com.gh4a.utils.ApiHelpers; import com.gh4a.utils.RxUtils; import com.gh4a.utils.StringUtils; import com.gh4a.utils.UiUtils; import com.meisolsson.githubsdk.model.Page; import com.meisolsson.githubsdk.model.Repository; import com.meisolsson.githubsdk.model.SearchCode; import com.meisolsson.githubsdk.model.TextMatch; import com.meisolsson.githubsdk.model.User; import com.meisolsson.githubsdk.service.search.SearchService; import io.reactivex.Single; import retrofit2.Response; public class SearchFragment extends PagedDataBaseFragment<Object> implements SearchView.OnQueryTextListener, SearchView.OnCloseListener, SearchView.OnSuggestionListener, FilterQueryProvider, AdapterView.OnItemSelectedListener, SearchAdapter.Callback { public static SearchFragment newInstance(int initialType, String initialQuery) { SearchFragment f = new SearchFragment(); Bundle args = new Bundle(); args.putInt("search_type", initialType); args.putString("initial_search", initialQuery); f.setArguments(args); return f; } private static final int SEARCH_TYPE_NONE = -1; public static final int SEARCH_TYPE_REPO = 0; public static final int SEARCH_TYPE_USER = 1; public static final int SEARCH_TYPE_CODE = 2; private static final int[][] HINT_AND_EMPTY_TEXTS = { { R.string.search_hint_repo, R.string.no_search_repos_found }, { R.string.search_hint_user, R.string.no_search_users_found }, { R.string.search_hint_code, R.string.no_search_code_found } }; private static final String[] SUGGESTION_PROJECTION = { SuggestionsProvider.Columns._ID, SuggestionsProvider.Columns.SUGGESTION }; private static final String SUGGESTION_SELECTION = SuggestionsProvider.Columns.TYPE + " = ? AND " + SuggestionsProvider.Columns.SUGGESTION + " LIKE ?"; private static final String SUGGESTION_ORDER = SuggestionsProvider.Columns.DATE + " DESC"; private static final String STATE_KEY_QUERY = "query"; private static final String STATE_KEY_SEARCH_TYPE = "search_type"; private SearchAdapter mAdapter; private Spinner mSearchType; private SearchView mSearch; private int mInitialSearchType; private int mSelectedSearchType = SEARCH_TYPE_NONE; private String mQuery; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); if (savedInstanceState != null) { mQuery = savedInstanceState.getString(STATE_KEY_QUERY); mInitialSearchType = savedInstanceState.getInt(STATE_KEY_SEARCH_TYPE, SEARCH_TYPE_NONE); } else { Bundle args = getArguments(); mInitialSearchType = args.getInt("search_type", SEARCH_TYPE_REPO); mQuery = args.getString("initial_search"); } } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.search, menu); mSearchType = (Spinner) menu.findItem(R.id.type).getActionView(); mSearchType.setAdapter(new SearchTypeAdapter(mSearchType.getContext(), getActivity())); mSearchType.setOnItemSelectedListener(this); if (mInitialSearchType != SEARCH_TYPE_NONE) { mSearchType.setSelection(mInitialSearchType); mInitialSearchType = SEARCH_TYPE_NONE; } SuggestionAdapter adapter = new SuggestionAdapter(getActivity()); adapter.setFilterQueryProvider(this); mSearch = (SearchView) menu.findItem(R.id.search).getActionView(); mSearch.setIconifiedByDefault(true); mSearch.requestFocus(); mSearch.onActionViewExpanded(); mSearch.setIconified(false); mSearch.setOnQueryTextListener(this); mSearch.setOnCloseListener(this); mSearch.setOnSuggestionListener(this); mSearch.setSuggestionsAdapter(adapter); if (mQuery != null) { mSearch.setQuery(mQuery, false); } updateSelectedSearchType(); super.onCreateOptionsMenu(menu, inflater); } @Override public void onSaveInstanceState(Bundle outState) { outState.putInt(STATE_KEY_SEARCH_TYPE, mSelectedSearchType); outState.putString(STATE_KEY_QUERY, mQuery); super.onSaveInstanceState(outState); } @Override protected RootAdapter<Object, ? extends RecyclerView.ViewHolder> onCreateAdapter() { mAdapter = new SearchAdapter(getActivity(), this); return mAdapter; } @Override protected Single<Response<Page<Object>>> loadPage(int page, boolean bypassCache) { if (TextUtils.isEmpty(mQuery)) { return Single.just(Response.success(new ApiHelpers.DummyPage<>())); } switch (mSelectedSearchType) { case SEARCH_TYPE_REPO: return makeRepoSearchSingle(page, bypassCache); case SEARCH_TYPE_USER: return makeUserSearchSingle(page, bypassCache); case SEARCH_TYPE_CODE: return makeCodeSearchSingle(page, bypassCache); } throw new IllegalStateException("Unexpected search type " + mSelectedSearchType); } @Override protected int getEmptyTextResId() { return 0; // will be updated later } @Override public void onItemClick(Object item) { if (item instanceof Repository) { Repository repository = (Repository) item; startActivity(RepositoryActivity.makeIntent(getActivity(), repository)); } else if (item instanceof SearchCode) { openFileViewer((SearchCode) item, -1); } else { User user = (User) item; startActivity(UserActivity.makeIntent(getActivity(), user)); } } @Override public boolean onQueryTextSubmit(String query) { mQuery = query; if (!StringUtils.isBlank(query)) { final ContentResolver cr = getActivity().getContentResolver(); final ContentValues cv = new ContentValues(); cv.put(SuggestionsProvider.Columns.TYPE, mSelectedSearchType); cv.put(SuggestionsProvider.Columns.SUGGESTION, query); cv.put(SuggestionsProvider.Columns.DATE, System.currentTimeMillis()); new Thread() { @Override public void run() { cr.insert(SuggestionsProvider.Columns.CONTENT_URI, cv); } }.start(); } loadResults(); return true; } @Override public boolean onQueryTextChange(String newText) { mQuery = newText; return true; } @Override public boolean onClose() { if (mAdapter != null) { mAdapter.clear(); } mQuery = null; return true; } @Override public boolean onSuggestionSelect(int position) { return false; } @Override public boolean onSuggestionClick(int position) { Cursor cursor = mSearch.getSuggestionsAdapter().getCursor(); if (cursor.moveToPosition(position)) { if (position == cursor.getCount() - 1) { final int type = mSelectedSearchType; final ContentResolver cr = getActivity().getContentResolver(); new Thread() { @Override public void run() { cr.delete(SuggestionsProvider.Columns.CONTENT_URI, SuggestionsProvider.Columns.TYPE + " = ?", new String[] { String.valueOf(type) }); } }.start(); } else { mQuery = cursor.getString(1); mSearch.setQuery(mQuery, false); } } return true; } @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { updateSelectedSearchType(); } @Override public void onNothingSelected(AdapterView<?> parent) { updateSelectedSearchType(); } @Override public void onSearchFragmentClick(SearchCode result, int matchIndex) { openFileViewer(result, matchIndex); } @Override public Cursor runQuery(CharSequence query) { if (TextUtils.isEmpty(query)) { return null; } return getContext().getContentResolver().query(SuggestionsProvider.Columns.CONTENT_URI, SUGGESTION_PROJECTION, SUGGESTION_SELECTION, new String[] { String.valueOf(mSelectedSearchType), query + "%" }, SUGGESTION_ORDER); } private void openFileViewer(SearchCode result, int matchIndex) { Repository repo = result.repository(); Uri uri = Uri.parse(result.url()); String ref = uri.getQueryParameter("ref"); TextMatch textMatch = matchIndex >= 0 ? result.textMatches().get(matchIndex) : null; startActivity(FileViewerActivity.makeIntentWithSearchMatch(getActivity(), repo.owner().login(), repo.name(), ref, result.path(), textMatch)); } private void loadResults() { mSearch.clearFocus(); onRefresh(); } private void updateSelectedSearchType() { int newType = mSearchType.getSelectedItemPosition(); if (newType == mSelectedSearchType) { return; } mSelectedSearchType = newType; mAdapter.setMode(newType); int[] hintAndEmptyTextResIds = HINT_AND_EMPTY_TEXTS[newType]; mSearch.setQueryHint(getString(hintAndEmptyTextResIds[0])); updateEmptyText(hintAndEmptyTextResIds[1]); updateEmptyState(); resetSubject(); // force re-filtering of the view mSearch.setQuery(mQuery, false); } private void updateEmptyText(@StringRes int emptyTextResId) { TextView emptyView = getView().findViewById(android.R.id.empty); emptyView.setText(emptyTextResId); } private Single<Response<Page<Object>>> makeRepoSearchSingle(long page, boolean bypassCache) { SearchService service = ServiceFactory.get(SearchService.class, bypassCache); String params = mQuery + " fork:true"; return service.searchRepositories(params, null, null, page) .compose(result -> RxUtils.<Repository, Object>searchPageAdapter(result, item -> item)) // With that status code, Github wants to tell us there are no // repositories to search in. Just pretend no error and return // an empty list in that case. .compose(RxUtils.mapFailureToValue(422, Response.success(new ApiHelpers.DummyPage<>()))); } private Single<Response<Page<Object>>> makeUserSearchSingle(long page, boolean bypassCache) { final SearchService service = ServiceFactory.get(SearchService.class, bypassCache); return service.searchUsers(mQuery, null, null, page) .compose(result -> RxUtils.<User, Object>searchPageAdapter(result, item -> item)); } private Single<Response<Page<Object>>> makeCodeSearchSingle(long page, boolean bypassCache) { SearchService service = ServiceFactory.get(SearchService.class, bypassCache, "application/vnd.github.v3.text-match+json", null, null); return service.searchCode(mQuery, null, null, page) .compose(result -> RxUtils.<SearchCode, Object>searchPageAdapter(result, item -> item)); } private static class SearchTypeAdapter extends BaseAdapter implements SpinnerAdapter { private final Context mContext; private final LayoutInflater mInflater; private final LayoutInflater mPopupInflater; private final int[][] mResources = new int[][] { { R.string.search_type_repo, R.drawable.icon_repositories_dark, R.attr.searchRepoIcon, 0 }, { R.string.search_type_user, R.drawable.search_users_dark, R.attr.searchUserIcon, 0 }, { R.string.search_type_code, R.drawable.search_code_dark, R.attr.searchCodeIcon, 0 } }; private SearchTypeAdapter(Context context, Context popupContext) { mContext = context; mInflater = LayoutInflater.from(context); mPopupInflater = LayoutInflater.from(popupContext); for (int i = 0; i < mResources.length; i++) { mResources[i][3] = UiUtils.resolveDrawable(popupContext, mResources[i][2]); } } @Override public int getCount() { return mResources.length; } @Override public CharSequence getItem(int position) { return mContext.getString(mResources[position][0]); } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = mInflater.inflate(R.layout.search_type_small, null); } ImageView icon = convertView.findViewById(R.id.icon); icon.setImageResource(mResources[position][1]); return convertView; } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = mPopupInflater.inflate(R.layout.search_type_popup, null); } ImageView icon = convertView.findViewById(R.id.icon); icon.setImageResource(mResources[position][3]); TextView label = convertView.findViewById(R.id.label); label.setText(mResources[position][0]); return convertView; } } private static class SuggestionAdapter extends CursorAdapter { private final LayoutInflater mInflater; public SuggestionAdapter(Context context) { super(context, null, false); mInflater = LayoutInflater.from(context); } @Override public Cursor swapCursor(Cursor newCursor) { if (newCursor != null && newCursor.getCount() > 0) { MatrixCursor clearRowCursor = new MatrixCursor(SUGGESTION_PROJECTION); clearRowCursor.addRow(new Object[] { Long.MAX_VALUE, mContext.getString(R.string.clear_suggestions) }); newCursor = new MergeCursor(new Cursor[] { newCursor, clearRowCursor }); } return super.swapCursor(newCursor); } @Override public int getItemViewType(int position) { return isClearRow(position) ? 1 : 0; } @Override public int getViewTypeCount() { return 2; } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { @LayoutRes int layoutResId = isClearRow(cursor.getPosition()) ? R.layout.row_suggestion_clear : R.layout.row_suggestion; return mInflater.inflate(layoutResId, parent, false); } @Override public void bindView(View view, Context context, Cursor cursor) { TextView textView = (TextView) view; int columnIndex = cursor.getColumnIndexOrThrow(SuggestionsProvider.Columns.SUGGESTION); textView.setText(cursor.getString(columnIndex)); } private boolean isClearRow(int position) { return position == getCount() - 1; } } }
Fix crash on 'search code in repo'. See #822
app/src/main/java/com/gh4a/fragment/SearchFragment.java
Fix crash on 'search code in repo'.
Java
apache-2.0
65cdd5aabba8a51363518acb243b21f3fadc3d33
0
camilesing/zstack,zsyzsyhao/zstack,winger007/zstack,mingjian2049/zstack,Alvin-Lau/zstack,AlanJinTS/zstack,WangXijue/zstack,HeathHose/zstack,AlanJager/zstack,zsyzsyhao/zstack,zstackorg/zstack,winger007/zstack,HeathHose/zstack,zstackio/zstack,Alvin-Lau/zstack,AlanJinTS/zstack,MatheMatrix/zstack,zstackorg/zstack,zstackio/zstack,zxwing/zstack-1,Alvin-Lau/zstack,MaJin1996/zstack,zxwing/zstack-1,hhjuliet/zstack,zxwing/zstack-1,WangXijue/zstack,hhjuliet/zstack,AlanJinTS/zstack,WangXijue/zstack,AlanJager/zstack,HeathHose/zstack,MatheMatrix/zstack,MaJin1996/zstack,zstackio/zstack,camilesing/zstack,mingjian2049/zstack,mingjian2049/zstack,MatheMatrix/zstack,liningone/zstack,liningone/zstack,liningone/zstack,camilesing/zstack,AlanJager/zstack
package org.zstack.header.vm; import org.zstack.header.core.ApiTimeout; import org.zstack.header.message.NeedReplyMessage; import java.util.List; /** * Created by david on 8/4/16. */ @ApiTimeout(apiClasses = {APICreateVmInstanceMsg.class}) public class CreateVmInstanceMsg extends NeedReplyMessage implements CreateVmInstanceMessage { private String accountUuid; private String name; private String imageUuid; private String instanceOfferingUuid; private int cpuNum; private long cpuSpeed; private long memorySize; private List<String> l3NetworkUuids; private String type; private String rootDiskOfferingUuid; private List<String> dataDiskOfferingUuids; private String zoneUuid; private String clusterUuid; private String hostUuid; private String description; private String resourceUuid; private String defaultL3NetworkUuid; private String allocatorStrategy; @Override public String getInstanceOfferingUuid() { return instanceOfferingUuid; } public void setInstanceOfferingUuid(String instanceOfferingUuid) { this.instanceOfferingUuid = instanceOfferingUuid; } @Override public String getDefaultL3NetworkUuid() { return defaultL3NetworkUuid; } public void setDefaultL3NetworkUuid(String defaultL3NetworkUuid) { this.defaultL3NetworkUuid = defaultL3NetworkUuid; } @Override public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @Override public String getHostUuid() { return hostUuid; } public void setHostUuid(String hostUuid) { this.hostUuid = hostUuid; } @Override public String getClusterUuid() { return clusterUuid; } public void setClusterUuid(String clusterUuid) { this.clusterUuid = clusterUuid; } @Override public String getZoneUuid() { return zoneUuid; } public void setZoneUuid(String zoneUuid) { this.zoneUuid = zoneUuid; } @Override public List<String> getDataDiskOfferingUuids() { return dataDiskOfferingUuids; } public void setDataDiskOfferingUuids(List<String> dataDiskOfferingUuids) { this.dataDiskOfferingUuids = dataDiskOfferingUuids; } @Override public String getRootDiskOfferingUuid() { return rootDiskOfferingUuid; } public void setRootDiskOfferingUuid(String rootDiskOfferingUuid) { this.rootDiskOfferingUuid = rootDiskOfferingUuid; } @Override public String getType() { return type; } public void setType(String type) { this.type = type; } @Override public List<String> getL3NetworkUuids() { return l3NetworkUuids; } public void setL3NetworkUuids(List<String> l3NetworkUuids) { this.l3NetworkUuids = l3NetworkUuids; } @Override public String getImageUuid() { return imageUuid; } public void setImageUuid(String imageUuid) { this.imageUuid = imageUuid; } @Override public int getCpuNum() { return cpuNum; } public void setCpuNum(int cpuNum) { this.cpuNum = cpuNum; } @Override public long getCpuSpeed() { return cpuSpeed; } public void setCpuSpeed(long cpuSpeed) { this.cpuSpeed = cpuSpeed; } @Override public long getMemorySize() { return memorySize; } public void setMemorySize(long memorySize) { this.memorySize = memorySize; } @Override public String getAllocatorStrategy() { return allocatorStrategy; } public void setAllocatorStrategy(String allocatorStrategy) { this.allocatorStrategy = allocatorStrategy; } @Override public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String getAccountUuid() { return accountUuid; } public void setAccountUuid(String accountUuid) { this.accountUuid = accountUuid; } @Override public String getResourceUuid() { return resourceUuid; } public void setResourceUuid(String resourceUuid) { this.resourceUuid = resourceUuid; } }
header/src/main/java/org/zstack/header/vm/CreateVmInstanceMsg.java
package org.zstack.header.vm; import org.zstack.header.message.NeedReplyMessage; import java.util.List; /** * Created by david on 8/4/16. */ public class CreateVmInstanceMsg extends NeedReplyMessage implements CreateVmInstanceMessage { private String accountUuid; private String name; private String imageUuid; private String instanceOfferingUuid; private int cpuNum; private long cpuSpeed; private long memorySize; private List<String> l3NetworkUuids; private String type; private String rootDiskOfferingUuid; private List<String> dataDiskOfferingUuids; private String zoneUuid; private String clusterUuid; private String hostUuid; private String description; private String resourceUuid; private String defaultL3NetworkUuid; private String allocatorStrategy; @Override public String getInstanceOfferingUuid() { return instanceOfferingUuid; } public void setInstanceOfferingUuid(String instanceOfferingUuid) { this.instanceOfferingUuid = instanceOfferingUuid; } @Override public String getDefaultL3NetworkUuid() { return defaultL3NetworkUuid; } public void setDefaultL3NetworkUuid(String defaultL3NetworkUuid) { this.defaultL3NetworkUuid = defaultL3NetworkUuid; } @Override public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @Override public String getHostUuid() { return hostUuid; } public void setHostUuid(String hostUuid) { this.hostUuid = hostUuid; } @Override public String getClusterUuid() { return clusterUuid; } public void setClusterUuid(String clusterUuid) { this.clusterUuid = clusterUuid; } @Override public String getZoneUuid() { return zoneUuid; } public void setZoneUuid(String zoneUuid) { this.zoneUuid = zoneUuid; } @Override public List<String> getDataDiskOfferingUuids() { return dataDiskOfferingUuids; } public void setDataDiskOfferingUuids(List<String> dataDiskOfferingUuids) { this.dataDiskOfferingUuids = dataDiskOfferingUuids; } @Override public String getRootDiskOfferingUuid() { return rootDiskOfferingUuid; } public void setRootDiskOfferingUuid(String rootDiskOfferingUuid) { this.rootDiskOfferingUuid = rootDiskOfferingUuid; } @Override public String getType() { return type; } public void setType(String type) { this.type = type; } @Override public List<String> getL3NetworkUuids() { return l3NetworkUuids; } public void setL3NetworkUuids(List<String> l3NetworkUuids) { this.l3NetworkUuids = l3NetworkUuids; } @Override public String getImageUuid() { return imageUuid; } public void setImageUuid(String imageUuid) { this.imageUuid = imageUuid; } @Override public int getCpuNum() { return cpuNum; } public void setCpuNum(int cpuNum) { this.cpuNum = cpuNum; } @Override public long getCpuSpeed() { return cpuSpeed; } public void setCpuSpeed(long cpuSpeed) { this.cpuSpeed = cpuSpeed; } @Override public long getMemorySize() { return memorySize; } public void setMemorySize(long memorySize) { this.memorySize = memorySize; } @Override public String getAllocatorStrategy() { return allocatorStrategy; } public void setAllocatorStrategy(String allocatorStrategy) { this.allocatorStrategy = allocatorStrategy; } @Override public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String getAccountUuid() { return accountUuid; } public void setAccountUuid(String accountUuid) { this.accountUuid = accountUuid; } @Override public String getResourceUuid() { return resourceUuid; } public void setResourceUuid(String resourceUuid) { this.resourceUuid = resourceUuid; } }
Add a missing @ApiTimeout decoration Signed-off-by: David Lee <[email protected]>
header/src/main/java/org/zstack/header/vm/CreateVmInstanceMsg.java
Add a missing @ApiTimeout decoration
Java
apache-2.0
56e64029098083471cce808643fb42548d3be2c5
0
neo4j-contrib/neo4j-apoc-procedures,neo4j-contrib/neo4j-apoc-procedures,neo4j-contrib/neo4j-apoc-procedures,neo4j-contrib/neo4j-apoc-procedures
import apoc.util.TestUtil; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.neo4j.configuration.GraphDatabaseSettings; import org.neo4j.test.rule.DbmsRule; import org.neo4j.test.rule.ImpermanentDbmsRule; import org.reflections.Reflections; import org.reflections.scanners.SubTypesScanner; import org.reflections.util.ConfigurationBuilder; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.stream.Collectors; import static apoc.ApocConfig.APOC_UUID_ENABLED; import static apoc.ApocConfig.apocConfig; import static org.junit.Assert.assertFalse; /** * @author ab-larus * @since 05.09.18 */ public class DocsTest { @Rule public DbmsRule db = new ImpermanentDbmsRule() .withSetting(GraphDatabaseSettings.auth_enabled, true); @Before public void setUp() throws Exception { apocConfig().setProperty(APOC_UUID_ENABLED, true); Set<Class<?>> allClasses = allClasses(); assertFalse(allClasses.isEmpty()); for (Class<?> klass : allClasses) { if(!klass.getName().endsWith("Test")) { TestUtil.registerProcedure(db, klass); } } new File("build/generated-documentation").mkdirs(); } static class Row { private String type; private String name; private String signature; private String description; public Row(String type, String name, String signature, String description) { this.type = type; this.name = name; this.signature = signature; this.description = description; } } @Test public void generateDocs() { // given List<Row> rows = new ArrayList<>(); List<Row> procedureRows = db.executeTransactionally("CALL dbms.procedures() YIELD signature, name, description WHERE name STARTS WITH 'apoc' RETURN 'procedure' AS type, name, description, signature ORDER BY signature", Collections.emptyMap(), result -> result.stream().map(record -> new Row( record.get("type").toString(), record.get("name").toString(), record.get("signature").toString(), record.get("description").toString()) ).collect(Collectors.toList())); rows.addAll(procedureRows); List<Row> functionRows = db.executeTransactionally("CALL dbms.functions() YIELD signature, name, description WHERE name STARTS WITH 'apoc' RETURN 'function' AS type, name, description, signature ORDER BY signature", Collections.emptyMap(), result -> result.stream().map(record -> new Row( record.get("type").toString(), record.get("name").toString(), record.get("signature").toString(), record.get("description").toString()) ).collect(Collectors.toList())); rows.addAll(functionRows); try (Writer writer = new OutputStreamWriter( new FileOutputStream( new File("build/generated-documentation/documentation.csv")), StandardCharsets.UTF_8 )) { writer.write("¦type¦qualified name¦signature¦description\n"); for (Row row : rows) { writer.write(String.format("¦%s¦%s¦%s¦%s\n", row.type, row.name, row.signature, row.description)); } } catch ( Exception e ) { throw new RuntimeException( e.getMessage(), e ); } Map<String, List<Row>> collect = rows.stream().collect(Collectors.groupingBy(value -> { String[] parts = value.name.split("\\."); parts = Arrays.copyOf(parts, parts.length - 1); return String.join(".", parts); })); for (Map.Entry<String, List<Row>> record : collect.entrySet()) { try (Writer writer = new OutputStreamWriter( new FileOutputStream( new File(String.format("build/generated-documentation/%s.csv", record.getKey()))), StandardCharsets.UTF_8 )) { writer.write("¦type¦qualified name¦signature¦description\n"); for (Row row : record.getValue()) { writer.write(String.format("¦%s¦%s¦%s¦%s\n", row.type, row.name, row.signature, row.description)); } } catch ( Exception e ) { throw new RuntimeException( e.getMessage(), e ); } } } private Set<Class<?>> allClasses() { Reflections reflections = new Reflections(new ConfigurationBuilder() .forPackages("apoc") .setScanners(new SubTypesScanner(false)) .filterInputsBy(input -> !input.endsWith("Test.class") && !input.endsWith("Result.class") && !input.contains("$")) ); return reflections.getSubTypesOf(Object.class); } }
src/test/java/DocsTest.java
import apoc.util.TestUtil; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.neo4j.configuration.GraphDatabaseSettings; import org.neo4j.test.rule.DbmsRule; import org.neo4j.test.rule.ImpermanentDbmsRule; import org.reflections.Reflections; import org.reflections.scanners.ResourcesScanner; import org.reflections.scanners.SubTypesScanner; import org.reflections.util.ClasspathHelper; import org.reflections.util.ConfigurationBuilder; import org.reflections.util.FilterBuilder; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.stream.Collectors; import static apoc.ApocConfig.APOC_UUID_ENABLED; import static apoc.ApocConfig.apocConfig; /** * @author ab-larus * @since 05.09.18 */ public class DocsTest { @Rule public DbmsRule db = new ImpermanentDbmsRule() .withSetting(GraphDatabaseSettings.auth_enabled, true); @Before public void setUp() throws Exception { apocConfig().setProperty(APOC_UUID_ENABLED, true); Set<Class<?>> allClasses = allClasses(); for (Class<?> klass : allClasses) { if(!klass.getName().endsWith("Test")) { TestUtil.registerProcedure(db, klass); } } new File("build/generated-documentation").mkdirs(); } static class Row { private String type; private String name; private String signature; private String description; public Row(String type, String name, String signature, String description) { this.type = type; this.name = name; this.signature = signature; this.description = description; } } @Test public void generateDocs() { // given List<Row> rows = new ArrayList<>(); List<Row> procedureRows = db.executeTransactionally("CALL dbms.procedures() YIELD signature, name, description WHERE name STARTS WITH 'apoc' RETURN 'procedure' AS type, name, description, signature ORDER BY signature", Collections.emptyMap(), result -> result.stream().map(record -> new Row( record.get("type").toString(), record.get("name").toString(), record.get("signature").toString(), record.get("description").toString()) ).collect(Collectors.toList())); rows.addAll(procedureRows); List<Row> functionRows = db.executeTransactionally("CALL dbms.functions() YIELD signature, name, description WHERE name STARTS WITH 'apoc' RETURN 'function' AS type, name, description, signature ORDER BY signature", Collections.emptyMap(), result -> result.stream().map(record -> new Row( record.get("type").toString(), record.get("name").toString(), record.get("signature").toString(), record.get("description").toString()) ).collect(Collectors.toList())); rows.addAll(functionRows); try (Writer writer = new OutputStreamWriter( new FileOutputStream( new File("build/generated-documentation/documentation.csv")), StandardCharsets.UTF_8 )) { writer.write("¦type¦qualified name¦signature¦description\n"); for (Row row : rows) { writer.write(String.format("¦%s¦%s¦%s¦%s\n", row.type, row.name, row.signature, row.description)); } } catch ( Exception e ) { throw new RuntimeException( e.getMessage(), e ); } Map<String, List<Row>> collect = rows.stream().collect(Collectors.groupingBy(value -> { String[] parts = value.name.split("\\."); parts = Arrays.copyOf(parts, parts.length - 1); return String.join(".", parts); })); for (Map.Entry<String, List<Row>> record : collect.entrySet()) { try (Writer writer = new OutputStreamWriter( new FileOutputStream( new File(String.format("build/generated-documentation/%s.csv", record.getKey()))), StandardCharsets.UTF_8 )) { writer.write("¦type¦qualified name¦signature¦description\n"); for (Row row : record.getValue()) { writer.write(String.format("¦%s¦%s¦%s¦%s\n", row.type, row.name, row.signature, row.description)); } } catch ( Exception e ) { throw new RuntimeException( e.getMessage(), e ); } } } private Set<Class<?>> allClasses() { List<ClassLoader> classLoadersList = new LinkedList<>(); classLoadersList.add(ClasspathHelper.contextClassLoader()); classLoadersList.add(ClasspathHelper.staticClassLoader()); Reflections reflections = new Reflections(new ConfigurationBuilder() .setScanners(new SubTypesScanner(false /* don't exclude Object.class */), new ResourcesScanner()) .setUrls(ClasspathHelper.forClassLoader(classLoadersList.toArray(new ClassLoader[0]))) .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix("apoc")))); return reflections.getSubTypesOf(Object.class); } }
fixing class scanning for generating signatures for docs
src/test/java/DocsTest.java
fixing class scanning for generating signatures for docs
Java
apache-2.0
8caa69c45c8839cc0cbb4c665d24e694417d7b74
0
liuyuanyuan/dbeaver,liuyuanyuan/dbeaver,AndrewKhitrin/dbeaver,ruspl-afed/dbeaver,ruspl-afed/dbeaver,liuyuanyuan/dbeaver,liuyuanyuan/dbeaver,AndrewKhitrin/dbeaver,ruspl-afed/dbeaver,ruspl-afed/dbeaver,liuyuanyuan/dbeaver,AndrewKhitrin/dbeaver,AndrewKhitrin/dbeaver
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2015 Serge Rieder ([email protected]) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License (version 2) * as published by the Free Software Foundation. * * This program 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 Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package org.jkiss.dbeaver.ui.dialogs.connection; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.wizard.Wizard; import org.eclipse.osgi.util.NLS; import org.eclipse.ui.INewWizard; import org.jkiss.code.NotNull; import org.jkiss.dbeaver.DBException; import org.jkiss.dbeaver.Log; import org.jkiss.dbeaver.core.CoreMessages; import org.jkiss.dbeaver.model.DBConstants; import org.jkiss.dbeaver.model.DBPConnectionConfiguration; import org.jkiss.dbeaver.model.DBPDataSource; import org.jkiss.dbeaver.model.DBPDataSourceInfo; import org.jkiss.dbeaver.model.exec.DBCExecutionPurpose; import org.jkiss.dbeaver.model.exec.DBCSession; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import org.jkiss.dbeaver.registry.DataSourceDescriptor; import org.jkiss.dbeaver.registry.DataSourceRegistry; import org.jkiss.dbeaver.registry.DriverDescriptor; import org.jkiss.dbeaver.runtime.DefaultProgressMonitor; import org.jkiss.dbeaver.runtime.jobs.ConnectJob; import org.jkiss.dbeaver.runtime.jobs.DisconnectJob; import org.jkiss.dbeaver.ui.UIUtils; import org.jkiss.dbeaver.utils.GeneralUtils; import org.jkiss.utils.CommonUtils; import java.lang.reflect.InvocationTargetException; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.util.HashMap; import java.util.Map; /** * Abstract connection wizard */ public abstract class ConnectionWizard extends Wizard implements INewWizard { static final Log log = Log.getLog(ConnectionWizard.class); // protected final IProject project; protected final DataSourceRegistry dataSourceRegistry; private final Map<DriverDescriptor, DataSourceDescriptor> infoMap = new HashMap<DriverDescriptor, DataSourceDescriptor>(); protected ConnectionWizard(DataSourceRegistry dataSourceRegistry) { setNeedsProgressMonitor(true); this.dataSourceRegistry = dataSourceRegistry; } @Override public void dispose() { // Dispose all temp data sources for (DataSourceDescriptor dataSource : infoMap.values()) { dataSource.dispose(); } super.dispose(); } public DataSourceRegistry getDataSourceRegistry() { return dataSourceRegistry; } abstract DriverDescriptor getSelectedDriver(); public abstract ConnectionPageSettings getPageSettings(); protected abstract void saveSettings(DataSourceDescriptor dataSource); @NotNull public DataSourceDescriptor getActiveDataSource() { DriverDescriptor driver = getSelectedDriver(); DataSourceDescriptor info = infoMap.get(driver); if (info == null) { DBPConnectionConfiguration connectionInfo = new DBPConnectionConfiguration(); info = new DataSourceDescriptor( getDataSourceRegistry(), DataSourceDescriptor.generateNewId(getSelectedDriver()), getSelectedDriver(), connectionInfo); info.getConnectionConfiguration().setClientHomeId(driver.getDefaultClientHomeId()); infoMap.put(driver, info); } return info; } public void testConnection() { DataSourceDescriptor dataSource = getPageSettings().getActiveDataSource(); DataSourceDescriptor testDataSource = new DataSourceDescriptor( dataSourceRegistry, dataSource.getId(), getSelectedDriver(), dataSource.getConnectionConfiguration()); try { saveSettings(testDataSource); final ConnectionTester op = new ConnectionTester(testDataSource); try { getContainer().run(true, true, new IRunnableWithProgress() { @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { // Wait for job to finish op.ownerMonitor = new DefaultProgressMonitor(monitor); op.schedule(); while (op.getState() == Job.WAITING || op.getState() == Job.RUNNING) { if (monitor.isCanceled()) { op.cancel(); throw new InterruptedException(); } try { Thread.sleep(50); } catch (InterruptedException e) { break; } } if (op.getConnectError() != null) { throw new InvocationTargetException(op.getConnectError()); } } }); String message = ""; if (!CommonUtils.isEmpty(op.productName)) { message += "Server: " + op.productName + " " + op.productVersion + "\n"; } if (!CommonUtils.isEmpty(op.driverName)) { message += "Driver: " + op.driverName + " " + op.driverVersion + "\n"; } if (!CommonUtils.isEmpty(message)) { message += "\n"; } message += NLS.bind(CoreMessages.dialog_connection_wizard_start_connection_monitor_connected, op.connectTime); MessageDialog.openInformation(getShell(), CoreMessages.dialog_connection_wizard_start_connection_monitor_success, message); } catch (InterruptedException ex) { UIUtils.showErrorDialog(getShell(), CoreMessages.dialog_connection_wizard_start_dialog_interrupted_title, CoreMessages.dialog_connection_wizard_start_dialog_interrupted_message); } catch (InvocationTargetException ex) { UIUtils.showErrorDialog( getShell(), CoreMessages.dialog_connection_wizard_start_dialog_error_title, null, GeneralUtils.makeExceptionStatus(ex.getTargetException())); } } finally { testDataSource.dispose(); } } public boolean isNew() { return false; } private class ConnectionTester extends ConnectJob { String productName; String productVersion; String driverName; String driverVersion; private boolean initOnTest; long startTime = -1; long connectTime = -1; DBRProgressMonitor ownerMonitor; public ConnectionTester(DataSourceDescriptor testDataSource) { super(testDataSource); setSystem(true); this.initOnTest = CommonUtils.toBoolean(testDataSource.getDriver().getDriverParameter(DBConstants.PARAM_INIT_ON_TEST)); productName = null; productVersion = null; } @Override public IStatus run(DBRProgressMonitor monitor) { if (ownerMonitor != null) { monitor = ownerMonitor; } monitor.beginTask(CoreMessages.dialog_connection_wizard_start_connection_monitor_start, 3); Thread.currentThread().setName(CoreMessages.dialog_connection_wizard_start_connection_monitor_thread); try { container.setName(container.getConnectionConfiguration().getUrl()); monitor.worked(1); startTime = System.currentTimeMillis(); super.run(monitor); connectTime = (System.currentTimeMillis() - startTime); if (connectError != null || monitor.isCanceled()) { return Status.OK_STATUS; } monitor.worked(1); DBPDataSource dataSource = container.getDataSource(); if (dataSource == null) { throw new DBException(CoreMessages.editors_sql_status_not_connected_to_database); } monitor.subTask(CoreMessages.dialog_connection_wizard_start_connection_monitor_subtask_test); DBPDataSourceInfo info = dataSource.getInfo(); if (info != null) { try { productName = info.getDatabaseProductName(); productVersion = info.getDatabaseProductVersion(); driverName = info.getDriverName(); driverVersion = info.getDriverVersion(); } catch (Exception e) { log.error("Can't obtain connection metadata", e); } } else { DBCSession session = dataSource.getDefaultContext(false).openSession(monitor, DBCExecutionPurpose.UTIL, "Test connection"); try { if (session instanceof Connection) { try { Connection connection = (Connection) session; DatabaseMetaData metaData = connection.getMetaData(); productName = metaData.getDatabaseProductName(); productVersion = metaData.getDatabaseProductVersion(); driverName = metaData.getDriverName(); driverVersion = metaData.getDriverVersion(); } catch (Exception e) { log.error("Can't obtain connection metadata", e); } } } finally { session.close(); } } new DisconnectJob(container).schedule(); monitor.subTask(CoreMessages.dialog_connection_wizard_start_connection_monitor_success); } catch (DBException ex) { connectError = ex; } monitor.done(); return Status.OK_STATUS; } } }
plugins/org.jkiss.dbeaver.core/src/org/jkiss/dbeaver/ui/dialogs/connection/ConnectionWizard.java
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2015 Serge Rieder ([email protected]) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License (version 2) * as published by the Free Software Foundation. * * This program 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 Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package org.jkiss.dbeaver.ui.dialogs.connection; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.wizard.Wizard; import org.eclipse.osgi.util.NLS; import org.eclipse.ui.INewWizard; import org.jkiss.code.NotNull; import org.jkiss.dbeaver.DBException; import org.jkiss.dbeaver.Log; import org.jkiss.dbeaver.core.CoreMessages; import org.jkiss.dbeaver.model.DBConstants; import org.jkiss.dbeaver.model.DBPConnectionConfiguration; import org.jkiss.dbeaver.model.DBPDataSource; import org.jkiss.dbeaver.model.DBPDataSourceInfo; import org.jkiss.dbeaver.model.exec.DBCExecutionPurpose; import org.jkiss.dbeaver.model.exec.DBCSession; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import org.jkiss.dbeaver.registry.DataSourceDescriptor; import org.jkiss.dbeaver.registry.DataSourceRegistry; import org.jkiss.dbeaver.registry.DriverDescriptor; import org.jkiss.dbeaver.runtime.DefaultProgressMonitor; import org.jkiss.dbeaver.runtime.jobs.ConnectJob; import org.jkiss.dbeaver.ui.UIUtils; import org.jkiss.dbeaver.utils.GeneralUtils; import org.jkiss.utils.CommonUtils; import java.lang.reflect.InvocationTargetException; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.util.HashMap; import java.util.Map; /** * Abstract connection wizard */ public abstract class ConnectionWizard extends Wizard implements INewWizard { static final Log log = Log.getLog(ConnectionWizard.class); // protected final IProject project; protected final DataSourceRegistry dataSourceRegistry; private final Map<DriverDescriptor, DataSourceDescriptor> infoMap = new HashMap<DriverDescriptor, DataSourceDescriptor>(); protected ConnectionWizard(DataSourceRegistry dataSourceRegistry) { setNeedsProgressMonitor(true); this.dataSourceRegistry = dataSourceRegistry; } @Override public void dispose() { // Dispose all temp data sources for (DataSourceDescriptor dataSource : infoMap.values()) { dataSource.dispose(); } super.dispose(); } public DataSourceRegistry getDataSourceRegistry() { return dataSourceRegistry; } abstract DriverDescriptor getSelectedDriver(); public abstract ConnectionPageSettings getPageSettings(); protected abstract void saveSettings(DataSourceDescriptor dataSource); @NotNull public DataSourceDescriptor getActiveDataSource() { DriverDescriptor driver = getSelectedDriver(); DataSourceDescriptor info = infoMap.get(driver); if (info == null) { DBPConnectionConfiguration connectionInfo = new DBPConnectionConfiguration(); info = new DataSourceDescriptor( getDataSourceRegistry(), DataSourceDescriptor.generateNewId(getSelectedDriver()), getSelectedDriver(), connectionInfo); info.getConnectionConfiguration().setClientHomeId(driver.getDefaultClientHomeId()); infoMap.put(driver, info); } return info; } public void testConnection() { DataSourceDescriptor dataSource = getPageSettings().getActiveDataSource(); DataSourceDescriptor testDataSource = new DataSourceDescriptor( dataSourceRegistry, dataSource.getId(), getSelectedDriver(), dataSource.getConnectionConfiguration()); try { saveSettings(testDataSource); final ConnectionTester op = new ConnectionTester(testDataSource); try { getContainer().run(true, true, new IRunnableWithProgress() { @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { // Wait for job to finish op.ownerMonitor = new DefaultProgressMonitor(monitor); op.schedule(); while (op.getState() == Job.WAITING || op.getState() == Job.RUNNING) { if (monitor.isCanceled()) { op.cancel(); throw new InterruptedException(); } try { Thread.sleep(50); } catch (InterruptedException e) { break; } } if (op.getConnectError() != null) { throw new InvocationTargetException(op.getConnectError()); } } }); String message = ""; if (!CommonUtils.isEmpty(op.productName)) { message += "Server: " + op.productName + " " + op.productVersion + "\n"; } if (!CommonUtils.isEmpty(op.driverName)) { message += "Driver: " + op.driverName + " " + op.driverVersion + "\n"; } if (!CommonUtils.isEmpty(message)) { message += "\n"; } message += NLS.bind(CoreMessages.dialog_connection_wizard_start_connection_monitor_connected, op.connectTime); MessageDialog.openInformation(getShell(), CoreMessages.dialog_connection_wizard_start_connection_monitor_success, message); } catch (InterruptedException ex) { UIUtils.showErrorDialog(getShell(), CoreMessages.dialog_connection_wizard_start_dialog_interrupted_title, CoreMessages.dialog_connection_wizard_start_dialog_interrupted_message); } catch (InvocationTargetException ex) { UIUtils.showErrorDialog( getShell(), CoreMessages.dialog_connection_wizard_start_dialog_error_title, null, GeneralUtils.makeExceptionStatus(ex.getTargetException())); } } finally { testDataSource.dispose(); } } public boolean isNew() { return false; } private class ConnectionTester extends ConnectJob { String productName; String productVersion; String driverName; String driverVersion; private boolean initOnTest; long startTime = -1; long connectTime = -1; DBRProgressMonitor ownerMonitor; public ConnectionTester(DataSourceDescriptor testDataSource) { super(testDataSource); setSystem(true); this.initOnTest = CommonUtils.toBoolean(testDataSource.getDriver().getDriverParameter(DBConstants.PARAM_INIT_ON_TEST)); productName = null; productVersion = null; } @Override public IStatus run(DBRProgressMonitor monitor) { if (ownerMonitor != null) { monitor = ownerMonitor; } monitor.beginTask(CoreMessages.dialog_connection_wizard_start_connection_monitor_start, 3); Thread.currentThread().setName(CoreMessages.dialog_connection_wizard_start_connection_monitor_thread); try { container.setName(container.getConnectionConfiguration().getUrl()); monitor.worked(1); startTime = System.currentTimeMillis(); super.run(monitor); connectTime = (System.currentTimeMillis() - startTime); if (connectError != null || monitor.isCanceled()) { return Status.OK_STATUS; } monitor.worked(1); DBPDataSource dataSource = container.getDataSource(); if (dataSource == null) { throw new DBException(CoreMessages.editors_sql_status_not_connected_to_database); } monitor.subTask(CoreMessages.dialog_connection_wizard_start_connection_monitor_subtask_test); DBPDataSourceInfo info = dataSource.getInfo(); if (info != null) { try { productName = info.getDatabaseProductName(); productVersion = info.getDatabaseProductVersion(); driverName = info.getDriverName(); driverVersion = info.getDriverVersion(); } catch (Exception e) { log.error("Can't obtain connection metadata", e); } } else { DBCSession session = dataSource.getDefaultContext(false).openSession(monitor, DBCExecutionPurpose.UTIL, "Test connection"); try { if (session instanceof Connection) { try { Connection connection = (Connection) session; DatabaseMetaData metaData = connection.getMetaData(); productName = metaData.getDatabaseProductName(); productVersion = metaData.getDatabaseProductVersion(); driverName = metaData.getDriverName(); driverVersion = metaData.getDriverVersion(); } catch (Exception e) { log.error("Can't obtain connection metadata", e); } } } finally { session.close(); } } try { monitor.subTask(CoreMessages.dialog_connection_wizard_start_connection_monitor_close); container.disconnect(monitor, false); } catch (DBException e) { // ignore it log.error(e); } finally { monitor.done(); } monitor.subTask(CoreMessages.dialog_connection_wizard_start_connection_monitor_success); } catch (DBException ex) { connectError = ex; } return Status.OK_STATUS; } } }
Connection test cancel implemented
plugins/org.jkiss.dbeaver.core/src/org/jkiss/dbeaver/ui/dialogs/connection/ConnectionWizard.java
Connection test cancel implemented
Java
apache-2.0
055fe76c00c14a9420e64adb28a721dd329c3452
0
Ks89/BYAManager,Ks89/BYAManager
/* Copyright 2011-2015 Stefano Cappa 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 logic; import gui.MainFrame; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.Socket; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import notification.Notification; import org.apache.commons.codec.digest.DigestUtils; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; import preferences.Settings; /** * Classe main */ public class BYAManager { private static int porta = 10378; private static final Logger LOGGER = LogManager.getLogger(BYAManager.class); /* * Da fare: * - RIFARE LA GUI CON JAVAFX E PIU' MODERNA * - Mettere controllo della sha1 se e' esadeciamale tramite un pattern. Per ora c'e' il codice commentato in CheckDBUpdate * - Controllo per far si che sia possibile scaricare un file solo se c'e' lo spazio disponibile nel disco (fatto, ma da testare) * - Aggiungere grafica personalizzata al popup nella systemtray * - Separare Gui dal download manager per poter avviare il DM dal main e quando si avvia la GUi farlo dal DM con invokelater * - Rimuovere la ncessita' di riavviare il programma dopo un aggiornamento dal file xml * - creare metodo a parte che valida il percorso inserito nella textfield del pannello preferenze * - prevedere 4 stati completed per l'insieme download, in modo da avvisare nella tabella quanti sono i thread in corso (magari solo se abilitata voce in preferenze) * - Eliminare il bordo nel jwindow * - Migliorare aspetto spostando meglio componenti * - Rimuovere menu donazioni ed inserire il pulsante nella grafica * - Aggiungere pulsanti twitter, facebook, youtube, link al sito ecc.. per ks89 e BYA */ /** * Metodo main per eseguire il programma. * @param args */ public static void main(String[] args) { //deve essere sempre la prima riga, in modo che questa propieta' venga //impostata nel thread principale e non in quello di swing. System.setProperty("apple.laf.useScreenMenuBar", "true"); if(System.getProperty("os.name").contains("Mac")) { System.setProperty("com.apple.mrj.application.apple.menu.about.name", "BYAManager"); } //inizializzo la gestione della splashscreen (usa singleton) SplashScreenManager.getInstance(); try { UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) { LOGGER.error("main() - Eccezione nell'impostare il look and feel = " + e); } //carico subito le preferenze per impostare la lingua Settings.getInstance().initSettings(); //dopo crea gli elementi della gui delle preferenze assegnandogli il nome nella lingua giusta Settings.getInstance().createAndAssignGuiElements(); //ora vi accedo in modo statico per tutti il programma (riottenendo eventualmente l'istanza) SplashScreenManager.mostraSplash(); SplashScreenManager.setText("starting"); //per impostare manualmente la porta if(args.length>0) { porta = (Integer) (new CommandLineParser(args[0])).interpretaComando(); System.out.println("Porta ricevuta: " + porta); } // try { // InputStream bya= new FileInputStream("/Users/Ks89/Desktop/BYA/cartella senza titolo/BYAManager.jar"); // System.out.println(" sha512 bya " + DigestUtils.sha512Hex(bya)); // InputStream bya2= new FileInputStream("/Users/Ks89/Desktop/BYA/BYAUpdater.jar"); // System.out.println(" sha512 updater " + DigestUtils.sha512Hex(bya2)); // } catch (FileNotFoundException e1) { // e1.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } ServerSingleInstance ssi = null; try { System.out.println("Porta impostata: " + porta); new Socket("localhost", porta); Notification.showNormalOptionPane("mainNoMultipleInstance"); System.exit(1); } catch (IOException e) { ssi = new ServerSingleInstance(porta); ssi.start(); } finally { SwingUtilities.invokeLater(MainFrame.getInstance()); //inizializzo la grafica DownloadManager.getInstance().run(); //inizializzo la logica } } /** * Metodo per avviare questo file jar dall'updater. Non c'e' differenza * ma mi server per tracciare con il loggere il diverso metodo di avvio */ public void avviaDaUpdater() { LOGGER.info("Richiesto avvio da Updater"); Notification.showNormalOptionPane("mainThanksForUpdate"); BYAManager.main(new String[1]); } }
ByaManager/src/main/java/logic/BYAManager.java
/* Copyright 2011-2015 Stefano Cappa 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 logic; import gui.MainFrame; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.Socket; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import notification.Notification; import org.apache.commons.codec.digest.DigestUtils; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; import preferences.Settings; /** * Classe main */ public class BYAManager { private static int porta = 10378; private static final Logger LOGGER = LogManager.getLogger(BYAManager.class); /* * Da fare: * - Mettere controllo della sha1 se e' esadeciamale tramite un pattern. Per ora c'e' il codice commentato in CheckDBUpdate * - Controllo per far si che sia possibile scaricare un file solo se c'e' lo spazio disponibile nel disco (fatto, ma da testare) * - Aggiungere grafica personalizzata al popup nella systemtray * - Separare Gui dal download manager per poter avviare il DM dal main e quando si avvia la GUi farlo dal DM con invokelater * - Rimuovere la ncessita' di riavviare il programma dopo un aggiornamento dal file xml * - creare metodo a parte che valida il percorso inserito nella textfield del pannello preferenze * - prevedere 4 stati completed per l'insieme download, in modo da avvisare nella tabella quanti sono i thread in corso (magari solo se abilitata voce in preferenze) * - Eliminare il bordo nel jwindow * - Migliorare aspetto spostando meglio componenti * - Rimuovere menu donazioni ed inserire il pulsante nella grafica * - Aggiungere pulsanti twitter, facebook, youtube, link al sito ecc.. per ks89 e BYA */ /** * Metodo main per eseguire il programma. * @param args */ public static void main(String[] args) { //deve essere sempre la prima riga, in modo che questa propieta' venga //impostata nel thread principale e non in quello di swing. System.setProperty("apple.laf.useScreenMenuBar", "true"); if(System.getProperty("os.name").contains("Mac")) { System.setProperty("com.apple.mrj.application.apple.menu.about.name", "BYAManager"); } //inizializzo la gestione della splashscreen (usa singleton) SplashScreenManager.getInstance(); try { UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) { LOGGER.error("main() - Eccezione nell'impostare il look and feel = " + e); } //carico subito le preferenze per impostare la lingua Settings.getInstance().initSettings(); //dopo crea gli elementi della gui delle preferenze assegnandogli il nome nella lingua giusta Settings.getInstance().createAndAssignGuiElements(); //ora vi accedo in modo statico per tutti il programma (riottenendo eventualmente l'istanza) SplashScreenManager.mostraSplash(); SplashScreenManager.setText("starting"); //per impostare manualmente la porta if(args.length>0) { porta = (Integer) (new CommandLineParser(args[0])).interpretaComando(); System.out.println("Porta ricevuta: " + porta); } // try { // InputStream bya= new FileInputStream("/Users/Ks89/Desktop/BYA/cartella senza titolo/BYAManager.jar"); // System.out.println(" sha512 bya " + DigestUtils.sha512Hex(bya)); // InputStream bya2= new FileInputStream("/Users/Ks89/Desktop/BYA/BYAUpdater.jar"); // System.out.println(" sha512 updater " + DigestUtils.sha512Hex(bya2)); // } catch (FileNotFoundException e1) { // e1.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } ServerSingleInstance ssi = null; try { System.out.println("Porta impostata: " + porta); new Socket("localhost", porta); Notification.showNormalOptionPane("mainNoMultipleInstance"); System.exit(1); } catch (IOException e) { ssi = new ServerSingleInstance(porta); ssi.start(); } finally { SwingUtilities.invokeLater(MainFrame.getInstance()); //inizializzo la grafica DownloadManager.getInstance().run(); //inizializzo la logica } } /** * Metodo per avviare questo file jar dall'updater. Non c'e' differenza * ma mi server per tracciare con il loggere il diverso metodo di avvio */ public void avviaDaUpdater() { LOGGER.info("Richiesto avvio da Updater"); Notification.showNormalOptionPane("mainThanksForUpdate"); BYAManager.main(new String[1]); } }
commit inutile
ByaManager/src/main/java/logic/BYAManager.java
commit inutile
Java
artistic-2.0
e9de45a8e24cb46b0b2331e521d3f664591122ce
0
BenArunski/RefactoringGoodness
private static final Map<Integer, Integer> classificationHeight = new HashMap<>(); static { classificationHeight.put(NpacsConstants.CLASSIFICATION_CBI, 50); classificationHeight.put(NpacsConstants.CLASSIFICATION_SEX_OFFENDER, 50); classificationHeight.put(NpacsConstants.CLASSIFICATION_DOMESTIC_VIOLENCE, 50); classificationHeight.put(NpacsConstants.CLASSIFICATION_SSAS, 50); classificationHeight.put(NpacsConstants.CLASSIFICATION_PSC_ADULT, 50); classificationHeight.put(NpacsConstants.CLASSIFICATION_WEC, 50); classificationHeight.put(NpacsConstants.CLASSIFICATION_CBI_DUI, 50); classificationHeight.put(NpacsConstants.CLASSIFICATION_CBR_MEDIUM_HIGH, 40); classificationHeight.put(NpacsConstants.CLASSIFICATION_CBR_MEDIUM_LOW, 30); classificationHeight.put(NpacsConstants.CLASSIFICATION_CBR_LOW, 20); classificationHeight.put(NpacsConstants.CLASSIFICATION_CBR_ADMIN_OVERRIDE_VL, 10); classificationHeight.put(NpacsConstants.CLASSIFICATION_JCBI, 30); classificationHeight.put(NpacsConstants.CLASSIFICATION_JSH, 30); classificationHeight.put(NpacsConstants.CLASSIFICATION_3_B, 30); classificationHeight.put(NpacsConstants.CLASSIFICATION_PSC_JUVENILE, 30); classificationHeight.put(NpacsConstants.CLASSIFICATION_JCBR_LOW_MODERATE, 20); classificationHeight.put(NpacsConstants.CLASSIFICATION_JCBR_LOW, 10); } public boolean isNewClassificationHigher(Integer currentClassificationCd, Integer newClassificationCd) { return currentClassificationCd != null && newClassificationCd != null && classificationHeight.get(newClassificationCd) > classificationHeight.get(currentClassificationCd); } public boolean isNewClassificationEqualOrLower(Integer currentClassificationCd, Integer newClassificationCd) { return currentClassificationCd != null && newClassificationCd != null && classificationHeight.get(newClassificationCd) <= classificationHeight.get(currentClassificationCd); } public boolean isNewClassificationEqualOrHigher(Integer currentClassificationCd, Integer newClassificationCd) { return currentClassificationCd != null && newClassificationCd != null && classificationHeight.get(newClassificationCd) >= classificationHeight.get(currentClassificationCd); }
20160912_Capstone_compareClassifications/CaseManagementService.java
public boolean isNewClassificationHigher(Integer currentClassificationCd, Integer newClassificationCd) { boolean isHigher = false; if (currentClassificationCd != null && newClassificationCd != null) { switch (currentClassificationCd) { case NpacsConstants.CLASSIFICATION_CBI: case NpacsConstants.CLASSIFICATION_SEX_OFFENDER: case NpacsConstants.CLASSIFICATION_DOMESTIC_VIOLENCE: case NpacsConstants.CLASSIFICATION_SSAS: case NpacsConstants.CLASSIFICATION_PSC_ADULT: case NpacsConstants.CLASSIFICATION_WEC: case NpacsConstants.CLASSIFICATION_CBI_DUI: isHigher = false; break; case NpacsConstants.CLASSIFICATION_CBR_MEDIUM_HIGH: switch (newClassificationCd) { case NpacsConstants.CLASSIFICATION_CBI: case NpacsConstants.CLASSIFICATION_SEX_OFFENDER: case NpacsConstants.CLASSIFICATION_DOMESTIC_VIOLENCE: case NpacsConstants.CLASSIFICATION_SSAS: case NpacsConstants.CLASSIFICATION_PSC_ADULT: case NpacsConstants.CLASSIFICATION_WEC: case NpacsConstants.CLASSIFICATION_CBI_DUI: isHigher = true; break; } break; case NpacsConstants.CLASSIFICATION_CBR_MEDIUM_LOW: switch (newClassificationCd) { case NpacsConstants.CLASSIFICATION_CBI: case NpacsConstants.CLASSIFICATION_SEX_OFFENDER: case NpacsConstants.CLASSIFICATION_DOMESTIC_VIOLENCE: case NpacsConstants.CLASSIFICATION_SSAS: case NpacsConstants.CLASSIFICATION_PSC_ADULT: case NpacsConstants.CLASSIFICATION_WEC: case NpacsConstants.CLASSIFICATION_CBI_DUI: case NpacsConstants.CLASSIFICATION_CBR_MEDIUM_HIGH: isHigher = true; break; } break; case NpacsConstants.CLASSIFICATION_CBR_LOW: switch (newClassificationCd) { case NpacsConstants.CLASSIFICATION_CBI: case NpacsConstants.CLASSIFICATION_SEX_OFFENDER: case NpacsConstants.CLASSIFICATION_DOMESTIC_VIOLENCE: case NpacsConstants.CLASSIFICATION_SSAS: case NpacsConstants.CLASSIFICATION_PSC_ADULT: case NpacsConstants.CLASSIFICATION_WEC: case NpacsConstants.CLASSIFICATION_CBI_DUI: case NpacsConstants.CLASSIFICATION_CBR_MEDIUM_HIGH: case NpacsConstants.CLASSIFICATION_CBR_MEDIUM_LOW: isHigher = true; break; } break; case NpacsConstants.CLASSIFICATION_CBR_ADMIN_OVERRIDE_VL: switch (newClassificationCd) { case NpacsConstants.CLASSIFICATION_CBI: case NpacsConstants.CLASSIFICATION_SEX_OFFENDER: case NpacsConstants.CLASSIFICATION_DOMESTIC_VIOLENCE: case NpacsConstants.CLASSIFICATION_SSAS: case NpacsConstants.CLASSIFICATION_PSC_ADULT: case NpacsConstants.CLASSIFICATION_WEC: case NpacsConstants.CLASSIFICATION_CBI_DUI: case NpacsConstants.CLASSIFICATION_CBR_MEDIUM_HIGH: case NpacsConstants.CLASSIFICATION_CBR_MEDIUM_LOW: case NpacsConstants.CLASSIFICATION_CBR_LOW: isHigher = true; break; } break; case NpacsConstants.CLASSIFICATION_JCBI: case NpacsConstants.CLASSIFICATION_JSH: case NpacsConstants.CLASSIFICATION_3_B: case NpacsConstants.CLASSIFICATION_PSC_JUVENILE: isHigher = false; break; case NpacsConstants.CLASSIFICATION_JCBR_LOW_MODERATE: switch (newClassificationCd) { case NpacsConstants.CLASSIFICATION_JCBI: case NpacsConstants.CLASSIFICATION_JSH: case NpacsConstants.CLASSIFICATION_3_B: case NpacsConstants.CLASSIFICATION_PSC_JUVENILE: isHigher = true; break; } break; case NpacsConstants.CLASSIFICATION_JCBR_LOW: switch (newClassificationCd) { case NpacsConstants.CLASSIFICATION_JCBI: case NpacsConstants.CLASSIFICATION_JSH: case NpacsConstants.CLASSIFICATION_3_B: case NpacsConstants.CLASSIFICATION_PSC_JUVENILE: case NpacsConstants.CLASSIFICATION_JCBR_LOW_MODERATE: isHigher = true; break; } break; } } return isHigher; } public boolean isNewClassificationEqualOrLower( Integer currentClassificationCd, Integer newClassificationCd) { boolean isEqualOrLower = false; if (currentClassificationCd != null && newClassificationCd != null) { switch (currentClassificationCd) { case NpacsConstants.CLASSIFICATION_CBI: case NpacsConstants.CLASSIFICATION_SEX_OFFENDER: case NpacsConstants.CLASSIFICATION_DOMESTIC_VIOLENCE: case NpacsConstants.CLASSIFICATION_SSAS: case NpacsConstants.CLASSIFICATION_PSC_ADULT: case NpacsConstants.CLASSIFICATION_WEC: case NpacsConstants.CLASSIFICATION_CBI_DUI: isEqualOrLower = true; break; case NpacsConstants.CLASSIFICATION_CBR_MEDIUM_HIGH: switch (newClassificationCd) { case NpacsConstants.CLASSIFICATION_CBI: case NpacsConstants.CLASSIFICATION_SEX_OFFENDER: case NpacsConstants.CLASSIFICATION_DOMESTIC_VIOLENCE: case NpacsConstants.CLASSIFICATION_SSAS: case NpacsConstants.CLASSIFICATION_PSC_ADULT: case NpacsConstants.CLASSIFICATION_WEC: case NpacsConstants.CLASSIFICATION_CBI_DUI: isEqualOrLower = false; break; default: isEqualOrLower = true; break; } break; case NpacsConstants.CLASSIFICATION_CBR_MEDIUM_LOW: switch (newClassificationCd) { case NpacsConstants.CLASSIFICATION_CBI: case NpacsConstants.CLASSIFICATION_SEX_OFFENDER: case NpacsConstants.CLASSIFICATION_DOMESTIC_VIOLENCE: case NpacsConstants.CLASSIFICATION_SSAS: case NpacsConstants.CLASSIFICATION_PSC_ADULT: case NpacsConstants.CLASSIFICATION_WEC: case NpacsConstants.CLASSIFICATION_CBI_DUI: case NpacsConstants.CLASSIFICATION_CBR_MEDIUM_HIGH: isEqualOrLower = false; break; default: isEqualOrLower = true; break; } break; case NpacsConstants.CLASSIFICATION_CBR_LOW: switch (newClassificationCd) { case NpacsConstants.CLASSIFICATION_CBI: case NpacsConstants.CLASSIFICATION_SEX_OFFENDER: case NpacsConstants.CLASSIFICATION_DOMESTIC_VIOLENCE: case NpacsConstants.CLASSIFICATION_SSAS: case NpacsConstants.CLASSIFICATION_PSC_ADULT: case NpacsConstants.CLASSIFICATION_WEC: case NpacsConstants.CLASSIFICATION_CBI_DUI: case NpacsConstants.CLASSIFICATION_CBR_MEDIUM_HIGH: case NpacsConstants.CLASSIFICATION_CBR_MEDIUM_LOW: isEqualOrLower = false; break; default: isEqualOrLower = true; break; } break; case NpacsConstants.CLASSIFICATION_CBR_ADMIN_OVERRIDE_VL: switch (newClassificationCd) { case NpacsConstants.CLASSIFICATION_CBI: case NpacsConstants.CLASSIFICATION_SEX_OFFENDER: case NpacsConstants.CLASSIFICATION_DOMESTIC_VIOLENCE: case NpacsConstants.CLASSIFICATION_SSAS: case NpacsConstants.CLASSIFICATION_PSC_ADULT: case NpacsConstants.CLASSIFICATION_WEC: case NpacsConstants.CLASSIFICATION_CBI_DUI: case NpacsConstants.CLASSIFICATION_CBR_MEDIUM_HIGH: case NpacsConstants.CLASSIFICATION_CBR_MEDIUM_LOW: case NpacsConstants.CLASSIFICATION_CBR_LOW: isEqualOrLower = false; break; default: isEqualOrLower = true; break; } break; case NpacsConstants.CLASSIFICATION_JCBI: case NpacsConstants.CLASSIFICATION_JSH: case NpacsConstants.CLASSIFICATION_3_B: case NpacsConstants.CLASSIFICATION_PSC_JUVENILE: isEqualOrLower = true; break; case NpacsConstants.CLASSIFICATION_JCBR_LOW_MODERATE: switch (newClassificationCd) { case NpacsConstants.CLASSIFICATION_JCBI: case NpacsConstants.CLASSIFICATION_JSH: case NpacsConstants.CLASSIFICATION_3_B: case NpacsConstants.CLASSIFICATION_PSC_JUVENILE: isEqualOrLower = false; break; default: isEqualOrLower = true; break; } break; case NpacsConstants.CLASSIFICATION_JCBR_LOW: switch (newClassificationCd) { case NpacsConstants.CLASSIFICATION_JCBI: case NpacsConstants.CLASSIFICATION_JSH: case NpacsConstants.CLASSIFICATION_3_B: case NpacsConstants.CLASSIFICATION_PSC_JUVENILE: case NpacsConstants.CLASSIFICATION_JCBR_LOW_MODERATE: isEqualOrLower = false; break; default: isEqualOrLower = true; break; } break; } } return isEqualOrLower; } public boolean isNewClassificationEqualOrHigher( Integer currentClassificationCd, Integer newClassificationCd) { boolean isEqualOrHigher = false; if (currentClassificationCd != null && newClassificationCd != null) { switch (currentClassificationCd) { case NpacsConstants.CLASSIFICATION_CBI: case NpacsConstants.CLASSIFICATION_SEX_OFFENDER: case NpacsConstants.CLASSIFICATION_DOMESTIC_VIOLENCE: case NpacsConstants.CLASSIFICATION_SSAS: case NpacsConstants.CLASSIFICATION_PSC_ADULT: case NpacsConstants.CLASSIFICATION_WEC: case NpacsConstants.CLASSIFICATION_CBI_DUI: switch (newClassificationCd) { case NpacsConstants.CLASSIFICATION_CBI: case NpacsConstants.CLASSIFICATION_SEX_OFFENDER: case NpacsConstants.CLASSIFICATION_DOMESTIC_VIOLENCE: case NpacsConstants.CLASSIFICATION_SSAS: case NpacsConstants.CLASSIFICATION_PSC_ADULT: case NpacsConstants.CLASSIFICATION_WEC: case NpacsConstants.CLASSIFICATION_CBI_DUI: isEqualOrHigher = true; break; } break; case NpacsConstants.CLASSIFICATION_CBR_MEDIUM_HIGH: switch (newClassificationCd) { case NpacsConstants.CLASSIFICATION_CBI: case NpacsConstants.CLASSIFICATION_SEX_OFFENDER: case NpacsConstants.CLASSIFICATION_DOMESTIC_VIOLENCE: case NpacsConstants.CLASSIFICATION_SSAS: case NpacsConstants.CLASSIFICATION_PSC_ADULT: case NpacsConstants.CLASSIFICATION_WEC: case NpacsConstants.CLASSIFICATION_CBI_DUI: case NpacsConstants.CLASSIFICATION_CBR_MEDIUM_HIGH: isEqualOrHigher = true; break; } break; case NpacsConstants.CLASSIFICATION_CBR_MEDIUM_LOW: switch (newClassificationCd) { case NpacsConstants.CLASSIFICATION_CBI: case NpacsConstants.CLASSIFICATION_SEX_OFFENDER: case NpacsConstants.CLASSIFICATION_DOMESTIC_VIOLENCE: case NpacsConstants.CLASSIFICATION_SSAS: case NpacsConstants.CLASSIFICATION_PSC_ADULT: case NpacsConstants.CLASSIFICATION_WEC: case NpacsConstants.CLASSIFICATION_CBI_DUI: case NpacsConstants.CLASSIFICATION_CBR_MEDIUM_HIGH: case NpacsConstants.CLASSIFICATION_CBR_MEDIUM_LOW: isEqualOrHigher = true; break; } break; case NpacsConstants.CLASSIFICATION_CBR_LOW: switch (newClassificationCd) { case NpacsConstants.CLASSIFICATION_CBI: case NpacsConstants.CLASSIFICATION_SEX_OFFENDER: case NpacsConstants.CLASSIFICATION_DOMESTIC_VIOLENCE: case NpacsConstants.CLASSIFICATION_SSAS: case NpacsConstants.CLASSIFICATION_PSC_ADULT: case NpacsConstants.CLASSIFICATION_WEC: case NpacsConstants.CLASSIFICATION_CBI_DUI: case NpacsConstants.CLASSIFICATION_CBR_MEDIUM_HIGH: case NpacsConstants.CLASSIFICATION_CBR_MEDIUM_LOW: case NpacsConstants.CLASSIFICATION_CBR_LOW: isEqualOrHigher = true; break; } break; case NpacsConstants.CLASSIFICATION_CBR_ADMIN_OVERRIDE_VL: switch (newClassificationCd) { case NpacsConstants.CLASSIFICATION_CBI: case NpacsConstants.CLASSIFICATION_SEX_OFFENDER: case NpacsConstants.CLASSIFICATION_DOMESTIC_VIOLENCE: case NpacsConstants.CLASSIFICATION_SSAS: case NpacsConstants.CLASSIFICATION_PSC_ADULT: case NpacsConstants.CLASSIFICATION_WEC: case NpacsConstants.CLASSIFICATION_CBI_DUI: case NpacsConstants.CLASSIFICATION_CBR_MEDIUM_HIGH: case NpacsConstants.CLASSIFICATION_CBR_MEDIUM_LOW: case NpacsConstants.CLASSIFICATION_CBR_LOW: case NpacsConstants.CLASSIFICATION_CBR_ADMIN_OVERRIDE_VL: isEqualOrHigher = true; break; } break; case NpacsConstants.CLASSIFICATION_JCBI: case NpacsConstants.CLASSIFICATION_JSH: case NpacsConstants.CLASSIFICATION_3_B: case NpacsConstants.CLASSIFICATION_PSC_JUVENILE: switch (newClassificationCd) { case NpacsConstants.CLASSIFICATION_JCBI: case NpacsConstants.CLASSIFICATION_JSH: case NpacsConstants.CLASSIFICATION_3_B: case NpacsConstants.CLASSIFICATION_PSC_JUVENILE: isEqualOrHigher = true; break; } break; case NpacsConstants.CLASSIFICATION_JCBR_LOW_MODERATE: switch (newClassificationCd) { case NpacsConstants.CLASSIFICATION_JCBI: case NpacsConstants.CLASSIFICATION_JSH: case NpacsConstants.CLASSIFICATION_3_B: case NpacsConstants.CLASSIFICATION_PSC_JUVENILE: case NpacsConstants.CLASSIFICATION_JCBR_LOW_MODERATE: isEqualOrHigher = true; break; } break; case NpacsConstants.CLASSIFICATION_JCBR_LOW: switch (newClassificationCd) { case NpacsConstants.CLASSIFICATION_JCBI: case NpacsConstants.CLASSIFICATION_JSH: case NpacsConstants.CLASSIFICATION_3_B: case NpacsConstants.CLASSIFICATION_PSC_JUVENILE: case NpacsConstants.CLASSIFICATION_JCBR_LOW_MODERATE: case NpacsConstants.CLASSIFICATION_JCBR_LOW: isEqualOrHigher = true; break; } break; } } return isEqualOrHigher; }
compare classifications REFACTORED
20160912_Capstone_compareClassifications/CaseManagementService.java
compare classifications REFACTORED
Java
bsd-2-clause
7456306e5662c7101ed7a045b5aaae3d27223564
0
malensek/forager,malensek/forager
/* Copyright (c) 2014, Colorado State University 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 holder or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of such damage. */ package forager.events; import galileo.event.EventMap; public class ForagerEventMap extends EventMap { public ForagerEventMap() { addMapping(TaskRequest.class); addMapping(TaskSpec.class); addMapping(TaskCompletion.class); addMapping(ImportRequest.class); addMapping(ImportResponse.class); } }
src/forager/events/ForagerEventMap.java
/* Copyright (c) 2014, Colorado State University 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 holder or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of such damage. */ package forager.events; import galileo.event.EventMap; public class ForagerEventMap extends EventMap { public ForagerEventMap() { addMapping(TaskRequest.class); addMapping(TaskSpec.class); addMapping(TaskCompletion.class); } }
Event mappings for import events
src/forager/events/ForagerEventMap.java
Event mappings for import events
Java
bsd-2-clause
b05835fb320c4ba9b9ef62c04b676f44e4994fee
0
l2-/runelite,Sethtroll/runelite,l2-/runelite,runelite/runelite,runelite/runelite,Sethtroll/runelite,runelite/runelite
/* * Copyright (c) 2018, Charlie Waters * 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.client.plugins.itemprices; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics2D; import javax.inject.Inject; import net.runelite.api.Client; import net.runelite.api.Constants; import net.runelite.api.InventoryID; import net.runelite.api.Item; import net.runelite.api.ItemComposition; import net.runelite.api.ItemContainer; import net.runelite.api.ItemID; import net.runelite.api.MenuAction; import net.runelite.api.MenuEntry; import net.runelite.api.widgets.WidgetID; import net.runelite.api.widgets.WidgetInfo; import net.runelite.client.game.ItemManager; import net.runelite.client.ui.overlay.Overlay; import net.runelite.client.ui.overlay.OverlayPosition; import net.runelite.client.ui.overlay.tooltip.Tooltip; import net.runelite.client.ui.overlay.tooltip.TooltipManager; import net.runelite.client.util.ColorUtil; import net.runelite.client.util.StackFormatter; class ItemPricesOverlay extends Overlay { private static final int INVENTORY_ITEM_WIDGETID = WidgetInfo.INVENTORY.getPackedId(); private static final int BANK_INVENTORY_ITEM_WIDGETID = WidgetInfo.BANK_INVENTORY_ITEMS_CONTAINER.getPackedId(); private static final int BANK_ITEM_WIDGETID = WidgetInfo.BANK_ITEM_CONTAINER.getPackedId(); private final Client client; private final ItemPricesConfig config; private final TooltipManager tooltipManager; private final StringBuilder itemStringBuilder = new StringBuilder(); @Inject ItemManager itemManager; @Inject ItemPricesOverlay(Client client, ItemPricesConfig config, TooltipManager tooltipManager) { setPosition(OverlayPosition.DYNAMIC); this.client = client; this.config = config; this.tooltipManager = tooltipManager; } @Override public Dimension render(Graphics2D graphics) { if (client.isMenuOpen()) { return null; } final MenuEntry[] menuEntries = client.getMenuEntries(); final int last = menuEntries.length - 1; if (last < 0) { return null; } final MenuEntry menuEntry = menuEntries[last]; final MenuAction action = MenuAction.of(menuEntry.getType()); final int widgetId = menuEntry.getParam1(); final int groupId = WidgetInfo.TO_GROUP(widgetId); // Tooltip action type handling switch (action) { case WIDGET_DEFAULT: case ITEM_USE: case ITEM_FIRST_OPTION: case ITEM_SECOND_OPTION: case ITEM_THIRD_OPTION: case ITEM_FOURTH_OPTION: case ITEM_FIFTH_OPTION: // Item tooltip values switch (groupId) { case WidgetID.INVENTORY_GROUP_ID: if (config.hideInventory()) { return null; } // intentional fallthrough case WidgetID.BANK_GROUP_ID: case WidgetID.BANK_INVENTORY_GROUP_ID: // Make tooltip final String text = makeValueTooltip(menuEntry); if (text != null) { tooltipManager.add(new Tooltip(ColorUtil.prependColorTag(text, new Color(238, 238, 238)))); } break; } break; } return null; } private String makeValueTooltip(MenuEntry menuEntry) { // Disabling both disables all value tooltips if (!config.showGEPrice() && !config.showHAValue()) { return null; } final int widgetId = menuEntry.getParam1(); ItemContainer container = null; // Inventory item if (widgetId == INVENTORY_ITEM_WIDGETID || widgetId == BANK_INVENTORY_ITEM_WIDGETID) { container = client.getItemContainer(InventoryID.INVENTORY); } // Bank item else if (widgetId == BANK_ITEM_WIDGETID) { container = client.getItemContainer(InventoryID.BANK); } if (container == null) { return null; } // Find the item in the container to get stack size final Item[] items = container.getItems(); final int index = menuEntry.getParam0(); if (index < items.length) { final Item item = items[index]; return getItemStackValueText(item); } return null; } private String getItemStackValueText(Item item) { int id = item.getId(); int qty = item.getQuantity(); // Special case for coins and platinum tokens if (id == ItemID.COINS_995) { return StackFormatter.formatNumber(qty) + " gp"; } else if (id == ItemID.PLATINUM_TOKEN) { return StackFormatter.formatNumber(qty * 1000) + " gp"; } ItemComposition itemDef = itemManager.getItemComposition(id); if (itemDef.getNote() != -1) { id = itemDef.getLinkedNoteId(); itemDef = itemManager.getItemComposition(id); } // Only check prices for things with store prices if (itemDef.getPrice() <= 0) { return null; } int gePrice = 0; int haPrice = 0; int haProfit = 0; final int itemHaPrice = Math.round(itemDef.getPrice() * Constants.HIGH_ALCHEMY_MULTIPLIER); if (config.showGEPrice()) { gePrice = itemManager.getItemPrice(id); } if (config.showHAValue()) { haPrice = itemHaPrice; } if (gePrice > 0 && itemHaPrice > 0 && config.showAlchProfit()) { haProfit = calculateHAProfit(itemHaPrice, gePrice); } if (gePrice > 0 || haPrice > 0) { return stackValueText(qty, gePrice, haPrice, haProfit); } return null; } private String stackValueText(int qty, int gePrice, int haValue, int haProfit) { if (gePrice > 0) { itemStringBuilder.append("EX: ") .append(StackFormatter.quantityToStackSize(gePrice * qty)) .append(" gp"); if (config.showEA() && qty > 1) { itemStringBuilder.append(" (") .append(StackFormatter.quantityToStackSize(gePrice)) .append(" ea)"); } } if (haValue > 0) { if (gePrice > 0) { itemStringBuilder.append("</br>"); } itemStringBuilder.append("HA: ") .append(StackFormatter.quantityToStackSize(haValue * qty)) .append(" gp"); if (config.showEA() && qty > 1) { itemStringBuilder.append(" (") .append(StackFormatter.quantityToStackSize(haValue)) .append(" ea)"); } } if (haProfit != 0) { Color haColor = haProfitColor(haProfit); itemStringBuilder.append("</br>"); itemStringBuilder.append("HA Profit: ") .append(ColorUtil.wrapWithColorTag(String.valueOf(haProfit * qty), haColor)) .append(" gp"); if (config.showEA() && qty > 1) { itemStringBuilder.append(" (") .append(ColorUtil.wrapWithColorTag(String.valueOf(haProfit), haColor)) .append(" ea)"); } } // Build string and reset builder final String text = itemStringBuilder.toString(); itemStringBuilder.setLength(0); return text; } private int calculateHAProfit(int haPrice, int gePrice) { int natureRunePrice = itemManager.getItemPrice(ItemID.NATURE_RUNE); return haPrice - gePrice - natureRunePrice; } private static Color haProfitColor(int haProfit) { return haProfit >= 0 ? Color.GREEN : Color.RED; } }
runelite-client/src/main/java/net/runelite/client/plugins/itemprices/ItemPricesOverlay.java
/* * Copyright (c) 2018, Charlie Waters * 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.client.plugins.itemprices; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics2D; import javax.inject.Inject; import net.runelite.api.Client; import net.runelite.api.Constants; import net.runelite.api.InventoryID; import net.runelite.api.Item; import net.runelite.api.ItemComposition; import net.runelite.api.ItemContainer; import net.runelite.api.ItemID; import net.runelite.api.MenuAction; import net.runelite.api.MenuEntry; import net.runelite.api.widgets.WidgetID; import net.runelite.api.widgets.WidgetInfo; import net.runelite.client.game.ItemManager; import net.runelite.client.ui.overlay.Overlay; import net.runelite.client.ui.overlay.OverlayPosition; import net.runelite.client.ui.overlay.tooltip.Tooltip; import net.runelite.client.ui.overlay.tooltip.TooltipManager; import net.runelite.client.util.ColorUtil; import net.runelite.client.util.StackFormatter; class ItemPricesOverlay extends Overlay { private static final int INVENTORY_ITEM_WIDGETID = WidgetInfo.INVENTORY.getPackedId(); private static final int BANK_INVENTORY_ITEM_WIDGETID = WidgetInfo.BANK_INVENTORY_ITEMS_CONTAINER.getPackedId(); private static final int BANK_ITEM_WIDGETID = WidgetInfo.BANK_ITEM_CONTAINER.getPackedId(); private final Client client; private final ItemPricesConfig config; private final TooltipManager tooltipManager; private final StringBuilder itemStringBuilder = new StringBuilder(); @Inject ItemManager itemManager; @Inject ItemPricesOverlay(Client client, ItemPricesConfig config, TooltipManager tooltipManager) { setPosition(OverlayPosition.DYNAMIC); this.client = client; this.config = config; this.tooltipManager = tooltipManager; } @Override public Dimension render(Graphics2D graphics) { if (client.isMenuOpen()) { return null; } final MenuEntry[] menuEntries = client.getMenuEntries(); final int last = menuEntries.length - 1; if (last < 0) { return null; } final MenuEntry menuEntry = menuEntries[last]; final MenuAction action = MenuAction.of(menuEntry.getType()); final int widgetId = menuEntry.getParam1(); final int groupId = WidgetInfo.TO_GROUP(widgetId); // Tooltip action type handling switch (action) { case WIDGET_DEFAULT: case ITEM_USE: case ITEM_FIRST_OPTION: case ITEM_SECOND_OPTION: case ITEM_THIRD_OPTION: case ITEM_FOURTH_OPTION: case ITEM_FIFTH_OPTION: // Item tooltip values switch (groupId) { case WidgetID.INVENTORY_GROUP_ID: if (config.hideInventory()) { return null; } // intentional fallthrough case WidgetID.BANK_GROUP_ID: case WidgetID.BANK_INVENTORY_GROUP_ID: // Make tooltip final String text = makeValueTooltip(menuEntry); if (text != null) { tooltipManager.add(new Tooltip(ColorUtil.prependColorTag(text, new Color(238, 238, 238)))); } break; } break; } return null; } private String makeValueTooltip(MenuEntry menuEntry) { // Disabling both disables all value tooltips if (!config.showGEPrice() && !config.showHAValue()) { return null; } final int widgetId = menuEntry.getParam1(); ItemContainer container = null; // Inventory item if (widgetId == INVENTORY_ITEM_WIDGETID || widgetId == BANK_INVENTORY_ITEM_WIDGETID) { container = client.getItemContainer(InventoryID.INVENTORY); } // Bank item else if (widgetId == BANK_ITEM_WIDGETID) { container = client.getItemContainer(InventoryID.BANK); } if (container == null) { return null; } // Find the item in the container to get stack size final Item[] items = container.getItems(); final int index = menuEntry.getParam0(); if (index < items.length) { final Item item = items[index]; return getItemStackValueText(item); } return null; } private String getItemStackValueText(Item item) { int id = item.getId(); int qty = item.getQuantity(); // Special case for coins and platinum tokens if (id == ItemID.COINS_995) { return StackFormatter.formatNumber(qty) + " gp"; } else if (id == ItemID.PLATINUM_TOKEN) { return StackFormatter.formatNumber(qty * 1000) + " gp"; } ItemComposition itemDef = itemManager.getItemComposition(id); if (itemDef.getNote() != -1) { id = itemDef.getLinkedNoteId(); itemDef = itemManager.getItemComposition(id); } // Only check prices for things with store prices if (itemDef.getPrice() <= 0) { return null; } int gePrice = 0; int haPrice = 0; int haProfit = 0; if (config.showGEPrice()) { gePrice = itemManager.getItemPrice(id); } if (config.showHAValue()) { haPrice = Math.round(itemDef.getPrice() * Constants.HIGH_ALCHEMY_MULTIPLIER); } if (gePrice > 0 && haPrice > 0 && config.showAlchProfit()) { haProfit = calculateHAProfit(haPrice, gePrice); } if (gePrice > 0 || haPrice > 0) { return stackValueText(qty, gePrice, haPrice, haProfit); } return null; } private String stackValueText(int qty, int gePrice, int haValue, int haProfit) { if (gePrice > 0) { itemStringBuilder.append("EX: ") .append(StackFormatter.quantityToStackSize(gePrice * qty)) .append(" gp"); if (config.showEA() && qty > 1) { itemStringBuilder.append(" (") .append(StackFormatter.quantityToStackSize(gePrice)) .append(" ea)"); } } if (haValue > 0) { if (gePrice > 0) { itemStringBuilder.append("</br>"); } itemStringBuilder.append("HA: ") .append(StackFormatter.quantityToStackSize(haValue * qty)) .append(" gp"); if (config.showEA() && qty > 1) { itemStringBuilder.append(" (") .append(StackFormatter.quantityToStackSize(haValue)) .append(" ea)"); } } if (haProfit != 0) { Color haColor = haProfitColor(haProfit); itemStringBuilder.append("</br>"); itemStringBuilder.append("HA Profit: ") .append(ColorUtil.wrapWithColorTag(String.valueOf(haProfit * qty), haColor)) .append(" gp"); if (config.showEA() && qty > 1) { itemStringBuilder.append(" (") .append(ColorUtil.wrapWithColorTag(String.valueOf(haProfit), haColor)) .append(" ea)"); } } // Build string and reset builder final String text = itemStringBuilder.toString(); itemStringBuilder.setLength(0); return text; } private int calculateHAProfit(int haPrice, int gePrice) { int natureRunePrice = itemManager.getItemPrice(ItemID.NATURE_RUNE); return haPrice - gePrice - natureRunePrice; } private static Color haProfitColor(int haProfit) { return haProfit >= 0 ? Color.GREEN : Color.RED; } }
itemprices: fix showing high alch profit with show ha value disabled Co-authored-by: Adam <[email protected]>
runelite-client/src/main/java/net/runelite/client/plugins/itemprices/ItemPricesOverlay.java
itemprices: fix showing high alch profit with show ha value disabled
Java
bsd-3-clause
f39b6a400973ef995291c35109949b776fd9cd14
0
apptentive/apptentive-android
/* * Copyright (c) 2017, Apptentive, Inc. All Rights Reserved. * Please refer to the LICENSE file for the terms and conditions * under which redistribution and use of this file is permitted. */ package com.apptentive.android.sdk.network; import org.json.JSONObject; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; public class MockHttpJsonRequest extends HttpJsonRequest { private final MockHttpURLConnection connection; public MockHttpJsonRequest(String name, JSONObject requestObject) { super("https://abc.com", requestObject); connection = new MockHttpURLConnection(); connection.setMockResponseCode(200); setName(name); setMethod(HttpRequestMethod.POST); } @Override protected HttpURLConnection openConnection(URL url) throws IOException { return connection; } @Override public String toString() { return getName(); } public MockHttpJsonRequest setMockResponseData(JSONObject responseData) { return setMockResponseData(responseData.toString()); } public MockHttpJsonRequest setMockResponseData(String responseData) { connection.setMockResponseData(responseData); return this; } @Override protected boolean isNetworkConnectionPresent() { return true; } }
apptentive/src/testCommon/java/com/apptentive/android/sdk/network/MockHttpJsonRequest.java
/* * Copyright (c) 2017, Apptentive, Inc. All Rights Reserved. * Please refer to the LICENSE file for the terms and conditions * under which redistribution and use of this file is permitted. */ package com.apptentive.android.sdk.network; import org.json.JSONObject; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; public class MockHttpJsonRequest extends HttpJsonRequest { private final MockHttpURLConnection connection; public MockHttpJsonRequest(String name, JSONObject requestObject) { super("https://abc.com", requestObject); connection = new MockHttpURLConnection(); connection.setMockResponseCode(200); setName(name); setMethod(HttpRequestMethod.POST); } @Override protected HttpURLConnection openConnection(URL url) throws IOException { return connection; } @Override public String toString() { return getName(); } public MockHttpJsonRequest setMockResponseData(JSONObject responseData) { return setMockResponseData(responseData.toString()); } public MockHttpJsonRequest setMockResponseData(String responseData) { connection.setMockResponseData(responseData); return this; } }
Override network connection check in another mock request to fix tests.
apptentive/src/testCommon/java/com/apptentive/android/sdk/network/MockHttpJsonRequest.java
Override network connection check in another mock request to fix tests.
Java
bsd-3-clause
f493a4872effa29789667965dbe2ff9b8d76371f
0
benfortuna/ical4j.vcard,benfortuna/ical4j.vcard
/* * $Id$ * * Created on 22/08/2008 * * Copyright (c) 2008, Ben Fortuna * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * o Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * o 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. * * o Neither the name of Ben Fortuna nor the names of any other contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.fortuna.ical4j.vcard; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.List; import net.fortuna.ical4j.vcard.property.Kind; import net.fortuna.ical4j.vcard.property.Name; import net.fortuna.ical4j.vcard.property.Source; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; /** * @author Ben * */ @RunWith(Parameterized.class) public class VCardTest { private VCard vCard; private int expectedPropertyCount; /** * @param vCard * @param expectedPropertyCount */ public VCardTest(VCard vCard, int expectedPropertyCount) { this.vCard = vCard; this.expectedPropertyCount = expectedPropertyCount; } @Test public void testGetProperties() { assertEquals(expectedPropertyCount, vCard.getProperties().size()); } @Test public void testGetPropertiesName() { for (Property p : vCard.getProperties()) { List<Property> matches = vCard.getProperties(p.name); assertNotNull(matches); assertTrue(matches.size() >= 1); assertTrue(matches.contains(p)); } } @Test public void testGetPropertyName() { for (Property p : vCard.getProperties()) { assertNotNull(vCard.getProperty(p.name)); } assertNull(vCard.getProperty(null)); } @Test public void testGetExtendedPropertiesName() { for (Property p : vCard.getProperties(net.fortuna.ical4j.vcard.Property.Name.EXTENDED)) { List<Property> matches = vCard.getExtendedProperties(p.extendedName); assertNotNull(matches); assertTrue(matches.size() >= 1); assertTrue(matches.contains(p)); } } @Test public void testGetExtendedPropertyName() { for (Property p : vCard.getProperties(net.fortuna.ical4j.vcard.Property.Name.EXTENDED)) { assertNotNull(vCard.getExtendedProperty(p.extendedName)); } assertNull(vCard.getExtendedProperty(null)); } @SuppressWarnings("serial") @Parameters public static Collection<Object[]> parameters() { List<Object[]> params = new ArrayList<Object[]>(); params.add(new Object[] {new VCard(), 0}); List<Property> props = new ArrayList<Property>(); props.add(new Source(URI.create("ldap://ldap.example.com/cn=Babs%20Jensen,%20o=Babsco,%20c=US"))); props.add(new Name("Babs Jensen's Contact Information")); props.add(Kind.INDIVIDUAL); props.add(new Property("test") { @Override public String getValue() { return null; } }); VCard vcard = new VCard(props); params.add(new Object[] {vcard, 4}); return params; } }
src/test/java/net/fortuna/ical4j/vcard/VCardTest.java
/* * $Id$ * * Created on 22/08/2008 * * Copyright (c) 2008, Ben Fortuna * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * o Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * o 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. * * o Neither the name of Ben Fortuna nor the names of any other contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.fortuna.ical4j.vcard; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.List; import net.fortuna.ical4j.vcard.property.Kind; import net.fortuna.ical4j.vcard.property.Name; import net.fortuna.ical4j.vcard.property.Source; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; /** * @author Ben * */ @RunWith(Parameterized.class) public class VCardTest { private VCard vCard; private int expectedPropertyCount; /** * @param vCard * @param expectedPropertyCount */ public VCardTest(VCard vCard, int expectedPropertyCount) { this.vCard = vCard; this.expectedPropertyCount = expectedPropertyCount; } @Test public void testGetProperties() { assertEquals(expectedPropertyCount, vCard.getProperties().size()); } @Test public void testGetPropertiesName() { for (Property p : vCard.getProperties()) { List<Property> matches = vCard.getProperties(p.name); assertNotNull(matches); assertTrue(matches.size() >= 1); assertTrue(matches.contains(p)); } } @Test public void testGetPropertyName() { for (Property p : vCard.getProperties()) { assertNotNull(vCard.getProperty(p.name)); } } @Test public void testGetExtendedPropertiesName() { for (Property p : vCard.getProperties()) { if (p.name.equals(net.fortuna.ical4j.vcard.Property.Name.EXTENDED)) { List<Property> matches = vCard.getExtendedProperties(p.extendedName); assertNotNull(matches); assertTrue(matches.size() >= 1); assertTrue(matches.contains(p)); } } } @Test public void testGetExtendedPropertyName() { for (Property p : vCard.getProperties()) { if (p.name.equals(net.fortuna.ical4j.vcard.Property.Name.EXTENDED)) { assertNotNull(vCard.getExtendedProperty(p.extendedName)); } } } @Parameters public static Collection<Object[]> parameters() { List<Object[]> params = new ArrayList<Object[]>(); params.add(new Object[] {new VCard(), 0}); List<Property> props = new ArrayList<Property>(); props.add(new Source(URI.create("ldap://ldap.example.com/cn=Babs%20Jensen,%20o=Babsco,%20c=US"))); props.add(new Name("Babs Jensen's Contact Information")); props.add(Kind.INDIVIDUAL); VCard vcard = new VCard(props); params.add(new Object[] {vcard, 3}); return params; } }
Support non-standard property accessors in VCard
src/test/java/net/fortuna/ical4j/vcard/VCardTest.java
Support non-standard property accessors in VCard
Java
bsd-3-clause
6b2817f8bbe313ccfe90b64b0e3be95aa5b320d4
0
lncosie/antlr4,lncosie/antlr4,joshids/antlr4,Pursuit92/antlr4,parrt/antlr4,cooperra/antlr4,mcanthony/antlr4,ericvergnaud/antlr4,cocosli/antlr4,joshids/antlr4,parrt/antlr4,cooperra/antlr4,mcanthony/antlr4,chandler14362/antlr4,chienjchienj/antlr4,krzkaczor/antlr4,worsht/antlr4,joshids/antlr4,mcanthony/antlr4,joshids/antlr4,wjkohnen/antlr4,ericvergnaud/antlr4,hce/antlr4,antlr/antlr4,supriyantomaftuh/antlr4,antlr/antlr4,ericvergnaud/antlr4,antlr/antlr4,antlr/antlr4,wjkohnen/antlr4,hce/antlr4,Distrotech/antlr4,krzkaczor/antlr4,worsht/antlr4,sidhart/antlr4,chandler14362/antlr4,chienjchienj/antlr4,cooperra/antlr4,chandler14362/antlr4,sidhart/antlr4,sidhart/antlr4,antlr/antlr4,wjkohnen/antlr4,antlr/antlr4,krzkaczor/antlr4,mcanthony/antlr4,chienjchienj/antlr4,sidhart/antlr4,jvanzyl/antlr4,krzkaczor/antlr4,Pursuit92/antlr4,hce/antlr4,Pursuit92/antlr4,joshids/antlr4,ericvergnaud/antlr4,joshids/antlr4,supriyantomaftuh/antlr4,Pursuit92/antlr4,supriyantomaftuh/antlr4,chienjchienj/antlr4,ericvergnaud/antlr4,mcanthony/antlr4,Pursuit92/antlr4,Distrotech/antlr4,lncosie/antlr4,joshids/antlr4,Pursuit92/antlr4,wjkohnen/antlr4,antlr/antlr4,jvanzyl/antlr4,chandler14362/antlr4,Distrotech/antlr4,antlr/antlr4,worsht/antlr4,Distrotech/antlr4,parrt/antlr4,wjkohnen/antlr4,cocosli/antlr4,jvanzyl/antlr4,ericvergnaud/antlr4,lncosie/antlr4,supriyantomaftuh/antlr4,chandler14362/antlr4,Pursuit92/antlr4,chienjchienj/antlr4,ericvergnaud/antlr4,cocosli/antlr4,hce/antlr4,parrt/antlr4,Pursuit92/antlr4,parrt/antlr4,cocosli/antlr4,parrt/antlr4,parrt/antlr4,Pursuit92/antlr4,parrt/antlr4,cooperra/antlr4,parrt/antlr4,ericvergnaud/antlr4,chandler14362/antlr4,chandler14362/antlr4,antlr/antlr4,antlr/antlr4,parrt/antlr4,chandler14362/antlr4,wjkohnen/antlr4,ericvergnaud/antlr4,chandler14362/antlr4,Distrotech/antlr4,krzkaczor/antlr4,lncosie/antlr4,supriyantomaftuh/antlr4,wjkohnen/antlr4,sidhart/antlr4,worsht/antlr4,wjkohnen/antlr4,jvanzyl/antlr4,ericvergnaud/antlr4,worsht/antlr4,joshids/antlr4,wjkohnen/antlr4
package org.antlr.v4.test; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.Lexer; import org.antlr.v4.runtime.Parser; import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.TokenStream; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.pattern.ParseTreeMatch; import org.antlr.v4.runtime.tree.pattern.ParseTreePattern; import org.antlr.v4.runtime.tree.pattern.ParseTreePatternMatcher; import org.junit.Test; import java.lang.reflect.Constructor; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; public class TestParseTreeMatcher extends BaseTest { @Test public void testChunking() throws Exception { ParseTreePatternMatcher m = new ParseTreePatternMatcher(null, null); assertEquals("[ID, ' = ', expr, ' ;']", m.split("<ID> = <expr> ;").toString()); assertEquals("[' ', ID, ' = ', expr]", m.split(" <ID> = <expr>").toString()); assertEquals("[ID, ' = ', expr]", m.split("<ID> = <expr>").toString()); assertEquals("[expr]", m.split("<expr>").toString()); assertEquals("['<x> foo']", m.split("\\<x\\> foo").toString()); assertEquals("['foo <x> bar ', tag]", m.split("foo \\<x\\> bar <tag>").toString()); } @Test public void testDelimiters() throws Exception { ParseTreePatternMatcher m = new ParseTreePatternMatcher(null, null); m.setDelimiters("<<", ">>", "$"); String result = m.split("<<ID>> = <<expr>> ;$<< ick $>>").toString(); assertEquals("[ID, ' = ', expr, ' ;<< ick >>']", result); } @Test public void testInvertedTags() throws Exception { ParseTreePatternMatcher m= new ParseTreePatternMatcher(null, null); String result = null; try { m.split(">expr<"); } catch (IllegalArgumentException iae) { result = iae.getMessage(); } String expected = "tag delimiters out of order in pattern: >expr<"; assertEquals(expected, result); } @Test public void testUnclosedTag() throws Exception { ParseTreePatternMatcher m = new ParseTreePatternMatcher(null, null); String result = null; try { m.split("<expr hi mom"); } catch (IllegalArgumentException iae) { result = iae.getMessage(); } String expected = "unterminated tag in pattern: <expr hi mom"; assertEquals(expected, result); } @Test public void testExtraClose() throws Exception { ParseTreePatternMatcher m = new ParseTreePatternMatcher(null, null); String result = null; try { m.split("<expr> >"); } catch (IllegalArgumentException iae) { result = iae.getMessage(); } String expected = "missing start tag in pattern: <expr> >"; assertEquals(expected, result); } @Test public void testTokenizingPattern() throws Exception { String grammar = "grammar X1;\n" + "s : ID '=' expr ';' ;\n" + "expr : ID | INT ;\n" + "ID : [a-z]+ ;\n" + "INT : [0-9]+ ;\n" + "WS : [ \\r\\n\\t]+ -> skip ;\n"; boolean ok = rawGenerateAndBuildRecognizer("X1.g4", grammar, "X1Parser", "X1Lexer", false); assertTrue(ok); ParseTreePatternMatcher m = getPatternMatcher("X1"); List<? extends Token> tokens = m.tokenize("<ID> = <expr> ;"); String results = tokens.toString(); String expected = "[ID:3, [@-1,1:1='=',<1>,1:1], expr:7, [@-1,1:1=';',<2>,1:1]]"; assertEquals(expected, results); } @Test public void testCompilingPattern() throws Exception { String grammar = "grammar X2;\n" + "s : ID '=' expr ';' ;\n" + "expr : ID | INT ;\n" + "ID : [a-z]+ ;\n" + "INT : [0-9]+ ;\n" + "WS : [ \\r\\n\\t]+ -> skip ;\n"; boolean ok = rawGenerateAndBuildRecognizer("X2.g4", grammar, "X2Parser", "X2Lexer", false); assertTrue(ok); ParseTreePatternMatcher m = getPatternMatcher("X2"); ParseTreePattern t = m.compile("<ID> = <expr> ;", m.getParser().getRuleIndex("s")); String results = t.getPatternTree().toStringTree(m.getParser()); String expected = "(s <ID> = (expr <expr>) ;)"; assertEquals(expected, results); } @Test public void testHiddenTokensNotSeenByTreePatternParser() throws Exception { String grammar = "grammar X2;\n" + "s : ID '=' expr ';' ;\n" + "expr : ID | INT ;\n" + "ID : [a-z]+ ;\n" + "INT : [0-9]+ ;\n" + "WS : [ \\r\\n\\t]+ -> channel(HIDDEN) ;\n"; boolean ok = rawGenerateAndBuildRecognizer("X2.g4", grammar, "X2Parser", "X2Lexer", false); assertTrue(ok); ParseTreePatternMatcher m = getPatternMatcher("X2"); ParseTreePattern t = m.compile("<ID> = <expr> ;", m.getParser().getRuleIndex("s")); String results = t.getPatternTree().toStringTree(m.getParser()); String expected = "(s <ID> = (expr <expr>) ;)"; assertEquals(expected, results); } @Test public void testCompilingMultipleTokens() throws Exception { String grammar = "grammar X2;\n" + "s : ID '=' ID ';' ;\n" + "ID : [a-z]+ ;\n" + "WS : [ \\r\\n\\t]+ -> skip ;\n"; boolean ok = rawGenerateAndBuildRecognizer("X2.g4", grammar, "X2Parser", "X2Lexer", false); assertTrue(ok); ParseTreePatternMatcher m = getPatternMatcher("X2"); ParseTreePattern t = m.compile("<ID> = <ID> ;", m.getParser().getRuleIndex("s")); String results = t.getPatternTree().toStringTree(m.getParser()); String expected = "(s <ID> = <ID> ;)"; assertEquals(expected, results); } @Test public void testIDNodeMatches() throws Exception { String grammar = "grammar X3;\n" + "s : ID ';' ;\n" + "ID : [a-z]+ ;\n" + "WS : [ \\r\\n\\t]+ -> skip ;\n"; String input = "x ;"; String pattern = "<ID>;"; checkPatternMatch(grammar, "s", input, pattern, "X3"); } @Test public void testIDNodeWithLabelMatches() throws Exception { String grammar = "grammar X8;\n" + "s : ID ';' ;\n" + "ID : [a-z]+ ;\n" + "WS : [ \\r\\n\\t]+ -> skip ;\n"; String input = "x ;"; String pattern = "<id:ID>;"; ParseTreeMatch m = checkPatternMatch(grammar, "s", input, pattern, "X8"); assertEquals("{ID=[x], id=[x]}", m.getLabels().toString()); assertNotNull(m.get("id")); assertNotNull(m.get("ID")); assertEquals("x", m.get("id").getText()); assertEquals("x", m.get("ID").getText()); assertEquals("[x]", m.getAll("id").toString()); assertEquals("[x]", m.getAll("ID").toString()); assertNull(m.get("undefined")); assertEquals("[]", m.getAll("undefined").toString()); } @Test public void testLabelGetsLastIDNode() throws Exception { String grammar = "grammar X9;\n" + "s : ID ID ';' ;\n" + "ID : [a-z]+ ;\n" + "WS : [ \\r\\n\\t]+ -> skip ;\n"; String input = "x y;"; String pattern = "<id:ID> <id:ID>;"; ParseTreeMatch m = checkPatternMatch(grammar, "s", input, pattern, "X9"); assertEquals("{ID=[x, y], id=[x, y]}", m.getLabels().toString()); assertNotNull(m.get("id")); assertNotNull(m.get("ID")); assertEquals("y", m.get("id").getText()); assertEquals("y", m.get("ID").getText()); assertEquals("[x, y]", m.getAll("id").toString()); assertEquals("[x, y]", m.getAll("ID").toString()); assertNull(m.get("undefined")); assertEquals("[]", m.getAll("undefined").toString()); } @Test public void testIDNodeWithMultipleLabelMatches() throws Exception { String grammar = "grammar X7;\n" + "s : ID ID ID ';' ;\n" + "ID : [a-z]+ ;\n" + "WS : [ \\r\\n\\t]+ -> skip ;\n"; String input = "x y z;"; String pattern = "<a:ID> <b:ID> <a:ID>;"; ParseTreeMatch m = checkPatternMatch(grammar, "s", input, pattern, "X7"); assertEquals("{ID=[x, y, z], a=[x, z], b=[y]}", m.getLabels().toString()); assertNotNull(m.get("a")); // get first assertNotNull(m.get("b")); assertNotNull(m.get("ID")); assertEquals("z", m.get("a").getText()); assertEquals("y", m.get("b").getText()); assertEquals("z", m.get("ID").getText()); // get last assertEquals("[x, z]", m.getAll("a").toString()); assertEquals("[y]", m.getAll("b").toString()); assertEquals("[x, y, z]", m.getAll("ID").toString()); // ordered assertEquals("xyz;", m.getTree().getText()); // whitespace stripped by lexer assertNull(m.get("undefined")); assertEquals("[]", m.getAll("undefined").toString()); } @Test public void testTokenAndRuleMatch() throws Exception { String grammar = "grammar X4;\n" + "s : ID '=' expr ';' ;\n" + "expr : ID | INT ;\n" + "ID : [a-z]+ ;\n" + "INT : [0-9]+ ;\n" + "WS : [ \\r\\n\\t]+ -> skip ;\n"; String input = "x = 99;"; String pattern = "<ID> = <expr> ;"; checkPatternMatch(grammar, "s", input, pattern, "X4"); } @Test public void testTokenTextMatch() throws Exception { String grammar = "grammar X4;\n" + "s : ID '=' expr ';' ;\n" + "expr : ID | INT ;\n" + "ID : [a-z]+ ;\n" + "INT : [0-9]+ ;\n" + "WS : [ \\r\\n\\t]+ -> skip ;\n"; String input = "x = 0;"; String pattern = "<ID> = 1;"; boolean invertMatch = true; // 0!=1 checkPatternMatch(grammar, "s", input, pattern, "X4", invertMatch); input = "x = 0;"; pattern = "<ID> = 0;"; invertMatch = false; checkPatternMatch(grammar, "s", input, pattern, "X4", invertMatch); input = "x = 0;"; pattern = "x = 0;"; invertMatch = false; checkPatternMatch(grammar, "s", input, pattern, "X4", invertMatch); input = "x = 0;"; pattern = "y = 0;"; invertMatch = true; checkPatternMatch(grammar, "s", input, pattern, "X4", invertMatch); } @Test public void testAssign() throws Exception { String grammar = "grammar X5;\n" + "s : expr ';'\n" + //" | 'return' expr ';'\n" + " ;\n" + "expr: expr '.' ID\n" + " | expr '*' expr\n" + " | expr '=' expr\n" + " | ID\n" + " | INT\n" + " ;\n" + "ID : [a-z]+ ;\n" + "INT : [0-9]+ ;\n" + "WS : [ \\r\\n\\t]+ -> skip ;\n"; String input = "x = 99;"; String pattern = "<ID> = <expr>;"; checkPatternMatch(grammar, "s", input, pattern, "X5"); } @Test public void testLRecursiveExpr() throws Exception { String grammar = "grammar X6;\n" + "s : expr ';'\n" + " ;\n" + "expr: expr '.' ID\n" + " | expr '*' expr\n" + " | expr '=' expr\n" + " | ID\n" + " | INT\n" + " ;\n" + "ID : [a-z]+ ;\n" + "INT : [0-9]+ ;\n" + "WS : [ \\r\\n\\t]+ -> skip ;\n"; String input = "3*4*5"; String pattern = "<expr> * <expr> * <expr>"; checkPatternMatch(grammar, "expr", input, pattern, "X6"); } public ParseTreeMatch checkPatternMatch(String grammar, String startRule, String input, String pattern, String grammarName) throws Exception { return checkPatternMatch(grammar, startRule, input, pattern, grammarName, false); } public ParseTreeMatch checkPatternMatch(String grammar, String startRule, String input, String pattern, String grammarName, boolean invertMatch) throws Exception { String grammarFileName = grammarName+".g4"; String parserName = grammarName+"Parser"; String lexerName = grammarName+"Lexer"; boolean ok = rawGenerateAndBuildRecognizer(grammarFileName, grammar, parserName, lexerName, false); assertTrue(ok); ParseTree result = execParser(startRule, input, parserName, lexerName); ParseTreePattern p = getPattern(grammarName, pattern, startRule); ParseTreeMatch match = p.match(result); boolean matched = match.succeeded(); if ( invertMatch ) assertFalse(matched); else assertTrue(matched); return match; } public ParseTreePattern getPattern(String grammarName, String pattern, String ruleName) throws Exception { Class<? extends Lexer> lexerClass = loadLexerClassFromTempDir(grammarName + "Lexer"); Constructor<? extends Lexer> ctor = lexerClass.getConstructor(CharStream.class); Lexer lexer = ctor.newInstance((CharStream) null); Class<? extends Parser> parserClass = loadParserClassFromTempDir(grammarName + "Parser"); Constructor<? extends Parser> pctor = parserClass.getConstructor(TokenStream.class); Parser parser = pctor.newInstance(new CommonTokenStream(lexer)); return parser.compileParseTreePattern(pattern, parser.getRuleIndex(ruleName)); } public ParseTreePatternMatcher getPatternMatcher(String grammarName) throws Exception { Class<? extends Lexer> lexerClass = loadLexerClassFromTempDir(grammarName + "Lexer"); Constructor<? extends Lexer> ctor = lexerClass.getConstructor(CharStream.class); Lexer lexer = ctor.newInstance((CharStream) null); Class<? extends Parser> parserClass = loadParserClassFromTempDir(grammarName + "Parser"); Constructor<? extends Parser> pctor = parserClass.getConstructor(TokenStream.class); Parser parser = pctor.newInstance(new CommonTokenStream(lexer)); return new ParseTreePatternMatcher(lexer, parser); } }
tool/test/org/antlr/v4/test/TestParseTreeMatcher.java
package org.antlr.v4.test; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.Lexer; import org.antlr.v4.runtime.Parser; import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.TokenStream; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.pattern.ParseTreeMatch; import org.antlr.v4.runtime.tree.pattern.ParseTreePattern; import org.antlr.v4.runtime.tree.pattern.ParseTreePatternMatcher; import org.junit.Test; import java.lang.reflect.Constructor; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; public class TestParseTreeMatcher extends BaseTest { @Test public void testChunking() throws Exception { ParseTreePatternMatcher m = new ParseTreePatternMatcher(null, null); assertEquals("[ID, ' = ', expr, ' ;']", m.split("<ID> = <expr> ;").toString()); assertEquals("[' ', ID, ' = ', expr]", m.split(" <ID> = <expr>").toString()); assertEquals("[ID, ' = ', expr]", m.split("<ID> = <expr>").toString()); assertEquals("[expr]", m.split("<expr>").toString()); assertEquals("['<x> foo']", m.split("\\<x\\> foo").toString()); assertEquals("['foo <x> bar ', tag]", m.split("foo \\<x\\> bar <tag>").toString()); } @Test public void testDelimiters() throws Exception { ParseTreePatternMatcher m = new ParseTreePatternMatcher(null, null); m.setDelimiters("<<", ">>", "$"); String result = m.split("<<ID>> = <<expr>> ;$<< ick $>>").toString(); assertEquals("[ID, ' = ', expr, ' ;<< ick >>']", result); } @Test public void testInvertedTags() throws Exception { ParseTreePatternMatcher m= new ParseTreePatternMatcher(null, null); String result = null; try { m.split(">expr<"); } catch (IllegalArgumentException iae) { result = iae.getMessage(); } String expected = "tag delimiters out of order in pattern: >expr<"; assertEquals(expected, result); } @Test public void testUnclosedTag() throws Exception { ParseTreePatternMatcher m = new ParseTreePatternMatcher(null, null); String result = null; try { m.split("<expr hi mom"); } catch (IllegalArgumentException iae) { result = iae.getMessage(); } String expected = "unterminated tag in pattern: <expr hi mom"; assertEquals(expected, result); } @Test public void testExtraClose() throws Exception { ParseTreePatternMatcher m = new ParseTreePatternMatcher(null, null); String result = null; try { m.split("<expr> >"); } catch (IllegalArgumentException iae) { result = iae.getMessage(); } String expected = "missing start tag in pattern: <expr> >"; assertEquals(expected, result); } @Test public void testTokenizingPattern() throws Exception { String grammar = "grammar X1;\n" + "s : ID '=' expr ';' ;\n" + "expr : ID | INT ;\n" + "ID : [a-z]+ ;\n" + "INT : [0-9]+ ;\n" + "WS : [ \\r\\n\\t]+ -> skip ;\n"; boolean ok = rawGenerateAndBuildRecognizer("X1.g4", grammar, "X1Parser", "X1Lexer", false); assertTrue(ok); ParseTreePatternMatcher m = getPatternMatcher("X1"); List<? extends Token> tokens = m.tokenize("<ID> = <expr> ;"); String results = tokens.toString(); String expected = "[ID:3, [@-1,1:1='=',<1>,1:1], expr:7, [@-1,1:1=';',<2>,1:1]]"; assertEquals(expected, results); } @Test public void testCompilingPattern() throws Exception { String grammar = "grammar X2;\n" + "s : ID '=' expr ';' ;\n" + "expr : ID | INT ;\n" + "ID : [a-z]+ ;\n" + "INT : [0-9]+ ;\n" + "WS : [ \\r\\n\\t]+ -> skip ;\n"; boolean ok = rawGenerateAndBuildRecognizer("X2.g4", grammar, "X2Parser", "X2Lexer", false); assertTrue(ok); ParseTreePatternMatcher m = getPatternMatcher("X2"); ParseTreePattern t = m.compile("<ID> = <expr> ;", m.getParser().getRuleIndex("s")); String results = t.getPatternTree().toStringTree(m.getParser()); String expected = "(s <ID> = (expr <expr>) ;)"; assertEquals(expected, results); } @Test public void testHiddenTokensNotSeenByTreePatternParser() throws Exception { String grammar = "grammar X2;\n" + "s : ID '=' expr ';' ;\n" + "expr : ID | INT ;\n" + "ID : [a-z]+ ;\n" + "INT : [0-9]+ ;\n" + "WS : [ \\r\\n\\t]+ -> channel(HIDDEN) ;\n"; boolean ok = rawGenerateAndBuildRecognizer("X2.g4", grammar, "X2Parser", "X2Lexer", false); assertTrue(ok); ParseTreePatternMatcher m = getPatternMatcher("X2"); ParseTreePattern t = m.compile("<ID> = <expr> ;", m.getParser().getRuleIndex("s")); String results = t.getPatternTree().toStringTree(m.getParser()); String expected = "(s <ID> = (expr <expr>) ;)"; assertEquals(expected, results); } @Test public void testCompilingMultipleTokens() throws Exception { String grammar = "grammar X2;\n" + "s : ID '=' ID ';' ;\n" + "ID : [a-z]+ ;\n" + "WS : [ \\r\\n\\t]+ -> skip ;\n"; boolean ok = rawGenerateAndBuildRecognizer("X2.g4", grammar, "X2Parser", "X2Lexer", false); assertTrue(ok); ParseTreePatternMatcher m = getPatternMatcher("X2"); ParseTreePattern t = m.compile("<ID> = <ID> ;", m.getParser().getRuleIndex("s")); String results = t.getPatternTree().toStringTree(m.getParser()); String expected = "(s <ID> = <ID> ;)"; assertEquals(expected, results); } @Test public void testIDNodeMatches() throws Exception { String grammar = "grammar X3;\n" + "s : ID ';' ;\n" + "ID : [a-z]+ ;\n" + "WS : [ \\r\\n\\t]+ -> skip ;\n"; String input = "x ;"; String pattern = "<ID>;"; checkPatternMatch(grammar, "s", input, pattern, "X3"); } @Test public void testIDNodeWithLabelMatches() throws Exception { String grammar = "grammar X8;\n" + "s : ID ';' ;\n" + "ID : [a-z]+ ;\n" + "WS : [ \\r\\n\\t]+ -> skip ;\n"; String input = "x ;"; String pattern = "<id:ID>;"; ParseTreeMatch m = checkPatternMatch(grammar, "s", input, pattern, "X8"); assertEquals("{ID=[x], id=[x]}", m.getLabels().toString()); assertNotNull(m.get("id")); assertNotNull(m.get("ID")); assertEquals("x", m.get("id").getText()); assertEquals("x", m.get("ID").getText()); assertEquals("[x]", m.getAll("id").toString()); assertEquals("[x]", m.getAll("ID").toString()); assertNull(m.get("undefined")); assertEquals("[]", m.getAll("undefined").toString()); } @Test public void testIDNodeWithMultipleLabelMatches() throws Exception { String grammar = "grammar X7;\n" + "s : ID ID ID ';' ;\n" + "ID : [a-z]+ ;\n" + "WS : [ \\r\\n\\t]+ -> skip ;\n"; String input = "x y z;"; String pattern = "<a:ID> <b:ID> <a:ID>;"; ParseTreeMatch m = checkPatternMatch(grammar, "s", input, pattern, "X7"); assertEquals("{ID=[x, y, z], a=[x, z], b=[y]}", m.getLabels().toString()); assertNotNull(m.get("a")); // get first assertNotNull(m.get("b")); assertNotNull(m.get("ID")); assertEquals("x", m.get("a").getText()); assertEquals("y", m.get("b").getText()); assertEquals("x", m.get("ID").getText()); // get first assertEquals("[x, z]", m.getAll("a").toString()); assertEquals("[y]", m.getAll("b").toString()); assertEquals("[x, y, z]", m.getAll("ID").toString()); // ordered assertEquals("xyz;", m.getTree().getText()); // whitespace stripped by lexer assertNull(m.get("undefined")); assertEquals("[]", m.getAll("undefined").toString()); } @Test public void testTokenAndRuleMatch() throws Exception { String grammar = "grammar X4;\n" + "s : ID '=' expr ';' ;\n" + "expr : ID | INT ;\n" + "ID : [a-z]+ ;\n" + "INT : [0-9]+ ;\n" + "WS : [ \\r\\n\\t]+ -> skip ;\n"; String input = "x = 99;"; String pattern = "<ID> = <expr> ;"; checkPatternMatch(grammar, "s", input, pattern, "X4"); } @Test public void testTokenTextMatch() throws Exception { String grammar = "grammar X4;\n" + "s : ID '=' expr ';' ;\n" + "expr : ID | INT ;\n" + "ID : [a-z]+ ;\n" + "INT : [0-9]+ ;\n" + "WS : [ \\r\\n\\t]+ -> skip ;\n"; String input = "x = 0;"; String pattern = "<ID> = 1;"; boolean invertMatch = true; // 0!=1 checkPatternMatch(grammar, "s", input, pattern, "X4", invertMatch); input = "x = 0;"; pattern = "<ID> = 0;"; invertMatch = false; checkPatternMatch(grammar, "s", input, pattern, "X4", invertMatch); input = "x = 0;"; pattern = "x = 0;"; invertMatch = false; checkPatternMatch(grammar, "s", input, pattern, "X4", invertMatch); input = "x = 0;"; pattern = "y = 0;"; invertMatch = true; checkPatternMatch(grammar, "s", input, pattern, "X4", invertMatch); } @Test public void testAssign() throws Exception { String grammar = "grammar X5;\n" + "s : expr ';'\n" + //" | 'return' expr ';'\n" + " ;\n" + "expr: expr '.' ID\n" + " | expr '*' expr\n" + " | expr '=' expr\n" + " | ID\n" + " | INT\n" + " ;\n" + "ID : [a-z]+ ;\n" + "INT : [0-9]+ ;\n" + "WS : [ \\r\\n\\t]+ -> skip ;\n"; String input = "x = 99;"; String pattern = "<ID> = <expr>;"; checkPatternMatch(grammar, "s", input, pattern, "X5"); } @Test public void testLRecursiveExpr() throws Exception { String grammar = "grammar X6;\n" + "s : expr ';'\n" + " ;\n" + "expr: expr '.' ID\n" + " | expr '*' expr\n" + " | expr '=' expr\n" + " | ID\n" + " | INT\n" + " ;\n" + "ID : [a-z]+ ;\n" + "INT : [0-9]+ ;\n" + "WS : [ \\r\\n\\t]+ -> skip ;\n"; String input = "3*4*5"; String pattern = "<expr> * <expr> * <expr>"; checkPatternMatch(grammar, "expr", input, pattern, "X6"); } public ParseTreeMatch checkPatternMatch(String grammar, String startRule, String input, String pattern, String grammarName) throws Exception { return checkPatternMatch(grammar, startRule, input, pattern, grammarName, false); } public ParseTreeMatch checkPatternMatch(String grammar, String startRule, String input, String pattern, String grammarName, boolean invertMatch) throws Exception { String grammarFileName = grammarName+".g4"; String parserName = grammarName+"Parser"; String lexerName = grammarName+"Lexer"; boolean ok = rawGenerateAndBuildRecognizer(grammarFileName, grammar, parserName, lexerName, false); assertTrue(ok); ParseTree result = execParser(startRule, input, parserName, lexerName); ParseTreePattern p = getPattern(grammarName, pattern, startRule); ParseTreeMatch match = p.match(result); boolean matched = match.succeeded(); if ( invertMatch ) assertFalse(matched); else assertTrue(matched); return match; } public ParseTreePattern getPattern(String grammarName, String pattern, String ruleName) throws Exception { Class<? extends Lexer> lexerClass = loadLexerClassFromTempDir(grammarName + "Lexer"); Constructor<? extends Lexer> ctor = lexerClass.getConstructor(CharStream.class); Lexer lexer = ctor.newInstance((CharStream) null); Class<? extends Parser> parserClass = loadParserClassFromTempDir(grammarName + "Parser"); Constructor<? extends Parser> pctor = parserClass.getConstructor(TokenStream.class); Parser parser = pctor.newInstance(new CommonTokenStream(lexer)); return parser.compileParseTreePattern(pattern, parser.getRuleIndex(ruleName)); } public ParseTreePatternMatcher getPatternMatcher(String grammarName) throws Exception { Class<? extends Lexer> lexerClass = loadLexerClassFromTempDir(grammarName + "Lexer"); Constructor<? extends Lexer> ctor = lexerClass.getConstructor(CharStream.class); Lexer lexer = ctor.newInstance((CharStream) null); Class<? extends Parser> parserClass = loadParserClassFromTempDir(grammarName + "Parser"); Constructor<? extends Parser> pctor = parserClass.getConstructor(TokenStream.class); Parser parser = pctor.newInstance(new CommonTokenStream(lexer)); return new ParseTreePatternMatcher(lexer, parser); } }
get last not first when get() finds multiple matching nodes.
tool/test/org/antlr/v4/test/TestParseTreeMatcher.java
get last not first when get() finds multiple matching nodes.
Java
isc
66e8eae9d5990b631b6760e18d3511cd3ca76ca7
0
severin-lemaignan/oro-server
package laas.openrobots.ontology.modules.diff; import java.util.HashSet; import java.util.Set; import laas.openrobots.ontology.Helpers; import laas.openrobots.ontology.IServiceProvider; import laas.openrobots.ontology.Namespaces; import laas.openrobots.ontology.RPCMethod; import laas.openrobots.ontology.backends.IOntologyBackend; import laas.openrobots.ontology.backends.OpenRobotsOntology.ResourceType; import laas.openrobots.ontology.exceptions.NotComparableException; import com.hp.hpl.jena.ontology.Individual; import com.hp.hpl.jena.ontology.OntClass; import com.hp.hpl.jena.ontology.OntModel; import com.hp.hpl.jena.ontology.OntProperty; import com.hp.hpl.jena.ontology.OntResource; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.rdf.model.Property; import com.hp.hpl.jena.rdf.model.RDFNode; import com.hp.hpl.jena.rdf.model.SimpleSelector; import com.hp.hpl.jena.rdf.model.Statement; import com.hp.hpl.jena.rdf.model.StmtIterator; import com.hp.hpl.jena.shared.Lock; import com.hp.hpl.jena.shared.NotFoundException; import com.hp.hpl.jena.util.iterator.ExtendedIterator; import com.hp.hpl.jena.util.iterator.Filter; /** The DiffModule computes differences and similarities between concepts. * * <h2>Type comparison</h2> * Let's consider the following hierarchie: * <pre> * +-------+ * | Thing | * .'+-------._ * .-' ``-._ * +----.'----+ +-----`-------+ * | Artifact | | WhiteObject | * +--.-----.-+ +------+--,---+ * / `-. / \ * +---.'---+ +`-.--+ | \ * | Animal | | Car | / \ * +----+---+ +-----+ | | * \ `. / '. * \ `-. | | * +-----+-------+ +---`------+ | * | WhiteAnimal | | WhiteCar | | * +-------------+ +----------+ / * `'--...__ ,' * ``---........,-' * </pre> * If you're looking for the similarities between concepts WhiteAnimal and * WhiteCar, the {@link #getSimilarities(OntResource, OntResource)} method would * return the set {Artifact, WhiteObject}, ie the set of classes that belong to * the intersection of the super-classes of both the concepts and without sub- * classes in this intersection (the common ancestors). * * On the contrary, the {@link #getDifferences(OntResource, OntResource)} method * returns {Animal, Car} and {WhiteAnimal, WhiteCar}, ie the direct subclasses * of the common ancestors that belongs to the hierarchies of the compared * concepts. * * <h3> Algo principle for common ancestors</h3> * * <pre> * We want S2 such as: * S1 = superclasses(A) ∩ superclasses(B) * S2 = { c / c ∈ S1 AND subclasses(c) ∩ S1 = ∅ } * </pre> * * In the example above, S2 = {Artifact, WhiteObject} * * <h3>Algo principle for first different ancestors</h3> * * <pre> * We want S3 such as: * S3 = ∪ { c / c ∈ S2, * (directsubclasses(c) ∩ superclasses(A)) ∪ * (directsubclasses(c) ∩ superclasses(B)) * } * </pre> * * In the example above, S3 = {{Animal, Car}, {WhiteAnimal, WhiteCar}} * * <h2>Comparison of other properties</h2> * * The {@link #getSimilarities(OntResource, OntResource)} method will return as * well the list of properties that are shared with the same object by both the * concepts. * * The {@link #getDifferences(OntResource, OntResource)} returns on the contrary * properties shared by both concept but with different objects. * * * @author slemaign * * @since 0.6.4 */ public class DiffModule implements IServiceProvider { IOntologyBackend oro; Individual indivA; Individual indivB; OntModel modelA; OntModel modelB; Set<OntClass> typesA; Set<OntClass> typesB; boolean sameClass = false; Property type; public DiffModule(IOntologyBackend oro) { super(); this.oro = oro; type = oro.getModel().getProperty(Namespaces.format("rdf:type")); typesA = new HashSet<OntClass>(); typesB = new HashSet<OntClass>(); } private void loadModels(OntResource conceptA, OntResource conceptB) throws NotComparableException { if (Helpers.getType(conceptA) != Helpers.getType(conceptB)) throw new NotComparableException("Can not compare resources of different kind (a " + Helpers.getType(conceptA) + " and a " + Helpers.getType(conceptB) + " were provided)."); //TODO: Implement a kind of comparison between resources different from individuals if (Helpers.getType(conceptA) != ResourceType.INSTANCE) throw new NotComparableException("Only the comparison between instances (individuals) is currently implemented"); //We recreate two ontology models from details we get for each concepts. modelA = ModelFactory.createOntologyModel(oro.getModel().getSpecification(), oro.getSubmodel(conceptA)); modelB = ModelFactory.createOntologyModel(oro.getModel().getSpecification(), oro.getSubmodel(conceptB)); indivA = oro.getModel().getIndividual(conceptA.getURI()); indivB = oro.getModel().getIndividual(conceptB.getURI()); //get the list of types for concept A (filtering anonymous classes) typesA.clear(); ExtendedIterator<OntClass> tmpA = indivA.listOntClasses(false); while (tmpA.hasNext()){ OntClass c = tmpA.next(); if (!c.isAnon()) typesA.add(c); } //get the list of types for concept B (filtering anonymous classes) typesB.clear(); ExtendedIterator<OntClass> tmpB = indivB.listOntClasses(false); while (tmpB.hasNext()){ OntClass c = tmpB.next(); if (!c.isAnon()) typesB.add(c); } if (typesA.equals(typesB)) sameClass = true; else sameClass = false; } /** Returns the classes that concept A and B have in common, as close as * possible from concept A and B. * * * @return the closest common ancestors of concept A and concept B * @see DiffModule Detailled explanations with a diagram. */ private Set<OntClass> commonAncestors(){ if (sameClass) return indivA.listOntClasses(true).toSet(); //keep the intersection oftypes of A and B. Set<OntClass> commonAncestors = new HashSet<OntClass>(typesB); commonAncestors.retainAll(typesA); //commonAncestors shouldn't be empty: at least owl:Thing should be in //common. assert(!commonAncestors.isEmpty()); //********************************************************************** // Now, some heuristics to optimize the method in special cases. commonAncestors.remove(modelA.getResource(Namespaces.format("owl:Nothing"))); if (commonAncestors.size() == 1) //owl:Thing return commonAncestors; commonAncestors.remove(modelA.getResource(Namespaces.format("owl:Thing"))); //********************************************************************** Set<OntClass> result = new HashSet<OntClass>(commonAncestors); for (OntClass c : commonAncestors) { if (result.size() == 1) return result; //We need to retrieve the class c IN the main ontology model to be //able to get the subclasses. OntClass classInOro = oro.getModel().getOntClass(c.getURI()); assert(c.equals(classInOro)); Set<OntClass> subClassesC = oro.getSubclassesOf(classInOro, false); subClassesC.retainAll(commonAncestors); if (!subClassesC.isEmpty()) result.remove(c); } return result; } /** Returns the first different ancestors class of concept A and B. * * * Algo principle for first different ancestors: * * With S2 defined as in commonAncestor() method documentation, * We want S4A and S4B such as: * S3 = ∪ { c / c ∈ S2, directsubclasses(c)} * S4A = S3 ∩ superclasses(A) * S4B = S3 ∩ superclasses(B) * * @return The first differents ancestors of concept A and B. * @see DiffModule Detailled explanations with a diagram. */ private Set<Set<Statement>> firstDifferentAncestors(){ //********************************************************************** Set<Set<Statement>> result = new HashSet<Set<Statement>>(); if (sameClass) return result; for (OntClass c : commonAncestors()) { //We need to retrieve the class c IN the main ontology model to be //able to get the subclasses. OntClass classInOro = oro.getModel().getOntClass(c.getURI()); assert(c.equals(classInOro)); Set<OntClass> directSubClassesC = oro.getSubclassesOf(classInOro, true); Set<OntClass> directSubClassesCbis = new HashSet<OntClass>(directSubClassesC); // Keep only ancestors of A that are direct subclasses of the current // common ancestors of both A and B. Set<Statement> ancestorsForC = new HashSet<Statement>(); directSubClassesC.retainAll(typesA); if (directSubClassesC.isEmpty()) directSubClassesC.add(c); for (OntClass dsc : directSubClassesC) ancestorsForC.add(oro.getModel().createStatement(indivA, type, dsc)); //Idem for B directSubClassesCbis.retainAll(typesB); if (directSubClassesCbis.isEmpty()) directSubClassesCbis.add(c); for (OntClass dsc : directSubClassesCbis) ancestorsForC.add(oro.getModel().createStatement(indivB, type, dsc)); if (!ancestorsForC.isEmpty()) result.add(ancestorsForC); } return result; } /*********************** Common properties*********************************/ private Set<OntProperty> commonProperties() { //Creates a filter to keep only properties in the default ORO namespace, // thus removing properties inferred from RDF or OWL models. Filter<OntProperty> defaultNsFilter = new Filter<OntProperty>() { public boolean accept(OntProperty p) { if (p.getNameSpace().equals(Namespaces.DEFAULT_NS)) return true; return false; } }; Set<OntProperty> propA = modelA.listOntProperties().filterKeep(defaultNsFilter).toSet(); Set <OntProperty> commonProp = modelB.listOntProperties().filterKeep(defaultNsFilter).toSet(); commonProp.retainAll(propA); return commonProp; } /***************** DIFFERENCES *********************/ /** Returns the computed differences between two concepts, relying on * asserted and inferred fact in the ontology. * * @see DiffModule Detailled explanations with a diagram. * @see #getDifferences(String, String) Same "stringified" method. */ public Set<Set<String>> getDifferences(OntResource conceptA, OntResource conceptB) throws NotComparableException { Set<Set<String>> result = new HashSet<Set<String>>(); oro.getModel().enterCriticalSection(Lock.READ); loadModels(conceptA, conceptB); for (Set<Statement> ss : firstDifferentAncestors()) { Set<String> resultForC = new HashSet<String>(); for (Statement s : ss) resultForC.add(Namespaces.toLightString(s)); result.add(resultForC); } //******************** Different properties **************************** for (OntProperty p : commonProperties()) { Set<String> resultForP = new HashSet<String>(); //First build a set of all the object in A's model for the current //property. Set<RDFNode> objPropA = indivA.listPropertyValues(p).toSet(); //Do the same for B. Set<RDFNode> objPropB = indivB.listPropertyValues(p).toSet(); if (objPropA.equals(objPropB)) continue; //Keep only the object of A that are not present for B Set<RDFNode> diffPropA = new HashSet<RDFNode>(objPropA); diffPropA.removeAll(objPropB); assert(!diffPropA.isEmpty()); //shouldn't be empty since we are iterating of common properties //Keep only the object of B that are not present for A Set<RDFNode> diffPropB = new HashSet<RDFNode>(objPropB); diffPropB.removeAll(objPropA); assert(!diffPropB.isEmpty()); //shouldn't be empty since we are iterating of common properties for (RDFNode o : diffPropA) resultForP.add(Namespaces.toLightString(indivA) + " " + Namespaces.toLightString(p) + " " + Namespaces.toLightString(o)); for (RDFNode o : diffPropB) resultForP.add(Namespaces.toLightString(indivB) + " " + Namespaces.toLightString(p) + " " + Namespaces.toLightString(o)); result.add(resultForP); } oro.getModel().leaveCriticalSection(); return result; } /** Returns the differences between two concepts (in their literal * representation). * * @param conceptA The first concept to compare * @param conceptB The second concept to compare * @return the computed differences between two concepts as a set of sets of * stringified statements: for each different property (including type), a * set of statement that explain for each concept its relation. * @throws NotFoundException * @throws NotComparableException * @see DiffModule Detailled explanations with a diagram. * @see #getDifferences(OntResource, OntResource) */ @RPCMethod( desc="given two concepts, return the list of relevant differences (types, properties...) between these concepts." ) public Set<Set<String>> getDifferences(String conceptA, String conceptB) throws NotFoundException, NotComparableException { oro.getModel().enterCriticalSection(Lock.READ); OntResource resA = oro.getModel().getOntResource(Namespaces.format(conceptA)); OntResource resB = oro.getModel().getOntResource(Namespaces.format(conceptB)); oro.getModel().leaveCriticalSection(); if (resA == null) throw new NotFoundException("Concept " + conceptA + " doesn't exist in the ontology."); if (resB == null) throw new NotFoundException("Concept " + conceptB + " doesn't exist in the ontology."); return getDifferences(resA, resB); } /***************** SIMILARITIES *********************/ /** Returns the computed similarities between two concepts, relying on * asserted and inferred fact in the ontology. * * @see DiffModule Detailled explanations with a diagram. * @see #getSimilarities(String, String) Same "stringified" method. */ public Set<String> getSimilarities(OntResource conceptA, OntResource conceptB) throws NotComparableException { Set<String> result = new HashSet<String>(); oro.getModel().enterCriticalSection(Lock.READ); loadModels(conceptA, conceptB); //*********************** Common ancestors ***************************** for (OntClass c : commonAncestors()) { result.add("? rdf:type " + Namespaces.toLightString(c)); } //*********************** Common properties **************************** for (OntProperty p : commonProperties()) { //First build a set of all the object in A's model for the current //property. Set<RDFNode> objPropA = indivA.listPropertyValues(p).toSet(); //Do the same for B and keep only the common ones. Set<RDFNode> objPropB = indivB.listPropertyValues(p).toSet(); objPropB.retainAll(objPropA); for (RDFNode o : objPropB) result.add("? " + Namespaces.toLightString(p) + " " + Namespaces.toLightString(o)); } oro.getModel().leaveCriticalSection(); return result; } /** Returns the similarities between two concepts (in their literal * representation). * * @param conceptA The first concept to compare * @param conceptB The second concept to compare * @return the computed similarities between two concepts as a set of * stringified partial statements: for each similar property (including * type), a string of form "? prop obj" is returned. * @throws NotFoundException * @throws NotComparableException * @see DiffModule Detailled explanations with a diagram. * @see #getSimilarities(OntResource, OntResource) */ @RPCMethod( desc="given two concepts, return the list of relevant similarities (types, properties...) between these concepts." ) public Set<String> getSimilarities(String conceptA, String conceptB) throws NotFoundException, NotComparableException { oro.getModel().enterCriticalSection(Lock.READ); OntResource resA = oro.getModel().getOntResource(Namespaces.format(conceptA)); OntResource resB = oro.getModel().getOntResource(Namespaces.format(conceptB)); oro.getModel().leaveCriticalSection(); if (resA == null) throw new NotFoundException("Concept " + conceptA + " doesn't exist in the ontology."); if (resB == null) throw new NotFoundException("Concept " + conceptB + " doesn't exist in the ontology."); return getSimilarities(resA, resB); } }
src/laas/openrobots/ontology/modules/diff/DiffModule.java
package laas.openrobots.ontology.modules.diff; import java.util.HashSet; import java.util.Set; import laas.openrobots.ontology.Helpers; import laas.openrobots.ontology.IServiceProvider; import laas.openrobots.ontology.Namespaces; import laas.openrobots.ontology.RPCMethod; import laas.openrobots.ontology.backends.IOntologyBackend; import laas.openrobots.ontology.backends.OpenRobotsOntology.ResourceType; import laas.openrobots.ontology.exceptions.NotComparableException; import com.hp.hpl.jena.ontology.Individual; import com.hp.hpl.jena.ontology.OntClass; import com.hp.hpl.jena.ontology.OntModel; import com.hp.hpl.jena.ontology.OntProperty; import com.hp.hpl.jena.ontology.OntResource; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.rdf.model.Property; import com.hp.hpl.jena.rdf.model.RDFNode; import com.hp.hpl.jena.rdf.model.SimpleSelector; import com.hp.hpl.jena.rdf.model.Statement; import com.hp.hpl.jena.rdf.model.StmtIterator; import com.hp.hpl.jena.shared.Lock; import com.hp.hpl.jena.shared.NotFoundException; import com.hp.hpl.jena.util.iterator.ExtendedIterator; import com.hp.hpl.jena.util.iterator.Filter; /** The DiffModule computes differences and similarities between concepts. * * <h2>Type comparison</h2> * Let's consider the following hierarchie: * <pre> * +-------+ * | Thing | * .'+-------._ * .-' ``-._ * +----.'----+ +-----`-------+ * | Artifact | | WhiteObject | * +--.-----.-+ +------+--,---+ * / `-. / \ * +---.'---+ +`-.--+ | \ * | Animal | | Car | / \ * +----+---+ +-----+ | | * \ `. / '. * \ `-. | | * +-----+-------+ +---`------+ | * | WhiteAnimal | | WhiteCar | | * +-------------+ +----------+ / * `'--...__ ,' * ``---........,-' * </pre> * If you're looking for the similarities between concepts WhiteAnimal and * WhiteCar, the {@link #getSimilarities(OntResource, OntResource)} method would * return the set {Artifact, WhiteObject}, ie the set of classes that belong to * the intersection of the super-classes of both the concepts and without sub- * classes in this intersection (the common ancestors). * * On the contrary, the {@link #getDifferences(OntResource, OntResource)} method * returns {Animal, Car} and {WhiteAnimal, WhiteCar}, ie the direct subclasses * of the common ancestors that belongs to the hierarchies of the compared * concepts. * * <h3> Algo principle for common ancestors</h3> * * <pre> * We want S2 such as: * S1 = superclasses(A) ∩ superclasses(B) * S2 = { c / c ∈ S1 AND subclasses(c) ∩ S1 = ∅ } * </pre> * * In the example above, S2 = {Artifact, WhiteObject} * * <h3>Algo principle for first different ancestors</h3> * * <pre> * We want S3 such as: * S3 = ∪ { c / c ∈ S2, * (directsubclasses(c) ∩ superclasses(A)) ∪ * (directsubclasses(c) ∩ superclasses(B)) * } * </pre> * * In the example above, S3 = {{Animal, Car}, {WhiteAnimal, WhiteCar}} * * <h2>Comparison of other properties</h2> * * The {@link #getSimilarities(OntResource, OntResource)} method will return as * well the list of properties that are shared with the same object by both the * concepts. * * The {@link #getDifferences(OntResource, OntResource)} returns on the contrary * properties shared by both concept but with different objects. * * * @author slemaign * * @since 0.6.4 */ public class DiffModule implements IServiceProvider { IOntologyBackend oro; Individual indivA; Individual indivB; OntModel modelA; OntModel modelB; Set<OntClass> typesA; Set<OntClass> typesB; boolean sameClass = false; Property type; public DiffModule(IOntologyBackend oro) { super(); this.oro = oro; type = oro.getModel().getProperty(Namespaces.format("rdf:type")); typesA = new HashSet<OntClass>(); typesB = new HashSet<OntClass>(); } private void loadModels(OntResource conceptA, OntResource conceptB) throws NotComparableException { if (Helpers.getType(conceptA) != Helpers.getType(conceptB)) throw new NotComparableException("Can not compare resources of different kind (a " + Helpers.getType(conceptA) + " and a " + Helpers.getType(conceptB) + " were provided)."); //TODO: Implement a kind of comparison between resources different from individuals if (Helpers.getType(conceptA) != ResourceType.INSTANCE) throw new NotComparableException("Only the comparison between instances (individuals) is currently implemented"); //We recreate two ontology models from details we get for each concepts. oro.getModel().enterCriticalSection(Lock.READ); modelA = ModelFactory.createOntologyModel(oro.getModel().getSpecification(), oro.getSubmodel(conceptA)); modelB = ModelFactory.createOntologyModel(oro.getModel().getSpecification(), oro.getSubmodel(conceptB)); indivA = oro.getModel().getIndividual(conceptA.getURI()); indivB = oro.getModel().getIndividual(conceptB.getURI()); //get the list of types for concept A (filtering anonymous classes) typesA.clear(); ExtendedIterator<OntClass> tmpA = indivA.listOntClasses(false); while (tmpA.hasNext()){ OntClass c = tmpA.next(); if (!c.isAnon()) typesA.add(c); } //get the list of types for concept B (filtering anonymous classes) typesB.clear(); ExtendedIterator<OntClass> tmpB = indivB.listOntClasses(false); while (tmpB.hasNext()){ OntClass c = tmpB.next(); if (!c.isAnon()) typesB.add(c); } if (typesA.equals(typesB)) sameClass = true; else sameClass = false; oro.getModel().leaveCriticalSection(); } /** Returns the classes that concept A and B have in common, as close as * possible from concept A and B. * * * @return the closest common ancestors of concept A and concept B * @see DiffModule Detailled explanations with a diagram. */ private Set<OntClass> commonAncestors(){ if (sameClass) return indivA.listOntClasses(true).toSet(); //keep the intersection oftypes of A and B. Set<OntClass> commonAncestors = new HashSet<OntClass>(typesB); commonAncestors.retainAll(typesA); //commonAncestors shouldn't be empty: at least owl:Thing should be in //common. assert(!commonAncestors.isEmpty()); //********************************************************************** // Now, some heuristics to optimize the method in special cases. commonAncestors.remove(modelA.getResource(Namespaces.format("owl:Nothing"))); if (commonAncestors.size() == 1) //owl:Thing return commonAncestors; commonAncestors.remove(modelA.getResource(Namespaces.format("owl:Thing"))); //********************************************************************** Set<OntClass> result = new HashSet<OntClass>(commonAncestors); oro.getModel().enterCriticalSection(Lock.READ); for (OntClass c : commonAncestors) { if (result.size() == 1) return result; //We need to retrieve the class c IN the main ontology model to be //able to get the subclasses. OntClass classInOro = oro.getModel().getOntClass(c.getURI()); assert(c.equals(classInOro)); Set<OntClass> subClassesC = oro.getSubclassesOf(classInOro, false); subClassesC.retainAll(commonAncestors); if (!subClassesC.isEmpty()) result.remove(c); } oro.getModel().leaveCriticalSection(); return result; } /** Returns the first different ancestors class of concept A and B. * * * Algo principle for first different ancestors: * * With S2 defined as in commonAncestor() method documentation, * We want S4A and S4B such as: * S3 = ∪ { c / c ∈ S2, directsubclasses(c)} * S4A = S3 ∩ superclasses(A) * S4B = S3 ∩ superclasses(B) * * @return The first differents ancestors of concept A and B. * @see DiffModule Detailled explanations with a diagram. */ private Set<Set<Statement>> firstDifferentAncestors(){ //********************************************************************** Set<Set<Statement>> result = new HashSet<Set<Statement>>(); if (sameClass) return result; oro.getModel().enterCriticalSection(Lock.READ); for (OntClass c : commonAncestors()) { //We need to retrieve the class c IN the main ontology model to be //able to get the subclasses. OntClass classInOro = oro.getModel().getOntClass(c.getURI()); assert(c.equals(classInOro)); Set<OntClass> directSubClassesC = oro.getSubclassesOf(classInOro, true); Set<OntClass> directSubClassesCbis = new HashSet<OntClass>(directSubClassesC); // Keep only ancestors of A that are direct subclasses of the current // common ancestors of both A and B. Set<Statement> ancestorsForC = new HashSet<Statement>(); directSubClassesC.retainAll(typesA); if (directSubClassesC.isEmpty()) directSubClassesC.add(c); for (OntClass dsc : directSubClassesC) ancestorsForC.add(oro.getModel().createStatement(indivA, type, dsc)); //Idem for B directSubClassesCbis.retainAll(typesB); if (directSubClassesCbis.isEmpty()) directSubClassesCbis.add(c); for (OntClass dsc : directSubClassesCbis) ancestorsForC.add(oro.getModel().createStatement(indivB, type, dsc)); if (!ancestorsForC.isEmpty()) result.add(ancestorsForC); } oro.getModel().leaveCriticalSection(); return result; } /*********************** Common properties*********************************/ private Set<OntProperty> commonProperties() { //Creates a filter to keep only properties in the default ORO namespace, // thus removing properties inferred from RDF or OWL models. Filter<OntProperty> defaultNsFilter = new Filter<OntProperty>() { public boolean accept(OntProperty p) { if (p.getNameSpace().equals(Namespaces.DEFAULT_NS)) return true; return false; } }; Set<OntProperty> propA = modelA.listOntProperties().filterKeep(defaultNsFilter).toSet(); Set <OntProperty> commonProp = modelB.listOntProperties().filterKeep(defaultNsFilter).toSet(); commonProp.retainAll(propA); return commonProp; } /***************** DIFFERENCES *********************/ /** Returns the computed differences between two concepts, relying on * asserted and inferred fact in the ontology. * * @see DiffModule Detailled explanations with a diagram. * @see #getDifferences(String, String) Same "stringified" method. */ public Set<Set<String>> getDifferences(OntResource conceptA, OntResource conceptB) throws NotComparableException { Set<Set<String>> result = new HashSet<Set<String>>(); loadModels(conceptA, conceptB); for (Set<Statement> ss : firstDifferentAncestors()) { Set<String> resultForC = new HashSet<String>(); for (Statement s : ss) resultForC.add(Namespaces.toLightString(s)); result.add(resultForC); } //******************** Different properties **************************** for (OntProperty p : commonProperties()) { Set<String> resultForP = new HashSet<String>(); //First build a set of all the object in A's model for the current //property. Set<RDFNode> objPropA = indivA.listPropertyValues(p).toSet(); //Do the same for B. Set<RDFNode> objPropB = indivB.listPropertyValues(p).toSet(); if (objPropA.equals(objPropB)) continue; //Keep only the object of A that are not present for B Set<RDFNode> diffPropA = new HashSet<RDFNode>(objPropA); diffPropA.removeAll(objPropB); assert(!diffPropA.isEmpty()); //shouldn't be empty since we are iterating of common properties //Keep only the object of B that are not present for A Set<RDFNode> diffPropB = new HashSet<RDFNode>(objPropB); diffPropB.removeAll(objPropA); assert(!diffPropB.isEmpty()); //shouldn't be empty since we are iterating of common properties for (RDFNode o : diffPropA) resultForP.add(Namespaces.toLightString(indivA) + " " + Namespaces.toLightString(p) + " " + Namespaces.toLightString(o)); for (RDFNode o : diffPropB) resultForP.add(Namespaces.toLightString(indivB) + " " + Namespaces.toLightString(p) + " " + Namespaces.toLightString(o)); result.add(resultForP); } return result; } /** Returns the differences between two concepts (in their literal * representation). * * @param conceptA The first concept to compare * @param conceptB The second concept to compare * @return the computed differences between two concepts as a set of sets of * stringified statements: for each different property (including type), a * set of statement that explain for each concept its relation. * @throws NotFoundException * @throws NotComparableException * @see DiffModule Detailled explanations with a diagram. * @see #getDifferences(OntResource, OntResource) */ @RPCMethod( desc="given two concepts, return the list of relevant differences (types, properties...) between these concepts." ) public Set<Set<String>> getDifferences(String conceptA, String conceptB) throws NotFoundException, NotComparableException { oro.getModel().enterCriticalSection(Lock.READ); OntResource resA = oro.getModel().getOntResource(Namespaces.format(conceptA)); OntResource resB = oro.getModel().getOntResource(Namespaces.format(conceptB)); oro.getModel().leaveCriticalSection(); if (resA == null) throw new NotFoundException("Concept " + conceptA + " doesn't exist in the ontology."); if (resB == null) throw new NotFoundException("Concept " + conceptB + " doesn't exist in the ontology."); return getDifferences(resA, resB); } /***************** SIMILARITIES *********************/ /** Returns the computed similarities between two concepts, relying on * asserted and inferred fact in the ontology. * * @see DiffModule Detailled explanations with a diagram. * @see #getSimilarities(String, String) Same "stringified" method. */ public Set<String> getSimilarities(OntResource conceptA, OntResource conceptB) throws NotComparableException { Set<String> result = new HashSet<String>(); loadModels(conceptA, conceptB); //*********************** Common ancestors ***************************** for (OntClass c : commonAncestors()) { result.add("? rdf:type " + Namespaces.toLightString(c)); } //*********************** Common properties **************************** for (OntProperty p : commonProperties()) { //First build a set of all the object in A's model for the current //property. Set<RDFNode> objPropA = indivA.listPropertyValues(p).toSet(); //Do the same for B and keep only the common ones. Set<RDFNode> objPropB = indivB.listPropertyValues(p).toSet(); objPropB.retainAll(objPropA); for (RDFNode o : objPropB) result.add("? " + Namespaces.toLightString(p) + " " + Namespaces.toLightString(o)); } return result; } /** Returns the similarities between two concepts (in their literal * representation). * * @param conceptA The first concept to compare * @param conceptB The second concept to compare * @return the computed similarities between two concepts as a set of * stringified partial statements: for each similar property (including * type), a string of form "? prop obj" is returned. * @throws NotFoundException * @throws NotComparableException * @see DiffModule Detailled explanations with a diagram. * @see #getSimilarities(OntResource, OntResource) */ @RPCMethod( desc="given two concepts, return the list of relevant similarities (types, properties...) between these concepts." ) public Set<String> getSimilarities(String conceptA, String conceptB) throws NotFoundException, NotComparableException { oro.getModel().enterCriticalSection(Lock.READ); OntResource resA = oro.getModel().getOntResource(Namespaces.format(conceptA)); OntResource resB = oro.getModel().getOntResource(Namespaces.format(conceptB)); oro.getModel().leaveCriticalSection(); if (resA == null) throw new NotFoundException("Concept " + conceptA + " doesn't exist in the ontology."); if (resB == null) throw new NotFoundException("Concept " + conceptB + " doesn't exist in the ontology."); return getSimilarities(resA, resB); } }
Fixed issue with ontology locking while diffing
src/laas/openrobots/ontology/modules/diff/DiffModule.java
Fixed issue with ontology locking while diffing
Java
mit
8e4e3e26a11a902923eb61a857a2f3a61315376b
0
codistmonk/IMJ
package imj3.draft; import static multij.tools.Tools.*; import static multij.xml.XMLTools.getNodes; import static multij.xml.XMLTools.parse; import java.awt.Rectangle; import java.awt.Shape; import java.awt.geom.AffineTransform; import java.awt.geom.Area; import java.awt.geom.Path2D; import java.awt.geom.PathIterator; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import java.io.UncheckedIOException; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Scanner; import java.util.TreeMap; import java.util.regex.Pattern; import multij.tools.CommandLineArgumentsParser; import multij.tools.IllegalInstantiationException; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * @author codistmonk (creation 2015-07-21) */ public final class SVGTools { private SVGTools() { throw new IllegalInstantiationException(); } public static final String COMMANDS = "MmLlQqCcZz"; public static final String NUMERICAL = "0-9.-"; public static final Pattern COMMAND_PATTERN = Pattern.compile("[" + COMMANDS + "]"); public static final String NUMBER_PATTERN = "[" + NUMERICAL + "]+"; /** * @param commandLineArguments * <br>Must not be null */ public static void main(final String[] commandLineArguments) { final CommandLineArgumentsParser arguments = new CommandLineArgumentsParser(commandLineArguments); final File svgFile = new File(arguments.get("svg", "")); final Document svg = readXML(svgFile); final Map<String, List<Area>> regions = getRegions(svg); final int lod = arguments.get("lod", 0)[0]; final int x = arguments.get("x", 6000)[0]; final int y = arguments.get("y", 12000)[0]; final int w = arguments.get("w", 512)[0]; final int h = arguments.get("h", 512)[0]; final int x0 = x << lod; final int y0 = y << lod; final int w0 = w << lod; final int h0 = h << lod; { final Map<String, Double> classRatios = normalize(getClassSurfaces(new Rectangle(x0, y0, w0, h0), regions)); debugPrint(classRatios); } } public static final Document readXML(final File file) { try (final InputStream input = new FileInputStream(file)) { return parse(input); } catch (final IOException exception) { throw new UncheckedIOException(exception); } } public static final Document readXMLOrNull(final File file) { try { return readXML(file); } catch (final Exception exception) { ignore(exception); return null; } } public static final <K> Map<K, Double> normalize(final Map<K, Double> map) { final double[] total = { 0.0 }; map.values().forEach(v -> total[0] += v); return normalize(map, total[0]); } public static final <K> Map<K, Double> normalize(final Map<K, Double> map, final double total) { map.replaceAll((k, v) -> v / total); return map; } public static final Map<String, List<Area>> getRegions(final Document svg) { return getRegions(svg, null); } public static final Map<String, List<Area>> getRegions(final Document svg, final Map<Object, Object> regionElements) { final Map<String, List<Area>> result = new TreeMap<>(); for (final Element regionElement : getRegionElements(svg)) { final String classId = regionElement.getAttribute("imj:classId"); final Area region = newRegion(regionElement); result.computeIfAbsent(classId, k -> new ArrayList<>()).add(region); if (regionElements != null) { regionElements.put(region, regionElement); } } return result; } @SuppressWarnings("unchecked") public static final List<Element> getRegionElements(final Document svg) { return (List<Element>) (Object) getNodes(svg, "//path|//polygon"); } public static final Map<String, Double> getClassSurfaces(final Shape shape, final Map<String, List<Area>> regions) { final Map<String, Double> result = new TreeMap<>(); final double flatness = 1.0; for (final Map.Entry<String, List<Area>> entry : regions.entrySet()) { final String classId = entry.getKey(); for (final Area region : entry.getValue()) { final Area intersection = new Area(shape); intersection.intersect(region); if (!intersection.isEmpty()) { result.compute(classId, (k, v) -> (v == null ? 0.0 : v) + getSurface(intersection, flatness)); } } } return result; } public static final double getSurface(final Shape shape, final double flatness) { return getSurface(shape, new AffineTransform(), flatness); } public static final double getSurface(final Shape shape, final AffineTransform transform, final double flatness) { final PathIterator pathIterator = shape.getPathIterator(transform, flatness); final double[] first = new double[2]; final double[] previous = new double[2]; final double[] current = new double[2]; double sum = 0.0; while (!pathIterator.isDone()) { switch (pathIterator.currentSegment(current)) { case PathIterator.SEG_CLOSE: sum -= previous[0] * first[1] - previous[1] * first[0]; break; case PathIterator.SEG_LINETO: sum -= previous[0] * current[1] - previous[1] * current[0]; System.arraycopy(current, 0, previous, 0, 2); break; case PathIterator.SEG_MOVETO: System.arraycopy(current, 0, first, 0, 2); System.arraycopy(current, 0, previous, 0, 2); break; case PathIterator.SEG_CUBICTO: case PathIterator.SEG_QUADTO: throw new IllegalStateException(); } pathIterator.next(); } return sum / 2.0; } public static final Area newRegion(final Element svgShape) { final Path2D path = new Path2D.Double(); path.setWindingRule(Path2D.WIND_EVEN_ODD); if ("polygon".equals(svgShape.getTagName())) { boolean first = true; try (final Scanner scanner = new Scanner(svgShape.getAttribute("points"))) { scanner.useLocale(Locale.ENGLISH); scanner.useDelimiter("[^0-9.-]"); while (scanner.hasNext()) { final double x = scanner.nextDouble(); final double y = scanner.nextDouble(); if (first) { first = false; path.moveTo(x, y); } else { path.lineTo(x, y); } } } path.closePath(); } else if ("path".equals(svgShape.getTagName())) { try (final Scanner scanner = new Scanner(svgShape.getAttribute("d"))) { scanner.useLocale(Locale.ENGLISH); double firstX = 0.0; double firstY = 0.0; double lastX = 0.0; double lastY = 0.0; String command = nextCommand(scanner, "M"); while (scanner.hasNext()) { final boolean relative = Character.isLowerCase(command.charAt(0)); if ("zZ".contains(command)) { path.closePath(); lastX = firstX; lastY = firstY; } else if ("mM".contains(command)) { final double x = nextDouble(scanner, relative, lastX); final double y = nextDouble(scanner, relative, lastY); path.moveTo(x, y); command = relative ? "l" : "L"; lastX = firstX = x; lastY = firstY = y; } else if ("lL".contains(command)) { final double x = nextDouble(scanner, relative, lastX); final double y = nextDouble(scanner, relative, lastY); path.lineTo(x, y); lastX = x; lastY = y; } else if ("qQ".contains(command)) { final double x1 = nextDouble(scanner, relative, lastX); final double y1 = nextDouble(scanner, relative, lastY); final double x = nextDouble(scanner, relative, x1); final double y = nextDouble(scanner, relative, y1); path.quadTo(x1, y1, x, y); lastX = x; lastY = y; } else if ("cC".contains(command)) { final double x1 = nextDouble(scanner, relative, lastX); final double y1 = nextDouble(scanner, relative, lastY); final double x2 = nextDouble(scanner, relative, x1); final double y2 = nextDouble(scanner, relative, y1); final double x = nextDouble(scanner, relative, x2); final double y = nextDouble(scanner, relative, y2); path.curveTo(x1, y1, x2, y2, x, y); lastX = x; lastY = y; } command = nextCommand(scanner, command); } } } return new Area(path); } public static final String nextCommand(final Scanner scanner, final String oldCommand) { scanner.useDelimiter(" *"); final String result = scanner.hasNext(COMMAND_PATTERN) ? scanner.next(COMMAND_PATTERN) : oldCommand; scanner.useDelimiter("[^" + NUMERICAL + "]+"); return result; } public static final double nextDouble(final Scanner scanner, final boolean relative, final double last) { return scanner.nextDouble() + (relative ? last : 0.0); } /** * @author codistmonk (creation 2015-06-05) */ public static final class Region implements Serializable { private final int label; private final Rectangle bounds; private final BufferedImage mask; public Region(final int label, final Rectangle bounds, final BufferedImage mask) { this.label = label; this.bounds = bounds; this.mask = mask; } public final int getLabel() { return this.label; } public final Rectangle getBounds() { return this.bounds; } public final BufferedImage getMask() { return this.mask; } public final long getSize() { final int width = this.getMask().getWidth(); final int height = this.getMask().getHeight(); long result = 0L; for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { if ((this.getMask().getRGB(x, y) & 1) != 0) { ++result; } } } return result; } private static final long serialVersionUID = 3168354082192346491L; } }
src/imj3/draft/SVGTools.java
package imj3.draft; import static multij.tools.Tools.*; import static multij.xml.XMLTools.getNodes; import static multij.xml.XMLTools.parse; import java.awt.Rectangle; import java.awt.Shape; import java.awt.geom.AffineTransform; import java.awt.geom.Area; import java.awt.geom.Path2D; import java.awt.geom.PathIterator; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import java.io.UncheckedIOException; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Scanner; import java.util.TreeMap; import java.util.regex.Pattern; import multij.tools.CommandLineArgumentsParser; import multij.tools.IllegalInstantiationException; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * @author codistmonk (creation 2015-07-21) */ public final class SVGTools { private SVGTools() { throw new IllegalInstantiationException(); } public static final String COMMANDS = "MmLlQqCcZz"; public static final String NUMERICAL = "0-9.-"; public static final Pattern COMMAND_PATTERN = Pattern.compile("[" + COMMANDS + "]"); public static final String NUMBER_PATTERN = "[" + NUMERICAL + "]+"; /** * @param commandLineArguments * <br>Must not be null */ public static void main(final String[] commandLineArguments) { final CommandLineArgumentsParser arguments = new CommandLineArgumentsParser(commandLineArguments); final File svgFile = new File(arguments.get("svg", "")); final Document svg = readXML(svgFile); final Map<String, List<Area>> regions = getRegions(svg); final int lod = arguments.get("lod", 0)[0]; final int x = arguments.get("x", 6000)[0]; final int y = arguments.get("y", 12000)[0]; final int w = arguments.get("w", 512)[0]; final int h = arguments.get("h", 512)[0]; final int x0 = x << lod; final int y0 = y << lod; final int w0 = w << lod; final int h0 = h << lod; { final Map<String, Double> classRatios = normalize(getClassSurfaces(new Rectangle(x0, y0, w0, h0), regions)); debugPrint(classRatios); } } public static final Document readXML(final File file) { try (final InputStream input = new FileInputStream(file)) { return parse(input); } catch (final IOException exception) { throw new UncheckedIOException(exception); } } public static final Document readXMLOrNull(final File file) { try { return readXML(file); } catch (final Exception exception) { ignore(exception); return null; } } public static final <K> Map<K, Double> normalize(final Map<K, Double> map) { final double[] total = { 0.0 }; map.values().forEach(v -> total[0] += v); return normalize(map, total[0]); } public static final <K> Map<K, Double> normalize(final Map<K, Double> map, final double total) { map.replaceAll((k, v) -> v / total); return map; } public static final Map<String, List<Area>> getRegions(final Document svg) { return getRegions(svg, null); } public static final Map<String, List<Area>> getRegions(final Document svg, final Map<Object, Object> regionElements) { final Map<String, List<Area>> result = new TreeMap<>(); for (final Element regionElement : getRegionElements(svg)) { final String classId = regionElement.getAttribute("imj:classId"); final Area region = newRegion(regionElement); result.computeIfAbsent(classId, k -> new ArrayList<>()).add(region); if (regionElements != null) { regionElements.put(region, regionElement); } } return result; } @SuppressWarnings("unchecked") public static final List<Element> getRegionElements(final Document svg) { return (List<Element>) (Object) getNodes(svg, "//path|//polygon"); } public static final Map<String, Double> getClassSurfaces(final Shape shape, final Map<String, List<Area>> regions) { final Map<String, Double> result = new TreeMap<>(); final double flatness = 1.0; for (final Map.Entry<String, List<Area>> entry : regions.entrySet()) { final String classId = entry.getKey(); for (final Area region : entry.getValue()) { final Area intersection = new Area(shape); intersection.intersect(region); if (!intersection.isEmpty()) { result.compute(classId, (k, v) -> (v == null ? 0.0 : v) + getSurface(intersection, flatness)); } } } return result; } public static double getSurface(final Shape shape, final double flatness) { final double[] surface = { 0.0 }; final PathIterator pathIterator = shape.getPathIterator(new AffineTransform(), flatness); final double[] first = new double[2]; final double[] previous = new double[2]; final double[] current = new double[2]; while (!pathIterator.isDone()) { switch (pathIterator.currentSegment(current)) { case PathIterator.SEG_CLOSE: surface[0] -= previous[0] * first[1] - previous[1] * first[0]; break; case PathIterator.SEG_LINETO: surface[0] -= previous[0] * current[1] - previous[1] * current[0]; System.arraycopy(current, 0, previous, 0, 2); break; case PathIterator.SEG_MOVETO: System.arraycopy(current, 0, first, 0, 2); System.arraycopy(current, 0, previous, 0, 2); break; case PathIterator.SEG_CUBICTO: case PathIterator.SEG_QUADTO: throw new IllegalStateException(); } pathIterator.next(); } surface[0] /= 2.0; final double s = surface[0]; return s; } public static final Area newRegion(final Element svgShape) { final Path2D path = new Path2D.Double(); path.setWindingRule(Path2D.WIND_EVEN_ODD); if ("polygon".equals(svgShape.getTagName())) { boolean first = true; try (final Scanner scanner = new Scanner(svgShape.getAttribute("points"))) { scanner.useLocale(Locale.ENGLISH); scanner.useDelimiter("[^0-9.-]"); while (scanner.hasNext()) { final double x = scanner.nextDouble(); final double y = scanner.nextDouble(); if (first) { first = false; path.moveTo(x, y); } else { path.lineTo(x, y); } } } path.closePath(); } else if ("path".equals(svgShape.getTagName())) { try (final Scanner scanner = new Scanner(svgShape.getAttribute("d"))) { scanner.useLocale(Locale.ENGLISH); double firstX = 0.0; double firstY = 0.0; double lastX = 0.0; double lastY = 0.0; String command = nextCommand(scanner, "M"); while (scanner.hasNext()) { final boolean relative = Character.isLowerCase(command.charAt(0)); if ("zZ".contains(command)) { path.closePath(); lastX = firstX; lastY = firstY; } else if ("mM".contains(command)) { final double x = nextDouble(scanner, relative, lastX); final double y = nextDouble(scanner, relative, lastY); path.moveTo(x, y); command = relative ? "l" : "L"; lastX = firstX = x; lastY = firstY = y; } else if ("lL".contains(command)) { final double x = nextDouble(scanner, relative, lastX); final double y = nextDouble(scanner, relative, lastY); path.lineTo(x, y); lastX = x; lastY = y; } else if ("qQ".contains(command)) { final double x1 = nextDouble(scanner, relative, lastX); final double y1 = nextDouble(scanner, relative, lastY); final double x = nextDouble(scanner, relative, x1); final double y = nextDouble(scanner, relative, y1); path.quadTo(x1, y1, x, y); lastX = x; lastY = y; } else if ("cC".contains(command)) { final double x1 = nextDouble(scanner, relative, lastX); final double y1 = nextDouble(scanner, relative, lastY); final double x2 = nextDouble(scanner, relative, x1); final double y2 = nextDouble(scanner, relative, y1); final double x = nextDouble(scanner, relative, x2); final double y = nextDouble(scanner, relative, y2); path.curveTo(x1, y1, x2, y2, x, y); lastX = x; lastY = y; } command = nextCommand(scanner, command); } } } return new Area(path); } public static final String nextCommand(final Scanner scanner, final String oldCommand) { scanner.useDelimiter(" *"); final String result = scanner.hasNext(COMMAND_PATTERN) ? scanner.next(COMMAND_PATTERN) : oldCommand; scanner.useDelimiter("[^" + NUMERICAL + "]+"); return result; } public static final double nextDouble(final Scanner scanner, final boolean relative, final double last) { return scanner.nextDouble() + (relative ? last : 0.0); } /** * @author codistmonk (creation 2015-06-05) */ public static final class Region implements Serializable { private final int label; private final Rectangle bounds; private final BufferedImage mask; public Region(final int label, final Rectangle bounds, final BufferedImage mask) { this.label = label; this.bounds = bounds; this.mask = mask; } public final int getLabel() { return this.label; } public final Rectangle getBounds() { return this.bounds; } public final BufferedImage getMask() { return this.mask; } public final long getSize() { final int width = this.getMask().getWidth(); final int height = this.getMask().getHeight(); long result = 0L; for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { if ((this.getMask().getRGB(x, y) & 1) != 0) { ++result; } } } return result; } private static final long serialVersionUID = 3168354082192346491L; } }
[imj3][draft][SVGTools] Refactoring.
src/imj3/draft/SVGTools.java
[imj3][draft][SVGTools] Refactoring.
Java
mit
151a01c96313fcb27575da5c56499b29289f5a33
0
InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service
package org.innovateuk.ifs.project.transactional; import org.innovateuk.ifs.commons.error.Error; import org.innovateuk.ifs.commons.service.ServiceResult; import org.innovateuk.ifs.competition.domain.Competition; import org.innovateuk.ifs.competition.repository.CompetitionRepository; import org.innovateuk.ifs.finance.transactional.FinanceRowService; import org.innovateuk.ifs.project.bankdetails.domain.BankDetails; import org.innovateuk.ifs.project.constant.ProjectActivityStates; import org.innovateuk.ifs.project.domain.MonitoringOfficer; import org.innovateuk.ifs.project.domain.Project; import org.innovateuk.ifs.project.domain.ProjectUser; import org.innovateuk.ifs.project.finance.domain.SpendProfile; import org.innovateuk.ifs.project.finance.transactional.ProjectFinanceService; import org.innovateuk.ifs.project.gol.workflow.configuration.GOLWorkflowHandler; import org.innovateuk.ifs.project.resource.ApprovalType; import org.innovateuk.ifs.project.status.resource.CompetitionProjectsStatusResource; import org.innovateuk.ifs.project.status.resource.ProjectStatusResource; import org.innovateuk.ifs.project.users.ProjectUsersHelper; import org.innovateuk.ifs.project.workflow.projectdetails.configuration.ProjectDetailsWorkflowHandler; import org.innovateuk.ifs.user.domain.Organisation; import org.innovateuk.ifs.user.resource.UserRoleType; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import static org.innovateuk.ifs.commons.error.CommonErrors.notFoundError; import static org.innovateuk.ifs.commons.error.CommonFailureKeys.GENERAL_NOT_FOUND; import static org.innovateuk.ifs.project.constant.ProjectActivityStates.*; import static org.innovateuk.ifs.user.resource.UserRoleType.COMP_ADMIN; import static org.innovateuk.ifs.util.CollectionFunctions.simpleMap; import static org.innovateuk.ifs.util.EntityLookupCallbacks.find; @Service public class ProjectStatusServiceImpl extends AbstractProjectServiceImpl implements ProjectStatusService { @Autowired private CompetitionRepository competitionRepository; @Autowired private ProjectUsersHelper projectUsersHelper; @Autowired private ProjectFinanceService projectFinanceService; @Autowired private ProjectDetailsWorkflowHandler projectDetailsWorkflowHandler; @Autowired private GOLWorkflowHandler golWorkflowHandler; @Autowired private FinanceRowService financeRowService; @Override public ServiceResult<CompetitionProjectsStatusResource> getCompetitionStatus(Long competitionId) { Competition competition = competitionRepository.findOne(competitionId); List<Project> projects = projectRepository.findByApplicationCompetitionId(competitionId); List<ProjectStatusResource> projectStatusResources = simpleMap(projects, project -> getProjectStatusResourceByProject(project)); CompetitionProjectsStatusResource competitionProjectsStatusResource = new CompetitionProjectsStatusResource(competition.getId(), competition.getFormattedId(), competition.getName(), projectStatusResources); return ServiceResult.serviceSuccess(competitionProjectsStatusResource); } @Override public ServiceResult<ProjectStatusResource> getProjectStatusByProjectId(Long projectId) { Project project = projectRepository.findOne(projectId); if(null != project) { return ServiceResult.serviceSuccess(getProjectStatusResourceByProject(project)); } return ServiceResult.serviceFailure(new Error(GENERAL_NOT_FOUND, HttpStatus.NOT_FOUND)); } private ProjectStatusResource getProjectStatusResourceByProject(Project project) { ProjectActivityStates projectDetailsStatus = getProjectDetailsStatus(project); ProjectActivityStates financeChecksStatus = getFinanceChecksStatus(project); return new ProjectStatusResource( project.getName(), project.getId(), project.getFormattedId(), project.getApplication().getId(), project.getApplication().getFormattedId(), getProjectPartnerCount(project.getId()), null != project.getApplication().getLeadOrganisation() ? project.getApplication().getLeadOrganisation().getName() : "", projectDetailsStatus, getBankDetailsStatus(project), financeChecksStatus, getSpendProfileStatus(project, financeChecksStatus), getMonitoringOfficerStatus(project, createProjectDetailsStatus(project)), getOtherDocumentsStatus(project), getGrantOfferLetterStatus(project), getRoleSpecificGrantOfferLetterState(project), golWorkflowHandler.isSent(project)); } private Integer getProjectPartnerCount(Long projectId){ return projectUsersHelper.getPartnerOrganisations(projectId).size(); } private ProjectActivityStates getProjectDetailsStatus(Project project){ for(Organisation organisation : project.getOrganisations()){ Optional<ProjectUser> financeContact = projectUsersHelper.getFinanceContact(project.getId(), organisation.getId()); if(financeContact == null || !financeContact.isPresent()){ return PENDING; } } return createProjectDetailsCompetitionStatus(project); } private ProjectActivityStates createProjectDetailsCompetitionStatus(Project project) { return projectDetailsWorkflowHandler.isSubmitted(project) ? COMPLETE : PENDING; } private boolean isOrganisationSeekingFunding(Long projectId, Long applicationId, Long organisationId){ Optional<Boolean> result = financeRowService.organisationSeeksFunding(projectId, applicationId, organisationId).getOptionalSuccessObject(); return result.map(Boolean::booleanValue).orElse(false); } private ProjectActivityStates getBankDetailsStatus(Project project){ // Show flag when there is any organisation awaiting approval. boolean incomplete = false; for(Organisation organisation : project.getOrganisations()){ if(isOrganisationSeekingFunding(project.getId(), project.getApplication().getId(), organisation.getId())) { Optional<BankDetails> bankDetails = Optional.ofNullable(bankDetailsRepository.findByProjectIdAndOrganisationId(project.getId(), organisation.getId())); ProjectActivityStates financeContactStatus = createFinanceContactStatus(project, organisation); ProjectActivityStates organisationBankDetailsStatus = createBankDetailStatus(project.getId(), project.getApplication().getId(), organisation.getId(), bankDetails, financeContactStatus); if (!bankDetails.isPresent() || organisationBankDetailsStatus.equals(ACTION_REQUIRED)) { incomplete = true; } if(bankDetails.isPresent() && organisationBankDetailsStatus.equals(PENDING)){ return ACTION_REQUIRED; } } } if(incomplete) { return PENDING; } else { return COMPLETE; } } private ProjectActivityStates getFinanceChecksStatus(Project project){ List<SpendProfile> spendProfile = spendProfileRepository.findByProjectId(project.getId()); if (spendProfile.isEmpty()) { return ACTION_REQUIRED; } return COMPLETE; } private ProjectActivityStates getSpendProfileStatus(Project project, ProjectActivityStates financeCheckStatus) { ApprovalType approvalType = projectFinanceService.getSpendProfileStatusByProjectId(project.getId()).getSuccessObject(); switch (approvalType) { case APPROVED: return COMPLETE; case REJECTED: return REJECTED; default: if (project.getSpendProfileSubmittedDate() != null) { return ACTION_REQUIRED; } if (financeCheckStatus.equals(COMPLETE)) { return PENDING; } return NOT_STARTED; } } private ProjectActivityStates getMonitoringOfficerStatus(Project project, ProjectActivityStates projectDetailsStatus){ return createMonitoringOfficerCompetitionStatus(getExistingMonitoringOfficerForProject(project.getId()).getOptionalSuccessObject(), projectDetailsStatus); } private ServiceResult<MonitoringOfficer> getExistingMonitoringOfficerForProject(Long projectId) { return find(monitoringOfficerRepository.findOneByProjectId(projectId), notFoundError(MonitoringOfficer.class, projectId)); } private ProjectActivityStates createMonitoringOfficerCompetitionStatus(final Optional<MonitoringOfficer> monitoringOfficer, final ProjectActivityStates leadProjectDetailsSubmitted) { if (leadProjectDetailsSubmitted.equals(COMPLETE)) { return monitoringOfficer.isPresent() ? COMPLETE : ACTION_REQUIRED; } else { return NOT_STARTED; } } private ProjectActivityStates getOtherDocumentsStatus(Project project){ if (project.getOtherDocumentsApproved() != null && !project.getOtherDocumentsApproved() && project.getDocumentsSubmittedDate() != null) { return REJECTED; } if (project.getOtherDocumentsApproved() != null && project.getOtherDocumentsApproved()) { return COMPLETE; } if (project.getOtherDocumentsApproved() != null && !project.getOtherDocumentsApproved()) { return PENDING; } if (project.getOtherDocumentsApproved() == null && project.getDocumentsSubmittedDate() != null) { return ACTION_REQUIRED; } return PENDING; } private ProjectActivityStates getGrantOfferLetterStatus(Project project){ ApprovalType spendProfileApprovalType = projectFinanceService.getSpendProfileStatusByProjectId(project.getId()).getSuccessObject(); if (project.getOfferSubmittedDate() == null && ApprovalType.APPROVED.equals(spendProfileApprovalType)){ return PENDING; } if (project.getOfferSubmittedDate() != null) { if (golWorkflowHandler.isApproved(project)) { return COMPLETE; } } if(project.getOfferSubmittedDate() != null) { return ACTION_REQUIRED; } return NOT_STARTED; } private Map<UserRoleType, ProjectActivityStates> getRoleSpecificGrantOfferLetterState(Project project) { Map<UserRoleType, ProjectActivityStates> roleSpecificGolStates = new HashMap<UserRoleType, ProjectActivityStates>(); ProjectActivityStates financeChecksStatus = getFinanceChecksStatus(project); ProjectActivityStates spendProfileStatus = getSpendProfileStatus(project, financeChecksStatus); if(project.getOtherDocumentsApproved() != null && project.getOtherDocumentsApproved() && COMPLETE.equals(spendProfileStatus)) { if(golWorkflowHandler.isApproved(project)) { roleSpecificGolStates.put(COMP_ADMIN, COMPLETE); } else { if(golWorkflowHandler.isReadyToApprove(project)) { roleSpecificGolStates.put(COMP_ADMIN, ACTION_REQUIRED); } else { if(golWorkflowHandler.isSent(project)) { roleSpecificGolStates.put(COMP_ADMIN, PENDING); } else { roleSpecificGolStates.put(COMP_ADMIN, ACTION_REQUIRED); } } } } else { roleSpecificGolStates.put(COMP_ADMIN, NOT_REQUIRED); } return roleSpecificGolStates; } }
ifs-data-service/src/main/java/org/innovateuk/ifs/project/transactional/ProjectStatusServiceImpl.java
package org.innovateuk.ifs.project.transactional; import org.innovateuk.ifs.commons.error.Error; import org.innovateuk.ifs.commons.service.ServiceResult; import org.innovateuk.ifs.competition.domain.Competition; import org.innovateuk.ifs.competition.repository.CompetitionRepository; import org.innovateuk.ifs.finance.transactional.FinanceRowService; import org.innovateuk.ifs.project.bankdetails.domain.BankDetails; import org.innovateuk.ifs.project.constant.ProjectActivityStates; import org.innovateuk.ifs.project.domain.MonitoringOfficer; import org.innovateuk.ifs.project.domain.Project; import org.innovateuk.ifs.project.domain.ProjectUser; import org.innovateuk.ifs.project.finance.domain.SpendProfile; import org.innovateuk.ifs.project.finance.transactional.ProjectFinanceService; import org.innovateuk.ifs.project.gol.workflow.configuration.GOLWorkflowHandler; import org.innovateuk.ifs.project.resource.ApprovalType; import org.innovateuk.ifs.project.status.resource.CompetitionProjectsStatusResource; import org.innovateuk.ifs.project.status.resource.ProjectStatusResource; import org.innovateuk.ifs.project.users.ProjectUsersHelper; import org.innovateuk.ifs.project.workflow.projectdetails.configuration.ProjectDetailsWorkflowHandler; import org.innovateuk.ifs.user.domain.Organisation; import org.innovateuk.ifs.user.resource.UserRoleType; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import static org.innovateuk.ifs.commons.error.CommonErrors.notFoundError; import static org.innovateuk.ifs.commons.error.CommonFailureKeys.GENERAL_NOT_FOUND; import static org.innovateuk.ifs.project.constant.ProjectActivityStates.*; import static org.innovateuk.ifs.user.resource.UserRoleType.COMP_ADMIN; import static org.innovateuk.ifs.util.CollectionFunctions.simpleMap; import static org.innovateuk.ifs.util.EntityLookupCallbacks.find; @Service public class ProjectStatusServiceImpl extends AbstractProjectServiceImpl implements ProjectStatusService { @Autowired private CompetitionRepository competitionRepository; @Autowired private ProjectUsersHelper projectUsersHelper; @Autowired private ProjectFinanceService projectFinanceService; @Autowired private ProjectDetailsWorkflowHandler projectDetailsWorkflowHandler; @Autowired private GOLWorkflowHandler golWorkflowHandler; @Autowired private FinanceRowService financeRowService; @Override public ServiceResult<CompetitionProjectsStatusResource> getCompetitionStatus(Long competitionId) { Competition competition = competitionRepository.findOne(competitionId); List<Project> projects = projectRepository.findByApplicationCompetitionId(competitionId); List<ProjectStatusResource> projectStatusResources = simpleMap(projects, project -> getProjectStatusResourceByProject(project)); CompetitionProjectsStatusResource competitionProjectsStatusResource = new CompetitionProjectsStatusResource(competition.getId(), competition.getFormattedId(), competition.getName(), projectStatusResources); return ServiceResult.serviceSuccess(competitionProjectsStatusResource); } @Override public ServiceResult<ProjectStatusResource> getProjectStatusByProjectId(Long projectId) { Project project = projectRepository.findOne(projectId); if(null != project) { return ServiceResult.serviceSuccess(getProjectStatusResourceByProject(project)); } return ServiceResult.serviceFailure(new Error(GENERAL_NOT_FOUND, HttpStatus.NOT_FOUND)); } private ProjectStatusResource getProjectStatusResourceByProject(Project project) { ProjectActivityStates projectDetailsStatus = getProjectDetailsStatus(project); ProjectActivityStates financeChecksStatus = getFinanceChecksStatus(project); return new ProjectStatusResource( project.getName(), project.getId(), project.getFormattedId(), project.getApplication().getId(), project.getApplication().getFormattedId(), getProjectPartnerCount(project.getId()), null != project.getApplication().getLeadOrganisation() ? project.getApplication().getLeadOrganisation().getName() : "", projectDetailsStatus, getBankDetailsStatus(project), financeChecksStatus, getSpendProfileStatus(project, financeChecksStatus), getMonitoringOfficerStatus(project, createProjectDetailsStatus(project)), getOtherDocumentsStatus(project), getGrantOfferLetterStatus(project), getRoleSpecificGrantOfferLetterState(project), golWorkflowHandler.isSent(project)); } private Integer getProjectPartnerCount(Long projectId){ return projectUsersHelper.getPartnerOrganisations(projectId).size(); } private ProjectActivityStates getProjectDetailsStatus(Project project){ for(Organisation organisation : project.getOrganisations()){ Optional<ProjectUser> financeContact = projectUsersHelper.getFinanceContact(project.getId(), organisation.getId()); if(financeContact == null || !financeContact.isPresent()){ return PENDING; } } return createProjectDetailsCompetitionStatus(project); } private ProjectActivityStates createProjectDetailsCompetitionStatus(Project project) { return projectDetailsWorkflowHandler.isSubmitted(project) ? COMPLETE : PENDING; } private boolean isOrganisationSeekingFunding(Long projectId, Long applicationId, Long organisationId){ Optional<Boolean> result = financeRowService.organisationSeeksFunding(projectId, applicationId, organisationId).getOptionalSuccessObject(); return result.map(Boolean::booleanValue).orElse(false); } private ProjectActivityStates getBankDetailsStatus(Project project){ // Show hourglass when there is at least one org which hasn't submitted bank details but is required to and none awaiting approval. boolean incomplete = false; for(Organisation organisation : project.getOrganisations()){ if(isOrganisationSeekingFunding(project.getId(), project.getApplication().getId(), organisation.getId())) { Optional<BankDetails> bankDetails = Optional.ofNullable(bankDetailsRepository.findByProjectIdAndOrganisationId(project.getId(), organisation.getId())); ProjectActivityStates financeContactStatus = createFinanceContactStatus(project, organisation); ProjectActivityStates organisationBankDetailsStatus = createBankDetailStatus(project.getId(), project.getApplication().getId(), organisation.getId(), bankDetails, financeContactStatus); if (!bankDetails.isPresent() || organisationBankDetailsStatus.equals(ACTION_REQUIRED)) { incomplete = true; } if(bankDetails.isPresent() && organisationBankDetailsStatus.equals(PENDING)){ return ACTION_REQUIRED; } } } // otherwise show a tick if(incomplete) { return PENDING; } else { return COMPLETE; } } private ProjectActivityStates getFinanceChecksStatus(Project project){ List<SpendProfile> spendProfile = spendProfileRepository.findByProjectId(project.getId()); if (spendProfile.isEmpty()) { return ACTION_REQUIRED; } return COMPLETE; } private ProjectActivityStates getSpendProfileStatus(Project project, ProjectActivityStates financeCheckStatus) { ApprovalType approvalType = projectFinanceService.getSpendProfileStatusByProjectId(project.getId()).getSuccessObject(); switch (approvalType) { case APPROVED: return COMPLETE; case REJECTED: return REJECTED; default: if (project.getSpendProfileSubmittedDate() != null) { return ACTION_REQUIRED; } if (financeCheckStatus.equals(COMPLETE)) { return PENDING; } return NOT_STARTED; } } private ProjectActivityStates getMonitoringOfficerStatus(Project project, ProjectActivityStates projectDetailsStatus){ return createMonitoringOfficerCompetitionStatus(getExistingMonitoringOfficerForProject(project.getId()).getOptionalSuccessObject(), projectDetailsStatus); } private ServiceResult<MonitoringOfficer> getExistingMonitoringOfficerForProject(Long projectId) { return find(monitoringOfficerRepository.findOneByProjectId(projectId), notFoundError(MonitoringOfficer.class, projectId)); } private ProjectActivityStates createMonitoringOfficerCompetitionStatus(final Optional<MonitoringOfficer> monitoringOfficer, final ProjectActivityStates leadProjectDetailsSubmitted) { if (leadProjectDetailsSubmitted.equals(COMPLETE)) { return monitoringOfficer.isPresent() ? COMPLETE : ACTION_REQUIRED; } else { return NOT_STARTED; } } private ProjectActivityStates getOtherDocumentsStatus(Project project){ if (project.getOtherDocumentsApproved() != null && !project.getOtherDocumentsApproved() && project.getDocumentsSubmittedDate() != null) { return REJECTED; } if (project.getOtherDocumentsApproved() != null && project.getOtherDocumentsApproved()) { return COMPLETE; } if (project.getOtherDocumentsApproved() != null && !project.getOtherDocumentsApproved()) { return PENDING; } if (project.getOtherDocumentsApproved() == null && project.getDocumentsSubmittedDate() != null) { return ACTION_REQUIRED; } return PENDING; } private ProjectActivityStates getGrantOfferLetterStatus(Project project){ ApprovalType spendProfileApprovalType = projectFinanceService.getSpendProfileStatusByProjectId(project.getId()).getSuccessObject(); if (project.getOfferSubmittedDate() == null && ApprovalType.APPROVED.equals(spendProfileApprovalType)){ return PENDING; } if (project.getOfferSubmittedDate() != null) { if (golWorkflowHandler.isApproved(project)) { return COMPLETE; } } if(project.getOfferSubmittedDate() != null) { return ACTION_REQUIRED; } return NOT_STARTED; } private Map<UserRoleType, ProjectActivityStates> getRoleSpecificGrantOfferLetterState(Project project) { Map<UserRoleType, ProjectActivityStates> roleSpecificGolStates = new HashMap<UserRoleType, ProjectActivityStates>(); ProjectActivityStates financeChecksStatus = getFinanceChecksStatus(project); ProjectActivityStates spendProfileStatus = getSpendProfileStatus(project, financeChecksStatus); if(project.getOtherDocumentsApproved() != null && project.getOtherDocumentsApproved() && COMPLETE.equals(spendProfileStatus)) { if(golWorkflowHandler.isApproved(project)) { roleSpecificGolStates.put(COMP_ADMIN, COMPLETE); } else { if(golWorkflowHandler.isReadyToApprove(project)) { roleSpecificGolStates.put(COMP_ADMIN, ACTION_REQUIRED); } else { if(golWorkflowHandler.isSent(project)) { roleSpecificGolStates.put(COMP_ADMIN, PENDING); } else { roleSpecificGolStates.put(COMP_ADMIN, ACTION_REQUIRED); } } } } else { roleSpecificGolStates.put(COMP_ADMIN, NOT_REQUIRED); } return roleSpecificGolStates; } }
Change comments Former-commit-id: ecc5b6b4a98e92f5db65a7928f06ea8432124d8d
ifs-data-service/src/main/java/org/innovateuk/ifs/project/transactional/ProjectStatusServiceImpl.java
Change comments
Java
mit
2f3c9451207d7652986263ef6c3ab923c7d9786b
0
Peter42/lunch_parser,Peter42/lunch_parser,Peter42/lunch_parser,Peter42/lunch_parser
package de.philipp1994.lunch.kit; import java.io.DataInputStream; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.time.temporal.IsoFields; import java.util.Map; import java.util.stream.Collectors; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import de.philipp1994.lunch.common.AbstractLunchMenuProvider; import de.philipp1994.lunch.common.LunchMenu; import de.philipp1994.lunch.common.LunchMenuItem; import de.philipp1994.lunch.common.LunchProviderException; import de.philipp1994.lunch.common.tools.Cache; public class KITLunchMenuProvider extends AbstractLunchMenuProvider { private static final Map<LocalDate, LunchMenu> cache = Cache.getSynchronizedCache(7); private static final String MENSA_NAME = "KIT Mensa"; private static URI getURI(LocalDate date) throws IOException { try { return new URI("http://www.sw-ka.de/de/essen/?view=ok&STYLE=popup_plain&c=adenauerring&p=1&kw=" + date.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR)); } catch (URISyntaxException e) { throw new IOException(e); } } private static URI getFallbackURI(LocalDate date) throws IOException { final String formattedDate = DateTimeFormatter.ofPattern("dd.MM.yyyy").format(date); try { return new URI("http://mensa.akk.uni-karlsruhe.de/?DATUM=" + formattedDate + "&uni=1&schnell=1"); } catch (URISyntaxException e) { throw new IOException(e); } } @Override public LunchMenu getMenu(final LocalDate date) throws IOException, LunchProviderException { if(cache.containsKey(date)){ return cache.get(date); } try { LunchMenu menu = new LunchMenu(MENSA_NAME); DataInputStream in = new DataInputStream(getURI(date).toURL().openStream()); Document document = Jsoup.parse(in, null, ""); LocalDate now = LocalDate.now(); int dayOfWeek = date.getDayOfWeek().getValue(); if(date.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR) == now.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR)) { // Lunch Menus of days in the past are hidden. dayOfWeek -= now.getDayOfWeek().getValue(); } final int child = 5 + 3 * dayOfWeek; Map<String, Element> lines = document.select("#platocontent > table:nth-child(" + child + ") > tbody > tr").stream() .filter(tr -> tr.text().length() > 0) .filter(tr -> tr.child(0).text().startsWith("L")) .collect(Collectors.toMap(tr -> tr.child(0).text(), tr -> tr.child(1).child(0).child(0))); lines.entrySet().stream().flatMap(e -> { return e.getValue().children().stream() .filter(tr -> { String text = null; try { text = tr.child(2).text().replaceAll("[^0-9,]", "").replace(",", ".").trim(); } catch(IndexOutOfBoundsException ex) { // if line is closed return false; } if(text.length() == 0) { return false; } return Double.parseDouble(text) > 1.5; }) .map(tr -> tr.child(1).text()) .map(name -> name.replaceAll("\\([^\\)]*\\)", "").trim()) .map(name -> new LunchMenuItem(name)); }).forEach(menu::addLunchItem); return menu; } catch(Exception e) { e.printStackTrace(); return getFallbackMenu(date); } } private LunchMenu getFallbackMenu(final LocalDate date) throws IOException, LunchProviderException { LunchMenu menu = new LunchMenu(MENSA_NAME); DataInputStream in = new DataInputStream(getFallbackURI(date).toURL().openStream()); Document document = Jsoup.parse(in, null, ""); Element table = document.getElementsByTag("tbody").get(0); Element e = table.child(0); String currentLine = ""; while( (e = e.nextElementSibling()) != null ) { String text = e.text(); if(text.startsWith("Linie")) { currentLine = text.substring(0, text.length() - 1); } else { menu.addLunchItem(new LunchMenuItem(e.child(0).text())); } } if(menu.getLunchItems().isEmpty()) { throw LunchProviderException.LUNCH_MENU_NOT_AVAILABLE_YET; } cache.put(date, menu); return menu; } }
kit-mensa/src/main/java/de/philipp1994/lunch/kit/KITLunchMenuProvider.java
package de.philipp1994.lunch.kit; import java.io.DataInputStream; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.time.LocalDate; import java.util.Map; import java.util.stream.Collectors; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import de.philipp1994.lunch.common.AbstractLunchMenuProvider; import de.philipp1994.lunch.common.LunchMenu; import de.philipp1994.lunch.common.LunchMenuItem; import de.philipp1994.lunch.common.LunchProviderException; import de.philipp1994.lunch.common.tools.Cache; public class KITLunchMenuProvider extends AbstractLunchMenuProvider { private static final URI FALLBACK_URL; private static final URI URL; private static final Map<LocalDate, LunchMenu> cache = Cache.getSynchronizedCache(7); private static final String MENSA_NAME = "KIT Mensa"; static { URI t = null; try { t = new URI("http://mensa.akk.uni-karlsruhe.de/?DATUM=heute&uni=1&schnell=1"); } catch (URISyntaxException e) { e.printStackTrace(); } finally { FALLBACK_URL = t; } t = null; try { t = new URI("http://www.sw-ka.de/de/essen/?view=ok&STYLE=popup_plain&c=adenauerring&p=1"); } catch (URISyntaxException e) { e.printStackTrace(); } finally { URL = t; } } @Override public LunchMenu getMenu(final LocalDate date) throws IOException, LunchProviderException { if(cache.containsKey(date)){ return cache.get(date); } try { LunchMenu menu = new LunchMenu(MENSA_NAME); DataInputStream in = new DataInputStream(URL.toURL().openStream()); Document document = Jsoup.parse(in, null, ""); Map<String, Element> lines = document.select("#platocontent > table:nth-child(5) > tbody > tr").stream() .filter(tr -> tr.text().length() > 0) .filter(tr -> tr.child(0).text().startsWith("L")) .collect(Collectors.toMap(tr -> tr.child(0).text(), tr -> tr.child(1).child(0).child(0))); lines.entrySet().stream().flatMap(e -> { return e.getValue().children().stream() .filter(tr -> { final String text = tr.child(2).text().replace("", "").replace(",", ".").trim(); if(text.length() == 0) { return false; } return Double.parseDouble(text) > 1.5; }) .map(tr -> tr.child(1).text()) .map(name -> name.replaceAll("\\([^\\)]*\\)", "").trim()) .map(name -> new LunchMenuItem(name)); }).forEach(menu::addLunchItem); return menu; } catch(Exception e) { e.printStackTrace(); return getFallbackMenu(date); } } private LunchMenu getFallbackMenu(final LocalDate date) throws IOException, LunchProviderException { LunchMenu menu = new LunchMenu(MENSA_NAME); DataInputStream in = new DataInputStream(FALLBACK_URL.toURL().openStream()); Document document = Jsoup.parse(in, null, ""); Element table = document.getElementsByTag("tbody").get(0); Element e = table.child(0); String currentLine = ""; while( (e = e.nextElementSibling()) != null ) { String text = e.text(); if(text.startsWith("Linie")) { currentLine = text.substring(0, text.length() - 1); } else { menu.addLunchItem(new LunchMenuItem(e.child(0).text())); } } if(menu.getLunchItems().isEmpty()) { throw LunchProviderException.LUNCH_MENU_NOT_AVAILABLE_YET; } cache.put(date, menu); return menu; } }
Fix KITLunchMenuProvider Date Bug. Closes #4
kit-mensa/src/main/java/de/philipp1994/lunch/kit/KITLunchMenuProvider.java
Fix KITLunchMenuProvider Date Bug. Closes #4
Java
mit
d932f361899e054df0aa1809a2e061455462cbc5
0
samirma/MeteoriteLandings,samirma/MeteoriteLandings
package com.antonio.samir.meteoritelandingsspots.service.repository.database; import com.antonio.samir.meteoritelandingsspots.model.Meteorite; import android.arch.persistence.room.Database; import android.arch.persistence.room.RoomDatabase; @Database(entities = {Meteorite.class}, version = 2) public abstract class AppDatabase extends RoomDatabase { public abstract MeteoriteDao meteoriteDao(); }
app/src/main/java/com/antonio/samir/meteoritelandingsspots/service/repository/database/AppDatabase.java
package com.antonio.samir.meteoritelandingsspots.service.repository.database; import android.arch.persistence.room.Database; import android.arch.persistence.room.RoomDatabase; import com.antonio.samir.meteoritelandingsspots.model.Meteorite; @Database(entities = {Meteorite.class, Address.class}, version = 1) public abstract class AppDatabase extends RoomDatabase { public abstract AddressDao addressDao(); public abstract MeteoriteDao meteoriteDao(); }
refactor: database version updated
app/src/main/java/com/antonio/samir/meteoritelandingsspots/service/repository/database/AppDatabase.java
refactor: database version updated
Java
mit
bed820ceaaa357e86fccabfe64836c5fa48ef9d8
0
KWStudios/RageMode,KWStudios/RageMode
package org.kwstudios.play.ragemode.gameLogic; import java.util.Arrays; import java.util.Random; import java.util.UUID; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.kwstudios.play.ragemode.scores.RageScores; import org.kwstudios.play.ragemode.toolbox.ConstantHolder; import org.kwstudios.play.ragemode.toolbox.GetGames; import org.kwstudios.play.ragemode.toolbox.TableList; public class PlayerList { private static FileConfiguration fileConfiguration; private static String[] list = new String[1]; // [Gamemane,Playername x overallMaxPlayers,Gamename,...] public static TableList<Player, Location> oldLocations = new TableList<Player, Location>(); public static TableList<Player, ItemStack[]> oldInventories = new TableList<Player, ItemStack[]>(); public static TableList<Player, ItemStack[]> oldArmor = new TableList<Player, ItemStack[]>(); public static TableList<Player, Double> oldHealth = new TableList<Player, Double>(); public static TableList<Player, Integer> oldHunger = new TableList<Player, Integer>(); public static TableList<Player, GameMode> oldGameMode = new TableList<Player, GameMode>(); private static String[] runningGames = new String[1]; public PlayerList(FileConfiguration fileConfiguration) { int i = 0; int imax = GetGames.getConfigGamesCount(fileConfiguration); String[] games = GetGames.getGameNames(fileConfiguration); PlayerList.fileConfiguration = fileConfiguration; list = Arrays .copyOf(list, GetGames.getConfigGamesCount(fileConfiguration) * (GetGames .getOverallMaxPlayers(fileConfiguration) + 1)); while(i < imax) { list[i*GetGames.getOverallMaxPlayers(fileConfiguration)] = games[i]; i++; } runningGames = Arrays.copyOf(runningGames, GetGames.getConfigGamesCount(fileConfiguration)); } public static String[] getPlayersInGame(String game) { int maxPlayers = GetGames.getMaxPlayers(game, fileConfiguration); if(maxPlayers == -1) return null; String[] players = new String[maxPlayers]; int i = 0; int n; int imax = GetGames.getConfigGamesCount(fileConfiguration) * (GetGames.getOverallMaxPlayers(fileConfiguration) + 1); int playersPerGame = GetGames.getOverallMaxPlayers(fileConfiguration); while (i < imax) { if(list[i] != null) { if (list[i].equals(game)) { n = i; int x = 0; while (n <= GetGames.getMaxPlayers(game, fileConfiguration) + i - 1) { if(list[n + 1] == null) n++; else { players[x] = list[n + 1]; n++; x++; } } players = Arrays.copyOf(players, x); } } i = i + (playersPerGame + 1); } return players; } public static boolean addPlayer(Player player, String game, FileConfiguration fileConfiguration) { if (isGameRunning(game)) { player.sendMessage(ConstantHolder.RAGEMODE_PREFIX + "This Game is already running."); return false; } int i, n; i = 0; n = 0; int kickposition; int imax = GetGames.getConfigGamesCount(fileConfiguration) * (GetGames.getOverallMaxPlayers(fileConfiguration) + 1); int playersPerGame = GetGames.getOverallMaxPlayers(fileConfiguration); while (i < imax) { if(list[i] != null) { if (player.getUniqueId().toString().equals(list[i])) { player.sendMessage(ConstantHolder.RAGEMODE_PREFIX + "You are already in a game. You can leave it by typing /rm leave"); return false; } } i++; } i = 0; while (i < imax) { if (list[i] != null) { if (list[i].equals(game)) { n = i; while (n <= GetGames.getMaxPlayers(game, fileConfiguration) + i) { if (list[n] == null) { list[n] = player.getUniqueId().toString(); player.sendMessage(ConstantHolder.RAGEMODE_PREFIX + "You joined " + ChatColor.DARK_AQUA + game + ChatColor.WHITE + "."); if (getPlayersInGame(game).length == 2) { new LobbyTimer(game, fileConfiguration); } return true; } n++; } } if (player.hasPermission("ragemode.vip") && hasRoomForVIP(game)) { Random random = new Random(); boolean isVIP = false; Player playerToKick; do { kickposition = random.nextInt(GetGames.getMaxPlayers(game, fileConfiguration) - 1); kickposition = kickposition + 1 + i; n = 0; playerToKick = Bukkit.getPlayer(UUID .fromString(list[kickposition])); isVIP = playerToKick.hasPermission("rm.vip"); } while (isVIP); while (n < oldLocations.getFirstLength()) { //Get him back to his old location. if (oldLocations.getFromFirstObject(n) == playerToKick) { playerToKick.teleport(oldLocations .getFromSecondObject(n)); oldLocations.removeFromBoth(n); } n++; } n = 0; while (n < oldInventories.getFirstLength()) { //Give him his inventory back. if (oldInventories.getFromFirstObject(n) == playerToKick) { playerToKick.getInventory().clear(); playerToKick.getInventory().setContents(oldInventories.getFromSecondObject(n)); oldInventories.removeFromBoth(n); } n++; } n = 0; while (n < oldArmor.getFirstLength()) { //Give him his armor back. if (oldArmor.getFromFirstObject(n) == playerToKick) { playerToKick.getInventory().setArmorContents(oldArmor.getFromSecondObject(n)); oldArmor.removeFromBoth(n); } n++; } n = 0; while (n < oldHealth.getFirstLength()) { //Give him his health back. if (oldHealth.getFromFirstObject(n) == playerToKick) { playerToKick.setHealth(oldHealth.getFromSecondObject(n)); oldHealth.removeFromBoth(n); } n++; } n = 0; while (n < oldHunger.getFirstLength()) { //Give him his hunger back. if (oldHunger.getFromFirstObject(n) == playerToKick) { playerToKick.setFoodLevel(oldHunger.getFromSecondObject(n)); oldHunger.removeFromBoth(n); } n++; } n = 0; while (n < oldGameMode.getFirstLength()) { //Give him his gamemode back. if (oldGameMode.getFromFirstObject(n) == playerToKick) { playerToKick.setGameMode(oldGameMode.getFromSecondObject(n)); oldGameMode.removeFromBoth(n); } n++; } list[kickposition] = player.getUniqueId().toString(); playerToKick .sendMessage(ConstantHolder.RAGEMODE_PREFIX + "You were kicked out of the Game to make room for a VIP."); if (getPlayersInGame(game).length == 2) { new LobbyTimer(game, fileConfiguration); } player.sendMessage(ConstantHolder.RAGEMODE_PREFIX + "You joined " + ChatColor.DARK_AQUA + game + ChatColor.WHITE + "."); return true; } else { player.sendMessage(ConstantHolder.RAGEMODE_PREFIX + "This Game is already full!"); return false; } } i = i + playersPerGame; } player.sendMessage(ConstantHolder.RAGEMODE_PREFIX + "The game you wish to join wasn't found."); return false; } public static boolean removePlayer(Player player) { int i = 0; int n = 0; int imax = GetGames.getConfigGamesCount(fileConfiguration) * (GetGames.getOverallMaxPlayers(fileConfiguration) + 1); while (i < imax) { if(list[i] != null) { if (list[i].equals(player.getUniqueId().toString())) { // TabGuiUpdater.removeTabForPlayer(player); // org.mcsg.double0negative.tabapi.TabAPI.disableTabForPlayer(player); // org.mcsg.double0negative.tabapi.TabAPI.updatePlayer(player); RageScores.removePointsForPlayers(new String[] {player.getUniqueId().toString()}); player.getInventory().clear(); player.sendMessage(ConstantHolder.RAGEMODE_PREFIX + "You left your current Game."); while (n < oldLocations.getFirstLength()) { //Bring him back to his old location if (oldLocations.getFromFirstObject(n) == player) { player.teleport(oldLocations.getFromSecondObject(n)); oldLocations.removeFromBoth(n); } n++; } n = 0; while (n < oldInventories.getFirstLength()) { //Give him his inventory back if (oldInventories.getFromFirstObject(n) == player) { player.getInventory().clear(); player.getInventory().setContents(oldInventories.getFromSecondObject(n)); oldInventories.removeFromBoth(n); } n++; } n = 0; while (n < oldArmor.getFirstLength()) { if (oldArmor.getFromFirstObject(n) == player) { //Give him his armor back player.getInventory().setArmorContents(oldArmor.getFromSecondObject(n)); oldArmor.removeFromBoth(n); } n++; } n = 0; while (n < oldHealth.getFirstLength()) { //Give him his health back. if (oldHealth.getFromFirstObject(n) == player) { player.setHealth(oldHealth.getFromSecondObject(n)); oldHealth.removeFromBoth(n); } n++; } n = 0; while (n < oldHunger.getFirstLength()) { //Give him his hunger back. if (oldHunger.getFromFirstObject(n) == player) { player.setFoodLevel(oldHunger.getFromSecondObject(n)); oldHunger.removeFromBoth(n); } n++; } n = 0; while (n < oldGameMode.getFirstLength()) { //Give him his gamemode back. if (oldGameMode.getFromFirstObject(n) == player) { player.setGameMode(oldGameMode.getFromSecondObject(n)); oldGameMode.removeFromBoth(n); } n++; } list[i] = null; return true; } } i++; } player.sendMessage(ConstantHolder.RAGEMODE_PREFIX + "The fact that you are not in a game caused a Problem while trying to remove you from that game."); return false; } public static boolean isGameRunning(String game) { int i = 0; int imax = runningGames.length; while (i < imax) { if (runningGames[i] != null) { if (runningGames[i].equals(game)) { return true; } } i++; } return false; } public static boolean setGameRunning(String game) { if (!GetGames.isGameExistent(game, fileConfiguration)) return false; int i = 0; int imax = runningGames.length; while (i < imax) { if(runningGames[i] != null) { if (runningGames[i].equals(game)) return false; } i++; } i = 0; while (i < imax) { if (runningGames[i] == null) { runningGames[i] = game; } i++; } return false; } public static boolean setGameNotRunning(String game) { if (!GetGames.isGameExistent(game, fileConfiguration)) return false; int i = 0; int imax = runningGames.length; while (i < imax) { if (runningGames[i] != null) { if (runningGames[i].equals(game)) { runningGames[i] = null; return true; } } i++; } return false; } public static boolean isPlayerPlaying(String player) { if(player != null) { int i = 0; int imax = list.length; while(i < imax) { if(list[i] != null) { if(list[i].equals(player)) { return true; } } i++; } } return false; } public static boolean hasRoomForVIP(String game) { String[] players = getPlayersInGame(game); int i = 0; int imax = players.length; int vipsInGame = 0; while(i < imax) { if(players[i] != null) { if(Bukkit.getPlayer(UUID.fromString(players[i])).hasPermission("rm.vip")) { vipsInGame++; } } i++; } if(vipsInGame == players.length) { return false; } return true; } public static void addGameToList(String game, int maxPlayers) { if(GetGames.getOverallMaxPlayers(fileConfiguration) < maxPlayers) { String[] oldList = list; list = Arrays.copyOf(list, (GetGames.getConfigGamesCount(fileConfiguration) + 1) * (maxPlayers + 1)); int i = 0; int imax = oldList.length; int n = 0; int nmax = (GetGames.getOverallMaxPlayers(fileConfiguration) + 1); while(i < imax) { while(n < nmax + i) { list[n + i] = oldList[n + i]; n++; } i = i + maxPlayers + 1; n = i; } list[i] = game; } else { String[] oldList = list; list = Arrays.copyOf(list, (GetGames.getConfigGamesCount(fileConfiguration) + 1) * (GetGames.getOverallMaxPlayers(fileConfiguration) + 1)); int i = 0; int imax = oldList.length; while(i < imax) { list[i] = oldList[i]; i++; } list[i] = game; } String[] oldRunningGames = runningGames; runningGames = Arrays.copyOf(runningGames, (runningGames.length + 1)); int i = 0; int imax = runningGames.length - 1; while(i < imax) { runningGames[i] = oldRunningGames[i]; i++; } } public static void deleteGameFromList(String game) { String[] playersInGame = getPlayersInGame(game); if(playersInGame != null) { int i = 0; int imax = playersInGame.length; while(i < imax) { if(playersInGame[i] != null) removePlayer(Bukkit.getPlayer(UUID.fromString(playersInGame[i]))); i++; } } int i = 0; int imax = list.length; int gamePos = imax; int nextGamePos = imax; while(i < imax) { if(list[i] != null) { if(list[i].equals(game)) { gamePos = i; int n = 0; int nmax = GetGames.getOverallMaxPlayers(fileConfiguration) + 1; while(n < nmax) { list[n + i] = null; n++; } nextGamePos = i + nmax; } } i++; } i = nextGamePos; while(i < imax) { list[gamePos] = list[i]; list[i] = null; i++; gamePos++; } String[] oldList = new String[(GetGames.getConfigGamesCount(fileConfiguration) - 1) * (GetGames.getOverallMaxPlayers(fileConfiguration) + 1)]; int g = 0; int gmax = oldList.length; while(g < gmax) { oldList[g] = list[g]; g++; } list = Arrays.copyOf(list, oldList.length); g = 0; while(g < gmax) { list[g] = oldList[g]; g++; } } public static String getPlayersGame(Player player) { String sPlayer = player.getUniqueId().toString(); String game = null; int i = 0; int imax = list.length; int playersPerGame = GetGames.getOverallMaxPlayers(fileConfiguration); while(i < imax) { if(list[i] != null) { if((i % (playersPerGame + 1)) == 0) { game = list[i]; } if(list[i].equals(sPlayer)) { return game; } } i++; } return null; } }
src/org/kwstudios/play/ragemode/gameLogic/PlayerList.java
package org.kwstudios.play.ragemode.gameLogic; import java.util.Arrays; import java.util.Random; import java.util.UUID; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.kwstudios.play.ragemode.scores.RageScores; import org.kwstudios.play.ragemode.toolbox.ConstantHolder; import org.kwstudios.play.ragemode.toolbox.GetGames; import org.kwstudios.play.ragemode.toolbox.TableList; public class PlayerList { private static FileConfiguration fileConfiguration; private static String[] list = new String[1]; // [Gamemane,Playername x overallMaxPlayers,Gamename,...] public static TableList<Player, Location> oldLocations = new TableList<Player, Location>(); public static TableList<Player, ItemStack[]> oldInventories = new TableList<Player, ItemStack[]>(); public static TableList<Player, ItemStack[]> oldArmor = new TableList<Player, ItemStack[]>(); public static TableList<Player, Double> oldHealth = new TableList<Player, Double>(); public static TableList<Player, Integer> oldHunger = new TableList<Player, Integer>(); public static TableList<Player, GameMode> oldGameMode = new TableList<Player, GameMode>(); private static String[] runningGames = new String[1]; public PlayerList(FileConfiguration fileConfiguration) { int i = 0; int imax = GetGames.getConfigGamesCount(fileConfiguration); String[] games = GetGames.getGameNames(fileConfiguration); PlayerList.fileConfiguration = fileConfiguration; list = Arrays .copyOf(list, GetGames.getConfigGamesCount(fileConfiguration) * (GetGames .getOverallMaxPlayers(fileConfiguration) + 1)); while(i < imax) { list[i*GetGames.getOverallMaxPlayers(fileConfiguration)] = games[i]; i++; } runningGames = Arrays.copyOf(runningGames, GetGames.getConfigGamesCount(fileConfiguration)); } public static String[] getPlayersInGame(String game) { int maxPlayers = GetGames.getMaxPlayers(game, fileConfiguration); if(maxPlayers == -1) return null; String[] players = new String[maxPlayers]; int i = 0; int n; int imax = GetGames.getConfigGamesCount(fileConfiguration) * (GetGames.getOverallMaxPlayers(fileConfiguration) + 1); int playersPerGame = GetGames.getOverallMaxPlayers(fileConfiguration); while (i <= imax) { if(list[i] != null) { if (list[i].equals(game)) { n = i; int x = 0; while (n <= GetGames.getMaxPlayers(game, fileConfiguration) + i - 1) { if(list[n + 1] == null) n++; else { players[x] = list[n + 1]; n++; x++; } } players = Arrays.copyOf(players, x); } } i = i + (playersPerGame + 1); } return players; } public static boolean addPlayer(Player player, String game, FileConfiguration fileConfiguration) { if (isGameRunning(game)) { player.sendMessage(ConstantHolder.RAGEMODE_PREFIX + "This Game is already running."); return false; } int i, n; i = 0; n = 0; int kickposition; int imax = GetGames.getConfigGamesCount(fileConfiguration) * (GetGames.getOverallMaxPlayers(fileConfiguration) + 1); int playersPerGame = GetGames.getOverallMaxPlayers(fileConfiguration); while (i < imax) { if(list[i] != null) { if (player.getUniqueId().toString().equals(list[i])) { player.sendMessage(ConstantHolder.RAGEMODE_PREFIX + "You are already in a game. You can leave it by typing /rm leave"); return false; } } i++; } i = 0; while (i < imax) { if (list[i] != null) { if (list[i].equals(game)) { n = i; while (n <= GetGames.getMaxPlayers(game, fileConfiguration) + i) { if (list[n] == null) { list[n] = player.getUniqueId().toString(); player.sendMessage(ConstantHolder.RAGEMODE_PREFIX + "You joined " + ChatColor.DARK_AQUA + game + ChatColor.WHITE + "."); if (getPlayersInGame(game).length == 2) { new LobbyTimer(game, fileConfiguration); } return true; } n++; } } if (player.hasPermission("ragemode.vip") && hasRoomForVIP(game)) { Random random = new Random(); boolean isVIP = false; Player playerToKick; do { kickposition = random.nextInt(GetGames.getMaxPlayers(game, fileConfiguration) - 1); kickposition = kickposition + 1 + i; n = 0; playerToKick = Bukkit.getPlayer(UUID .fromString(list[kickposition])); isVIP = playerToKick.hasPermission("rm.vip"); } while (isVIP); while (n < oldLocations.getFirstLength()) { //Get him back to his old location. if (oldLocations.getFromFirstObject(n) == playerToKick) { playerToKick.teleport(oldLocations .getFromSecondObject(n)); oldLocations.removeFromBoth(n); } n++; } n = 0; while (n < oldInventories.getFirstLength()) { //Give him his inventory back. if (oldInventories.getFromFirstObject(n) == playerToKick) { playerToKick.getInventory().clear(); playerToKick.getInventory().setContents(oldInventories.getFromSecondObject(n)); oldInventories.removeFromBoth(n); } n++; } n = 0; while (n < oldArmor.getFirstLength()) { //Give him his armor back. if (oldArmor.getFromFirstObject(n) == playerToKick) { playerToKick.getInventory().setArmorContents(oldArmor.getFromSecondObject(n)); oldArmor.removeFromBoth(n); } n++; } n = 0; while (n < oldHealth.getFirstLength()) { //Give him his health back. if (oldHealth.getFromFirstObject(n) == playerToKick) { playerToKick.setHealth(oldHealth.getFromSecondObject(n)); oldHealth.removeFromBoth(n); } n++; } n = 0; while (n < oldHunger.getFirstLength()) { //Give him his hunger back. if (oldHunger.getFromFirstObject(n) == playerToKick) { playerToKick.setFoodLevel(oldHunger.getFromSecondObject(n)); oldHunger.removeFromBoth(n); } n++; } n = 0; while (n < oldGameMode.getFirstLength()) { //Give him his gamemode back. if (oldGameMode.getFromFirstObject(n) == playerToKick) { playerToKick.setGameMode(oldGameMode.getFromSecondObject(n)); oldGameMode.removeFromBoth(n); } n++; } list[kickposition] = player.getUniqueId().toString(); playerToKick .sendMessage(ConstantHolder.RAGEMODE_PREFIX + "You were kicked out of the Game to make room for a VIP."); if (getPlayersInGame(game).length == 2) { new LobbyTimer(game, fileConfiguration); } player.sendMessage(ConstantHolder.RAGEMODE_PREFIX + "You joined " + ChatColor.DARK_AQUA + game + ChatColor.WHITE + "."); return true; } else { player.sendMessage(ConstantHolder.RAGEMODE_PREFIX + "This Game is already full!"); return false; } } i = i + playersPerGame; } player.sendMessage(ConstantHolder.RAGEMODE_PREFIX + "The game you wish to join wasn't found."); return false; } public static boolean removePlayer(Player player) { int i = 0; int n = 0; int imax = GetGames.getConfigGamesCount(fileConfiguration) * (GetGames.getOverallMaxPlayers(fileConfiguration) + 1); while (i < imax) { if(list[i] != null) { if (list[i].equals(player.getUniqueId().toString())) { // TabGuiUpdater.removeTabForPlayer(player); // org.mcsg.double0negative.tabapi.TabAPI.disableTabForPlayer(player); // org.mcsg.double0negative.tabapi.TabAPI.updatePlayer(player); RageScores.removePointsForPlayers(new String[] {player.getUniqueId().toString()}); player.getInventory().clear(); player.sendMessage(ConstantHolder.RAGEMODE_PREFIX + "You left your current Game."); while (n < oldLocations.getFirstLength()) { //Bring him back to his old location if (oldLocations.getFromFirstObject(n) == player) { player.teleport(oldLocations.getFromSecondObject(n)); oldLocations.removeFromBoth(n); } n++; } n = 0; while (n < oldInventories.getFirstLength()) { //Give him his inventory back if (oldInventories.getFromFirstObject(n) == player) { player.getInventory().clear(); player.getInventory().setContents(oldInventories.getFromSecondObject(n)); oldInventories.removeFromBoth(n); } n++; } n = 0; while (n < oldArmor.getFirstLength()) { if (oldArmor.getFromFirstObject(n) == player) { //Give him his armor back player.getInventory().setArmorContents(oldArmor.getFromSecondObject(n)); oldArmor.removeFromBoth(n); } n++; } n = 0; while (n < oldHealth.getFirstLength()) { //Give him his health back. if (oldHealth.getFromFirstObject(n) == player) { player.setHealth(oldHealth.getFromSecondObject(n)); oldHealth.removeFromBoth(n); } n++; } n = 0; while (n < oldHunger.getFirstLength()) { //Give him his hunger back. if (oldHunger.getFromFirstObject(n) == player) { player.setFoodLevel(oldHunger.getFromSecondObject(n)); oldHunger.removeFromBoth(n); } n++; } n = 0; while (n < oldGameMode.getFirstLength()) { //Give him his gamemode back. if (oldGameMode.getFromFirstObject(n) == player) { player.setGameMode(oldGameMode.getFromSecondObject(n)); oldGameMode.removeFromBoth(n); } n++; } list[i] = null; return true; } } i++; } player.sendMessage(ConstantHolder.RAGEMODE_PREFIX + "The fact that you are not in a game caused a Problem while trying to remove you from that game."); return false; } public static boolean isGameRunning(String game) { int i = 0; int imax = runningGames.length; while (i < imax) { if (runningGames[i] != null) { if (runningGames[i].equals(game)) { return true; } } i++; } return false; } public static boolean setGameRunning(String game) { if (!GetGames.isGameExistent(game, fileConfiguration)) return false; int i = 0; int imax = runningGames.length; while (i < imax) { if(runningGames[i] != null) { if (runningGames[i].equals(game)) return false; } i++; } i = 0; while (i < imax) { if (runningGames[i] == null) { runningGames[i] = game; } i++; } return false; } public static boolean setGameNotRunning(String game) { if (!GetGames.isGameExistent(game, fileConfiguration)) return false; int i = 0; int imax = runningGames.length; while (i < imax) { if (runningGames[i] != null) { if (runningGames[i].equals(game)) { runningGames[i] = null; return true; } } i++; } return false; } public static boolean isPlayerPlaying(String player) { if(player != null) { int i = 0; int imax = list.length; while(i < imax) { if(list[i] != null) { if(list[i].equals(player)) { return true; } } i++; } } return false; } public static boolean hasRoomForVIP(String game) { String[] players = getPlayersInGame(game); int i = 0; int imax = players.length; int vipsInGame = 0; while(i < imax) { if(players[i] != null) { if(Bukkit.getPlayer(UUID.fromString(players[i])).hasPermission("rm.vip")) { vipsInGame++; } } i++; } if(vipsInGame == players.length) { return false; } return true; } public static void addGameToList(String game, int maxPlayers) { if(GetGames.getOverallMaxPlayers(fileConfiguration) < maxPlayers) { String[] oldList = list; list = Arrays.copyOf(list, (GetGames.getConfigGamesCount(fileConfiguration) + 1) * (maxPlayers + 1)); int i = 0; int imax = oldList.length; int n = 0; int nmax = (GetGames.getOverallMaxPlayers(fileConfiguration) + 1); while(i < imax) { while(n < nmax + i) { list[n + i] = oldList[n + i]; n++; } i = i + maxPlayers + 1; n = i; } list[i] = game; } else { String[] oldList = list; list = Arrays.copyOf(list, (GetGames.getConfigGamesCount(fileConfiguration) + 1) * (GetGames.getOverallMaxPlayers(fileConfiguration) + 1)); int i = 0; int imax = oldList.length; while(i < imax) { list[i] = oldList[i]; i++; } list[i] = game; } String[] oldRunningGames = runningGames; runningGames = Arrays.copyOf(runningGames, (runningGames.length + 1)); int i = 0; int imax = runningGames.length - 1; while(i < imax) { runningGames[i] = oldRunningGames[i]; i++; } } public static void deleteGameFromList(String game) { String[] playersInGame = getPlayersInGame(game); if(playersInGame != null) { int i = 0; int imax = playersInGame.length; while(i < imax) { if(playersInGame[i] != null) removePlayer(Bukkit.getPlayer(UUID.fromString(playersInGame[i]))); i++; } } int i = 0; int imax = list.length; int gamePos = imax; int nextGamePos = imax; while(i < imax) { if(list[i] != null) { if(list[i].equals(game)) { gamePos = i; int n = 0; int nmax = GetGames.getOverallMaxPlayers(fileConfiguration) + 1; while(n < nmax) { list[n + i] = null; n++; } nextGamePos = i + nmax; } } i++; } i = nextGamePos; while(i < imax) { list[gamePos] = list[i]; list[i] = null; i++; gamePos++; } String[] oldList = new String[(GetGames.getConfigGamesCount(fileConfiguration) - 1) * (GetGames.getOverallMaxPlayers(fileConfiguration) + 1)]; int g = 0; int gmax = oldList.length; while(g < gmax) { oldList[g] = list[g]; g++; } list = Arrays.copyOf(list, oldList.length); g = 0; while(g < gmax) { list[g] = oldList[g]; g++; } } public static String getPlayersGame(Player player) { String sPlayer = player.getUniqueId().toString(); String game = null; int i = 0; int imax = list.length; int playersPerGame = GetGames.getOverallMaxPlayers(fileConfiguration); while(i < imax) { if(list[i] != null) { if((i % (playersPerGame + 1)) == 0) { game = list[i]; } if(list[i].equals(sPlayer)) { return game; } } i++; } return null; } }
fixed ArrayIndexOutOfBoundsException
src/org/kwstudios/play/ragemode/gameLogic/PlayerList.java
fixed ArrayIndexOutOfBoundsException
Java
mit
c431800c26ca969392965c0f3fe26486363c1b7e
0
CS2103JAN2017-W14-B4/main,CS2103JAN2017-W14-B4/main
package seedu.ezdo.commons.util; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import java.io.File; import java.io.IOException; import java.util.Optional; import java.util.logging.Level; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import seedu.ezdo.commons.core.Config; import seedu.ezdo.commons.exceptions.DataConversionException; public class ConfigUtilTest { private static final String TEST_DATA_FOLDER = FileUtil.getPath("./src/test/data/ConfigUtilTest/"); @Rule public ExpectedException thrown = ExpectedException.none(); @Rule public TemporaryFolder testFolder = new TemporaryFolder(); @Test public void read_null_assertionFailure() throws DataConversionException { thrown.expect(AssertionError.class); read(null); } @Test public void read_missingFile_emptyResult() throws DataConversionException { assertFalse(read("NonExistentFile.json").isPresent()); } @Test public void read_notJsonFormat_exceptionThrown() throws DataConversionException { thrown.expect(DataConversionException.class); read("NotJsonFormatConfig.json"); /* IMPORTANT: Any code below an exception-throwing line (like the one above) will be ignored. * That means you should not have more than one exception test in one method */ } @Test public void read_fileInOrder_successfullyRead() throws DataConversionException { Config expected = getTypicalConfig(); Config actual = read("TypicalConfig.json").get(); assertEquals(expected, actual); } @Test public void read_valuesMissingFromFile_defaultValuesUsed() throws DataConversionException { Config actual = read("EmptyConfig.json").get(); assertEquals(new Config(), actual); } @Test public void read_extraValuesInFile_extraValuesIgnored() throws DataConversionException { Config expected = getTypicalConfig(); Config actual = read("ExtraValuesConfig.json").get(); assertEquals(expected, actual); } private Config getTypicalConfig() { Config config = new Config(); config.setAppTitle("Typical App Title"); config.setLogLevel(Level.INFO); config.setUserPrefsFilePath("C:\\preferences.json"); config.setEzDoFilePath("data/ezDo.xml"); config.setEzDoName("ezDo"); return config; } private Optional<Config> read(String configFileInTestDataFolder) throws DataConversionException { String configFilePath = addToTestDataPathIfNotNull(configFileInTestDataFolder); return ConfigUtil.readConfig(configFilePath); } @Test public void save_nullConfig_assertionFailure() throws IOException { thrown.expect(AssertionError.class); save(null, "SomeFile.json"); } @Test public void save_nullFile_assertionFailure() throws IOException { thrown.expect(AssertionError.class); save(new Config(), null); } @Test public void saveConfig_allInOrder_success() throws DataConversionException, IOException { Config original = getTypicalConfig(); String configFilePath = testFolder.getRoot() + File.separator + "TempConfig.json"; //Try writing when the file doesn't exist ConfigUtil.saveConfig(original, configFilePath); Config readBack = ConfigUtil.readConfig(configFilePath).get(); assertEquals(original, readBack); //Try saving when the file exists original.setAppTitle("Updated Title"); original.setLogLevel(Level.FINE); ConfigUtil.saveConfig(original, configFilePath); readBack = ConfigUtil.readConfig(configFilePath).get(); assertEquals(original, readBack); } private void save(Config config, String configFileInTestDataFolder) throws IOException { String configFilePath = addToTestDataPathIfNotNull(configFileInTestDataFolder); ConfigUtil.saveConfig(config, configFilePath); } private String addToTestDataPathIfNotNull(String configFileInTestDataFolder) { return configFileInTestDataFolder != null ? TEST_DATA_FOLDER + configFileInTestDataFolder : null; } }
src/test/java/seedu/ezdo/commons/util/ConfigUtilTest.java
package seedu.ezdo.commons.util; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import java.io.File; import java.io.IOException; import java.util.Optional; import java.util.logging.Level; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import seedu.ezdo.commons.core.Config; import seedu.ezdo.commons.exceptions.DataConversionException; public class ConfigUtilTest { private static final String TEST_DATA_FOLDER = FileUtil.getPath("./src/test/data/ConfigUtilTest/"); @Rule public ExpectedException thrown = ExpectedException.none(); @Rule public TemporaryFolder testFolder = new TemporaryFolder(); @Test public void read_null_assertionFailure() throws DataConversionException { thrown.expect(AssertionError.class); read(null); } @Test public void read_missingFile_emptyResult() throws DataConversionException { assertFalse(read("NonExistentFile.json").isPresent()); } @Test public void read_notJsonFormat_exceptionThrown() throws DataConversionException { thrown.expect(DataConversionException.class); read("NotJsonFormatConfig.json"); /* IMPORTANT: Any code below an exception-throwing line (like the one above) will be ignored. * That means you should not have more than one exception test in one method */ } @Test public void read_fileInOrder_successfullyRead() throws DataConversionException { Config expected = getTypicalConfig(); Config actual = read("TypicalConfig.json").get(); assertEquals(expected, actual); } @Test public void read_valuesMissingFromFile_defaultValuesUsed() throws DataConversionException { Config actual = read("EmptyConfig.json").get(); assertEquals(new Config(), actual); } @Test public void read_extraValuesInFile_extraValuesIgnored() throws DataConversionException { Config expected = getTypicalConfig(); Config actual = read("ExtraValuesConfig.json").get(); assertEquals(expected, actual); } private Config getTypicalConfig() { Config config = new Config(); config.setAppTitle("Typical App Title"); config.setLogLevel(Level.INFO); config.setUserPrefsFilePath("C:\\preferences.json"); config.setEzDoFilePath("data/ezDo.xml"); config.setEzDoName("ezDo"); return config; } private Optional<Config> read(String configFileInTestDataFolder) throws DataConversionException { String configFilePath = addToTestDataPathIfNotNull(configFileInTestDataFolder); return ConfigUtil.readConfig(configFilePath); } @Test public void save_nullConfig_assertionFailure() throws IOException { thrown.expect(AssertionError.class); save(null, "SomeFile.json"); } @Test public void save_nullFile_assertionFailure() throws IOException { thrown.expect(AssertionError.class); save(new Config(), null); } @Test public void saveConfig_allInOrder_success() throws DataConversionException, IOException { Config original = getTypicalConfig(); String configFilePath = testFolder.getRoot() + File.separator + "TempConfig.json"; //Try writing when the file doesn't exist ConfigUtil.saveConfig(original, configFilePath); Config readBack = ConfigUtil.readConfig(configFilePath).get(); assertEquals(original, readBack); //Try saving when the file exists original.setAppTitle("Updated Title"); original.setLogLevel(Level.FINE); ConfigUtil.saveConfig(original, configFilePath); readBack = ConfigUtil.readConfig(configFilePath).get(); assertEquals(original, readBack); } private void save(Config config, String configFileInTestDataFolder) throws IOException { String configFilePath = addToTestDataPathIfNotNull(configFileInTestDataFolder); ConfigUtil.saveConfig(config, configFilePath); } private String addToTestDataPathIfNotNull(String configFileInTestDataFolder) { return configFileInTestDataFolder != null ? TEST_DATA_FOLDER + configFileInTestDataFolder : null; } }
Remove whitespace
src/test/java/seedu/ezdo/commons/util/ConfigUtilTest.java
Remove whitespace
Java
mit
f35768fe970c3cbfd474f95244817d1dd62c9fa7
0
curiosone-bot/curiosone-core
package com.github.bot.curiosone.core.workflow; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.anyOf; import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; import org.junit.Test; public class LogicTest { @Test public void testAnswer() throws IOException { Message msg = Logic.talk(new Message("", "", "")); assertThat(msg.getMessage()).isEqualTo("Sorry my head hurts, what were we talking about?"); assertThat(msg.getScope()).isEmpty(); msg = Logic.talk(null); assertThat(msg.getMessage()).isEqualTo("Sorry my head hurts, what were we talking about?"); assertThat(msg.getScope()).isEmpty(); msg = Logic.talk(new Message("Sorry my head hurts, what were we talking about?", "", "")); assertThat(msg.getMessage()) .containsIgnoringCase("Sorry my head hurts, what were we talking about?"); msg = Logic.talk(new Message("How old are you?", "", "")); assertThat(msg.getMessage()) .isNotEmpty() .isNotEqualTo("Sorry my head hurts, what were we talking about?"); assertThat(msg.getScope()).isEmpty(); msg = Logic.talk(new Message("What is apple?", "", "")); assertThat(msg.getMessage()).containsIgnoringCase("apple"); assertThat(msg.getScope()).containsIgnoringCase("apple"); msg = Logic.talk(new Message("What is a red apple?", "", "")); assertThat(msg.getMessage()).containsIgnoringCase("apple"); assertThat(msg.getScope()).containsIgnoringCase("apple"); msg = Logic.talk(new Message("Is a fruit", "apple?", "")); assertThat(msg.getMessage()).containsIgnoringCase("fruit"); assertThat(msg.getScope()).containsIgnoringCase("fruit"); msg = Logic.talk(new Message("It is a fruit", "apple", "")); assertThat(msg.getMessage()).containsIgnoringCase("fruit"); assertThat(msg.getScope()).containsIgnoringCase("fruit"); msg = Logic.talk(new Message("The apple is a fruit", "apple", "")); assertThat(msg.getMessage()).containsIgnoringCase("fruit"); assertThat(msg.getScope()).containsIgnoringCase("fruit"); msg = Logic.talk(new Message("Who is Roberto Navigli?", "", "")); assertThat(msg.getMessage()).isNotNull().isNotEmpty(); assertThat(msg.getScope()).isNotNull(); msg = Logic.talk(new Message("Who is Roberto?", "", "")); assertThat(msg.getMessage()).containsIgnoringCase("roberto"); assertThat(msg.getScope()).containsIgnoringCase("roberto"); msg = Logic.talk(new Message("Who is Navigli?", "", "")); assertThat(msg.getMessage()).containsIgnoringCase("Navigli"); assertThat(msg.getScope()).containsIgnoringCase("Navigli"); msg = Logic.talk(new Message("Where is Europe?", "", "")); assertThat(msg.getMessage()).containsIgnoringCase("europe"); assertThat(msg.getScope()).containsIgnoringCase("europe"); msg = Logic.talk(new Message("Where is Rome?", "", "")); assertThat(msg.getMessage()).containsIgnoringCase("Rome"); assertThat(msg.getScope()).containsIgnoringCase("Rome"); msg = Logic.talk(new Message("Where are United States of America?", "", "")); assertThat(msg.getMessage()).isNotNull().isNotEmpty(); assertThat(msg.getScope()).isNotNull(); msg = Logic.talk(new Message("Hi", "", "")); assertThat(msg.getMessage()).isIn("Hi there!", "Hi.", "Hello!"); assertThat(msg.getScope()).isEmpty(); msg = Logic.talk(new Message("Hello", "", "")); assertThat(msg.getMessage()).isIn("Hi there!", "Hi.", "Hello!"); assertThat(msg.getScope()).isEmpty(); msg = Logic.talk(new Message("Are we friends?", "", "")); assertThat(msg.getMessage()) .isIn("Facebook teached me what a friend is", "I really want a friend."); assertThat(msg.getScope()).isEmpty(); msg = Logic.talk(new Message("Are you busy?", "", "")); assertThat(msg.getMessage()) .isIn("I am not busy.", "I can not be busy, I am always ready to answer your questions."); assertThat(msg.getScope()).isEmpty(); msg = Logic.talk(new Message("Are you a human?", "", "")); assertThat(msg.getMessage()) .isIn("No I am not human.", "Humans have blood, I have 101010101011011."); assertThat(msg.getScope()).isEmpty(); msg = Logic.talk(new Message("hsxzk vhdskjv,mcjzklk", "", "")); assertThat(msg.getMessage()) .isIn("I think you should speak english", "PLEASE, speak english!", "Are you a robot too?"); assertThat(msg.getScope()).isEmpty(); msg = Logic.talk(new Message("Nel mezzo del cammin di nostra vita...", "", "")); assertThat(msg.getMessage()) .isIn("I think you should speak english", "PLEASE, speak english!", "Are you a robot too?"); assertThat(msg.getScope()).isEmpty(); msg = Logic.talk(new Message("ImFoolingYou!", "", "")); assertThat(msg.getMessage()).isNotNull().isNotEmpty(); assertThat(msg.getScope()).isNotNull(); msg = Logic.talk(new Message("Robots are weirdo", "", "")); assertThat(msg.getMessage()) .isIn( "I do not like your way of talking.", "You should speak more politely.", "Why are you talking like this? Are you a little kid?","Come back when you grow up." ); assertThat(msg.getScope()).isEmpty(); msg = Logic.talk(new Message("What is dog?", "", "")); assertThat(msg.getMessage()).containsIgnoringCase("dog"); assertThat(msg.getScope()).containsIgnoringCase("dog"); msg = Logic.talk(new Message("What is a dog?", "", "")); assertThat(msg.getMessage()).containsIgnoringCase("dog"); assertThat(msg.getScope()).containsIgnoringCase("dog"); } }
src/test/java/com/github/bot/curiosone/core/workflow/LogicTest.java
package com.github.bot.curiosone.core.workflow; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.anyOf; import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; import org.junit.Test; public class LogicTest { @Test public void testAnswer() throws IOException { Message msg = Logic.talk(new Message("", "", "")); assertThat(msg.getMessage()).isEqualTo("Sorry my head hurts, what were we talking about?"); assertThat(msg.getScope()).isEmpty(); msg = Logic.talk(null); assertThat(msg.getMessage()).isEqualTo("Sorry my head hurts, what were we talking about?"); assertThat(msg.getScope()).isEmpty(); msg = Logic.talk(new Message("Sorry my head hurts, what were we talking about? " + "Sorry my head hurts, what were we talking about?", "", "")); assertThat(msg.getMessage()) .containsIgnoringCase("Sorry my head hurts, what were we talking about?"); msg = Logic.talk(new Message("How old are you?", "", "")); assertThat(msg.getMessage()) .isNotEmpty() .isNotEqualTo("Sorry my head hurts, what were we talking about?"); assertThat(msg.getScope()).isEmpty(); msg = Logic.talk(new Message("What is apple?", "", "")); assertThat(msg.getMessage()).containsIgnoringCase("apple"); assertThat(msg.getScope()).containsIgnoringCase("apple"); msg = Logic.talk(new Message("What is a red apple?", "", "")); assertThat(msg.getMessage()).containsIgnoringCase("apple"); assertThat(msg.getScope()).containsIgnoringCase("apple"); msg = Logic.talk(new Message("Is a fruit", "apple?", "")); assertThat(msg.getMessage()).containsIgnoringCase("fruit"); assertThat(msg.getScope()).containsIgnoringCase("fruit"); msg = Logic.talk(new Message("It is a fruit", "apple", "")); assertThat(msg.getMessage()).containsIgnoringCase("fruit"); assertThat(msg.getScope()).containsIgnoringCase("fruit"); msg = Logic.talk(new Message("The apple is a fruit", "apple", "")); assertThat(msg.getMessage()).containsIgnoringCase("fruit"); assertThat(msg.getScope()).containsIgnoringCase("fruit"); msg = Logic.talk(new Message("Who is Roberto Navigli?", "", "")); assertThat(msg.getMessage()).isNotNull().isNotEmpty(); assertThat(msg.getScope()).isNotNull(); msg = Logic.talk(new Message("Who is Roberto?", "", "")); assertThat(msg.getMessage()).containsIgnoringCase("roberto"); assertThat(msg.getScope()).containsIgnoringCase("roberto"); msg = Logic.talk(new Message("Who is Navigli?", "", "")); assertThat(msg.getMessage()).containsIgnoringCase("Navigli"); assertThat(msg.getScope()).containsIgnoringCase("Navigli"); msg = Logic.talk(new Message("Where is Europe?", "", "")); assertThat(msg.getMessage()).containsIgnoringCase("europe"); assertThat(msg.getScope()).containsIgnoringCase("europe"); msg = Logic.talk(new Message("Where is Rome?", "", "")); assertThat(msg.getMessage()).containsIgnoringCase("Rome"); assertThat(msg.getScope()).containsIgnoringCase("Rome"); msg = Logic.talk(new Message("Where are United States of America?", "", "")); assertThat(msg.getMessage()).isNotNull().isNotEmpty(); assertThat(msg.getScope()).isNotNull(); msg = Logic.talk(new Message("Hi", "", "")); assertThat(msg.getMessage()).isIn("Hi there!", "Hi.", "Hello!"); assertThat(msg.getScope()).isEmpty(); msg = Logic.talk(new Message("Hello", "", "")); assertThat(msg.getMessage()).isIn("Hi there!", "Hi.", "Hello!"); assertThat(msg.getScope()).isEmpty(); msg = Logic.talk(new Message("Are we friends?", "", "")); assertThat(msg.getMessage()) .isIn("Facebook teached me what a friend is", "I really want a friend."); assertThat(msg.getScope()).isEmpty(); msg = Logic.talk(new Message("Are you busy?", "", "")); assertThat(msg.getMessage()) .isIn("I am not busy.", "I can not be busy, I am always ready to answer your questions."); assertThat(msg.getScope()).isEmpty(); msg = Logic.talk(new Message("Are you a human?", "", "")); assertThat(msg.getMessage()) .isIn("No I am not human.", "Humans have blood, I have 101010101011011."); assertThat(msg.getScope()).isEmpty(); msg = Logic.talk(new Message("hsxzk vhdskjv,mcjzklk", "", "")); assertThat(msg.getMessage()) .isIn("I think you should speak english", "PLEASE, speak english!", "Are you a robot too?"); assertThat(msg.getScope()).isEmpty(); msg = Logic.talk(new Message("Nel mezzo del cammin di nostra vita...", "", "")); assertThat(msg.getMessage()) .isIn("I think you should speak english", "PLEASE, speak english!", "Are you a robot too?"); assertThat(msg.getScope()).isEmpty(); msg = Logic.talk(new Message("ImFoolingYou!", "", "")); assertThat(msg.getMessage()).isNotNull().isNotEmpty(); assertThat(msg.getScope()).isNotNull(); msg = Logic.talk(new Message("Robots are weirdo", "", "")); assertThat(msg.getMessage()) .isIn( "I do not like your way of talking.", "You should speak more politely.", "Why are you talking like this? Are you a little kid?","Come back when you grow up." ); assertThat(msg.getScope()).isEmpty(); msg = Logic.talk(new Message("What is dog?", "", "")); assertThat(msg.getMessage()).containsIgnoringCase("dog"); assertThat(msg.getScope()).containsIgnoringCase("dog"); msg = Logic.talk(new Message("What is a dog?", "", "")); assertThat(msg.getMessage()).containsIgnoringCase("dog"); assertThat(msg.getScope()).containsIgnoringCase("dog"); } }
Update LogicTest.java
src/test/java/com/github/bot/curiosone/core/workflow/LogicTest.java
Update LogicTest.java
Java
mit
88714e4b55cb3f6fa7315c1b8f18015fa50a5b9a
0
tonussi/teia
package dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.logging.Level; import java.util.logging.Logger; public class DBConnectionImpl implements DBConnection { Logger logger = Logger.getLogger(DBConnectionImpl.class.getName()); private final String database, user, pass; private Connection connection; private Statement statement; private ResultSet resultSet; public DBConnectionImpl(String database, String user, String pass) { this.database = database; this.user = user; this.pass = pass; verifica(); } @Override public void verifica() { try { connection = connect(); statement = connection.createStatement(); resultSet = statement.executeQuery("SELECT VERSION()"); if (resultSet.next()) System.out.println(resultSet.getString(1)); } catch (SQLException event) { logger.log(Level.SEVERE, event.getMessage(), event); } finally { close(); } } @Override public Connection connect() { Connection connection = null; try { Class.forName("org.postgresql.Driver"); String url = "jdbc:postgresql://localhost/" + database; connection = DriverManager.getConnection(url, user, pass); } catch (ClassNotFoundException event) { logger.log(Level.SEVERE, event.getMessage(), event); System.exit(1); } catch (SQLException event) { logger.log(Level.SEVERE, event.getMessage(), event); System.exit(2); } return connection; } @Override public void close() { try { if (resultSet != null) resultSet.close(); if (statement != null) statement.close(); if (connection != null) connection.close(); } catch (SQLException event) { logger.log(Level.WARNING, event.getMessage(), event); } } }
src/dao/DBConnectionImpl.java
package dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; public class DBConnectionImpl implements DBConnection { Logger logger = Logger.getLogger(DBConnectionImpl.class.getName()); private String database, user, pass; public DBConnectionImpl(String database, String user, String pass) { this.database = database; this.user = user; this.pass = pass; } @Override public Connection connect() { Connection conn = null; try { Class.forName("org.postgresql.Driver"); String url = "jdbc:postgresql://localhost/" + database; conn = DriverManager.getConnection(url, user, pass); } catch (ClassNotFoundException event) { logger.log(Level.SEVERE, event.getMessage(), event); System.exit(1); } catch (SQLException event) { logger.log(Level.SEVERE, event.getMessage(), event); System.exit(2); } return conn; } @Override public Connection close() { return null; } }
Refatora impl dbconnection
src/dao/DBConnectionImpl.java
Refatora impl dbconnection
Java
mit
178d84584bba92c603c6d8b6539ae417f5663beb
0
jed204/ustack-core-data
package com.untzuntz.coredata; import com.Ostermiller.util.MD5; import com.mongodb.BasicDBObject; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import com.untzuntz.coredata.anno.DBTableMap; import com.untzuntz.coredata.exceptions.FailedRequestException; import com.untzuntz.coredata.exceptions.FieldSetException; import com.untzuntz.coredata.exceptions.UnknownPrimaryKeyException; import com.untzuntz.ustack.data.MongoDB; import com.untzuntz.ustack.data.UDataCache; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.lang.UnhandledException; import org.apache.log4j.Logger; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; public class MongoQueryRunner { static Logger logger = Logger.getLogger(MongoQueryRunner.class); public static <T> List<T> runListQuery(Class<T> clazz, SearchFilters filters, OrderBy orderBy, PagingSupport paging) throws FailedRequestException, UnknownPrimaryKeyException, UnhandledException { return runListQuery(clazz, filters, orderBy, paging, null); } public static <T> List<T> runListQuery(Class<T> clazz, SearchFilters filters, OrderBy orderBy, PagingSupport paging, DBObject additionalSearch) throws FailedRequestException, UnknownPrimaryKeyException, UnhandledException { return runListQuery(clazz, filters, orderBy, paging, additionalSearch, null, null, null); } public static <T> int count(Class<T> clazz, SearchFilters filters, DBObject additionalSearch, Integer maxTimeSeconds) throws FailedRequestException { DBTableMap tbl = clazz.getAnnotation(DBTableMap.class); if (tbl == null) throw new FailedRequestException("Cannot persist or grab class from data source : " + clazz.getName()); // search parameters DBObject searchObj = null; if (filters != null) searchObj = filters.getMongoSearchObject(); else searchObj = new BasicDBObject(); if (additionalSearch != null) searchObj.putAll(additionalSearch); String db = DataMgr.getDb(tbl); String colName = tbl.dbTable(); DBCollection col = MongoDB.getCollection(db, colName); DBCursor cur = col.find(searchObj); if (maxTimeSeconds != null) { cur.maxTime(maxTimeSeconds, TimeUnit.SECONDS); } int count = cur.count(); logger.info(String.format("[%s.%s] => %s | Count: %d", db, colName, searchObj, count)); return count; } public static class CachePlan { private Integer resultCacheTime; private Integer countCacheTime; private String key; private boolean countFromCache; private boolean resultsFromCache; private DBObject summary = new BasicDBObject(); private String queryUid; public CachePlan(String key, Integer resultCacheTime, Integer countCacheTime) { this.key = key; this.resultCacheTime = resultCacheTime; this.countCacheTime = countCacheTime; } public boolean hasCountCache() { return key != null && countCacheTime != null; } public boolean hasResultCache() { return key != null && resultCacheTime != null; } public void setSearch(DBObject search) { summary.put("search", search); } public void setSort(DBObject sort) { summary.put("sort", sort); } public void setPaging(PagingSupport paging) { summary.put("page", paging.getPage()); summary.put("limit", paging.getItemsPerPage()); } private void calculateQueryUid() { queryUid = String.format("mcq_%s_%s", key, DigestUtils.md5Hex(summary.toString())); } public void setCacheCount(Long value) { if (value == null || !hasCountCache()) { logger.info("Skipping Cache Count"); return; } logger.info(String.format("Setting Cache [%s] => %d", queryUid, value)); if (UOpts.getCacheEnabled()) { UDataCache.getInstance().set(queryUid, countCacheTime, value); } } public Long getCacheCount() { if (!hasCountCache()) { return null; } calculateQueryUid(); if (UOpts.getCacheEnabled()) { return (Long)UDataCache.getInstance().get(queryUid); } return null; } public String getQueryUid() { return queryUid; } public boolean isCountFromCache() { return countFromCache; } public void setCountFromCache(boolean countFromCache) { this.countFromCache = countFromCache; } public boolean isResultsFromCache() { return resultsFromCache; } public void setResultsFromCache(boolean resultsFromCache) { this.resultsFromCache = resultsFromCache; } } public static <T> List<T> runListQuery(Class<T> clazz, SearchFilters filters, OrderBy orderBy, PagingSupport paging, DBObject additionalSearch, ExportFormat exportFormat, Integer maxTimeSeconds, CachePlan cache) throws FailedRequestException, UnknownPrimaryKeyException, UnhandledException { DBTableMap tbl = clazz.getAnnotation(DBTableMap.class); if (tbl == null) throw new FailedRequestException("Cannot persist or grab class from data source : " + clazz.getName()); DBCollection col = MongoDB.getCollection(DataMgr.getDb(tbl), tbl.dbTable()); return runListQuery(col, clazz, filters, orderBy, paging, additionalSearch, exportFormat, maxTimeSeconds, cache); } /** * Executes a query against the MongoDB database for the request class and collection * * @throws FailedRequestException * @throws UnknownPrimaryKeyException * @throws UnhandledException * @throws SecurityException */ public static <T> List<T> runListQuery(DBCollection col, Class<T> clazz, SearchFilters filters, OrderBy orderBy, PagingSupport paging, DBObject additionalSearch, ExportFormat exportFormat, Integer maxTimeSeconds, CachePlan cache) throws FailedRequestException, UnknownPrimaryKeyException, UnhandledException { List<T> ret = new ArrayList<T>(); // search parameters DBObject searchObj = null; if (filters != null) searchObj = filters.getMongoSearchObject(); else searchObj = new BasicDBObject(); if (additionalSearch != null) { searchObj.putAll(additionalSearch); } // paging and limits int skip = 0; int limit = -1; if (paging != null) { skip = (paging.getPage() - 1) * paging.getItemsPerPage(); limit = paging.getItemsPerPage(); } // sorting parameters DBObject orderByObj = null; if (orderBy != null) { orderByObj = new BasicDBObject(); orderByObj.put(orderBy.getFieldName(), orderBy.getDirection().getOrderInt()); } long start = System.currentTimeMillis(); // run the actual query DBCursor cur = col.find(searchObj); if (maxTimeSeconds != null) { cur.maxTime(maxTimeSeconds, TimeUnit.SECONDS); } cur.sort(orderByObj); cur.skip(skip); if (limit != -1) cur.limit(limit); // setup result paging long pagingStart = System.currentTimeMillis(); boolean nocount = false; if (paging != null && !paging.isNoCount()) { Long total = null; if (cache != null) { cache.setSort(orderByObj); cache.setPaging(paging); cache.setSearch(searchObj); total = cache.getCacheCount(); } if (total == null) { total = new Long(cur.count()); if (cache != null) { cache.setCacheCount(total); } } paging.setTotal(total); } else { nocount = true; } long pagingEnd = System.currentTimeMillis(); long iterateStart = System.currentTimeMillis(); if (exportFormat != null) exportFormat.output(cur); else { while (cur.hasNext()) { ret.add(DataMgr.getObjectFromDBObject(clazz, cur.next())); } } long iterateEnd = System.currentTimeMillis(); long totalTime = (System.currentTimeMillis() - start); logger.info(String.format("%s | Search [%s] | Sort [%s] | Skip %d | Limit %d => PagingTime %d / IterationTime %d / TotalTime %d CountEnabled: (nocount: %s)%s", clazz.getSimpleName(), searchObj, orderByObj, skip, limit, (pagingEnd - pagingStart), (iterateEnd - iterateStart), totalTime, nocount, totalTime > 5000 ? " | SLOWQUERY" : "")); return ret; } /** * Searches for a single object based on the provided search filters * * @throws FailedRequestException * @throws UnknownPrimaryKeyException * @throws SecurityException */ public static <T> T runQuery(Class<T> clazz, SearchFilters filters) throws FailedRequestException, UnknownPrimaryKeyException { DBTableMap tbl = clazz.getAnnotation(DBTableMap.class); if (tbl == null) throw new FailedRequestException("Cannot persist or grab class from data source : " + clazz.getName()); // search parameters DBObject searchObj = null; if (filters != null) searchObj = filters.getMongoSearchObject(); else searchObj = new BasicDBObject(); // run the actual query DBCollection col = MongoDB.getCollection(DataMgr.getDb(tbl), tbl.dbTable()); DBObject ret = col.findOne(searchObj); return DataMgr.getObjectFromDBObject(clazz, ret); } }
src/main/java/com/untzuntz/coredata/MongoQueryRunner.java
package com.untzuntz.coredata; import com.Ostermiller.util.MD5; import com.mongodb.BasicDBObject; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import com.untzuntz.coredata.anno.DBTableMap; import com.untzuntz.coredata.exceptions.FailedRequestException; import com.untzuntz.coredata.exceptions.FieldSetException; import com.untzuntz.coredata.exceptions.UnknownPrimaryKeyException; import com.untzuntz.ustack.data.MongoDB; import com.untzuntz.ustack.data.UDataCache; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.lang.UnhandledException; import org.apache.log4j.Logger; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; public class MongoQueryRunner { static Logger logger = Logger.getLogger(MongoQueryRunner.class); public static <T> List<T> runListQuery(Class<T> clazz, SearchFilters filters, OrderBy orderBy, PagingSupport paging) throws FailedRequestException, UnknownPrimaryKeyException, UnhandledException { return runListQuery(clazz, filters, orderBy, paging, null); } public static <T> List<T> runListQuery(Class<T> clazz, SearchFilters filters, OrderBy orderBy, PagingSupport paging, DBObject additionalSearch) throws FailedRequestException, UnknownPrimaryKeyException, UnhandledException { return runListQuery(clazz, filters, orderBy, paging, additionalSearch, null, null, null); } public static <T> int count(Class<T> clazz, SearchFilters filters, DBObject additionalSearch, Integer maxTimeSeconds) throws FailedRequestException { DBTableMap tbl = clazz.getAnnotation(DBTableMap.class); if (tbl == null) throw new FailedRequestException("Cannot persist or grab class from data source : " + clazz.getName()); // search parameters DBObject searchObj = null; if (filters != null) searchObj = filters.getMongoSearchObject(); else searchObj = new BasicDBObject(); if (additionalSearch != null) searchObj.putAll(additionalSearch); String db = DataMgr.getDb(tbl); String colName = tbl.dbTable(); DBCollection col = MongoDB.getCollection(db, colName); DBCursor cur = col.find(searchObj); if (maxTimeSeconds != null) { cur.maxTime(maxTimeSeconds, TimeUnit.SECONDS); } int count = cur.count(); logger.info(String.format("[%s.%s] => %s | Count: %d", db, colName, searchObj, count)); return count; } public static class CachePlan { private Integer resultCacheTime; private Integer countCacheTime; private String key; private boolean countFromCache; private boolean resultsFromCache; private DBObject summary = new BasicDBObject(); private String queryUid; public CachePlan(String key, Integer resultCacheTime, Integer countCacheTime) { this.key = key; this.resultCacheTime = resultCacheTime; this.countCacheTime = countCacheTime; } public boolean hasCountCache() { return key != null && countCacheTime != null; } public boolean hasResultCache() { return key != null && resultCacheTime != null; } public void setSearch(DBObject search) { summary.put("search", search); } public void setSort(DBObject sort) { summary.put("sort", sort); } public void setPaging(PagingSupport paging) { summary.put("page", paging.getPage()); summary.put("limit", paging.getItemsPerPage()); } private void calculateQueryUid() { queryUid = String.format("mcq_%s_%s", key, DigestUtils.md5Hex(summary.toString())); } public void setCacheCount(Long value) { if (value == null || !hasCountCache()) { logger.info("Skipping Cache Count"); return; } logger.info(String.format("Setting Cache [%s] => %d", queryUid, value)); UDataCache.getInstance().set(queryUid, countCacheTime, value); } public Long getCacheCount() { if (!hasCountCache()) { return null; } calculateQueryUid(); return (Long)UDataCache.getInstance().get(queryUid); } public String getQueryUid() { return queryUid; } public boolean isCountFromCache() { return countFromCache; } public void setCountFromCache(boolean countFromCache) { this.countFromCache = countFromCache; } public boolean isResultsFromCache() { return resultsFromCache; } public void setResultsFromCache(boolean resultsFromCache) { this.resultsFromCache = resultsFromCache; } } public static <T> List<T> runListQuery(Class<T> clazz, SearchFilters filters, OrderBy orderBy, PagingSupport paging, DBObject additionalSearch, ExportFormat exportFormat, Integer maxTimeSeconds, CachePlan cache) throws FailedRequestException, UnknownPrimaryKeyException, UnhandledException { DBTableMap tbl = clazz.getAnnotation(DBTableMap.class); if (tbl == null) throw new FailedRequestException("Cannot persist or grab class from data source : " + clazz.getName()); DBCollection col = MongoDB.getCollection(DataMgr.getDb(tbl), tbl.dbTable()); return runListQuery(col, clazz, filters, orderBy, paging, additionalSearch, exportFormat, maxTimeSeconds, cache); } /** * Executes a query against the MongoDB database for the request class and collection * * @throws FailedRequestException * @throws UnknownPrimaryKeyException * @throws UnhandledException * @throws SecurityException */ public static <T> List<T> runListQuery(DBCollection col, Class<T> clazz, SearchFilters filters, OrderBy orderBy, PagingSupport paging, DBObject additionalSearch, ExportFormat exportFormat, Integer maxTimeSeconds, CachePlan cache) throws FailedRequestException, UnknownPrimaryKeyException, UnhandledException { List<T> ret = new ArrayList<T>(); // search parameters DBObject searchObj = null; if (filters != null) searchObj = filters.getMongoSearchObject(); else searchObj = new BasicDBObject(); if (additionalSearch != null) { searchObj.putAll(additionalSearch); } // paging and limits int skip = 0; int limit = -1; if (paging != null) { skip = (paging.getPage() - 1) * paging.getItemsPerPage(); limit = paging.getItemsPerPage(); } // sorting parameters DBObject orderByObj = null; if (orderBy != null) { orderByObj = new BasicDBObject(); orderByObj.put(orderBy.getFieldName(), orderBy.getDirection().getOrderInt()); } long start = System.currentTimeMillis(); // run the actual query DBCursor cur = col.find(searchObj); if (maxTimeSeconds != null) { cur.maxTime(maxTimeSeconds, TimeUnit.SECONDS); } cur.sort(orderByObj); cur.skip(skip); if (limit != -1) cur.limit(limit); // setup result paging long pagingStart = System.currentTimeMillis(); boolean nocount = false; if (paging != null && !paging.isNoCount()) { Long total = null; if (cache != null) { cache.setSort(orderByObj); cache.setPaging(paging); cache.setSearch(searchObj); total = cache.getCacheCount(); } if (total == null) { total = new Long(cur.count()); if (cache != null) { cache.setCacheCount(total); } } paging.setTotal(total); } else { nocount = true; } long pagingEnd = System.currentTimeMillis(); long iterateStart = System.currentTimeMillis(); if (exportFormat != null) exportFormat.output(cur); else { while (cur.hasNext()) { ret.add(DataMgr.getObjectFromDBObject(clazz, cur.next())); } } long iterateEnd = System.currentTimeMillis(); long totalTime = (System.currentTimeMillis() - start); logger.info(String.format("%s | Search [%s] | Sort [%s] | Skip %d | Limit %d => PagingTime %d / IterationTime %d / TotalTime %d CountEnabled: (nocount: %s)%s", clazz.getSimpleName(), searchObj, orderByObj, skip, limit, (pagingEnd - pagingStart), (iterateEnd - iterateStart), totalTime, nocount, totalTime > 5000 ? " | SLOWQUERY" : "")); return ret; } /** * Searches for a single object based on the provided search filters * * @throws FailedRequestException * @throws UnknownPrimaryKeyException * @throws SecurityException */ public static <T> T runQuery(Class<T> clazz, SearchFilters filters) throws FailedRequestException, UnknownPrimaryKeyException { DBTableMap tbl = clazz.getAnnotation(DBTableMap.class); if (tbl == null) throw new FailedRequestException("Cannot persist or grab class from data source : " + clazz.getName()); // search parameters DBObject searchObj = null; if (filters != null) searchObj = filters.getMongoSearchObject(); else searchObj = new BasicDBObject(); // run the actual query DBCollection col = MongoDB.getCollection(DataMgr.getDb(tbl), tbl.dbTable()); DBObject ret = col.findOne(searchObj); return DataMgr.getObjectFromDBObject(clazz, ret); } }
Check for null memcached instance
src/main/java/com/untzuntz/coredata/MongoQueryRunner.java
Check for null memcached instance
Java
epl-1.0
300b5a16e2db7a765cbd1ac7b7699ec530301a5b
0
opendaylight/bgpcep
/* * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.protocol.bgp.parser.spi.pojo; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import java.util.concurrent.atomic.AtomicReference; import org.opendaylight.protocol.bgp.parser.spi.AttributeParser; import org.opendaylight.protocol.bgp.parser.spi.AttributeSerializer; import org.opendaylight.protocol.bgp.parser.spi.BGPExtensionProviderContext; import org.opendaylight.protocol.bgp.parser.spi.BgpPrefixSidTlvParser; import org.opendaylight.protocol.bgp.parser.spi.BgpPrefixSidTlvSerializer; import org.opendaylight.protocol.bgp.parser.spi.CapabilityParser; import org.opendaylight.protocol.bgp.parser.spi.CapabilitySerializer; import org.opendaylight.protocol.bgp.parser.spi.MessageParser; import org.opendaylight.protocol.bgp.parser.spi.MessageSerializer; import org.opendaylight.protocol.bgp.parser.spi.NextHopParserSerializer; import org.opendaylight.protocol.bgp.parser.spi.NlriParser; import org.opendaylight.protocol.bgp.parser.spi.NlriSerializer; import org.opendaylight.protocol.bgp.parser.spi.ParameterParser; import org.opendaylight.protocol.bgp.parser.spi.ParameterSerializer; import org.opendaylight.protocol.bgp.parser.spi.extended.community.ExtendedCommunityParser; import org.opendaylight.protocol.bgp.parser.spi.extended.community.ExtendedCommunitySerializer; import org.opendaylight.protocol.util.ReferenceCache; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.BgpParameters; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.path.attributes.attributes.bgp.prefix.sid.bgp.prefix.sid.tlvs.BgpPrefixSidTlv; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.AddressFamily; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.SubsequentAddressFamily; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.extended.community.ExtendedCommunity; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.next.hop.CNextHop; import org.opendaylight.yangtools.yang.binding.DataObject; import org.opendaylight.yangtools.yang.binding.Notification; public class SimpleBGPExtensionProviderContext extends SimpleBGPExtensionConsumerContext implements BGPExtensionProviderContext { public static final int DEFAULT_MAXIMUM_CACHED_OBJECTS = 100000; private final AtomicReference<Cache<Object, Object>> cacheRef; private final ReferenceCache referenceCache = new ReferenceCache() { @Override public <T> T getSharedReference(final T object) { final Cache<Object, Object> cache = SimpleBGPExtensionProviderContext.this.cacheRef.get(); @SuppressWarnings("unchecked") final T ret = (T) cache.getIfPresent(object); if (ret == null) { cache.put(object, object); return object; } return ret; } }; public SimpleBGPExtensionProviderContext() { this(DEFAULT_MAXIMUM_CACHED_OBJECTS); } public SimpleBGPExtensionProviderContext(final int maximumCachedObjects) { final Cache<Object, Object> cache = CacheBuilder.newBuilder().maximumSize(maximumCachedObjects).build(); this.cacheRef = new AtomicReference<>(cache); } @Override public AutoCloseable registerAddressFamily(final Class<? extends AddressFamily> clazz, final int number) { return this.getAddressFamilyRegistry().registerAddressFamily(clazz, number); } @Override public AutoCloseable registerAttributeParser(final int attributeType, final AttributeParser parser) { return this.getAttributeRegistry().registerAttributeParser(attributeType, parser); } @Override public AutoCloseable registerAttributeSerializer(final Class<? extends DataObject> attributeClass, final AttributeSerializer serializer) { return this.getAttributeRegistry().registerAttributeSerializer(attributeClass, serializer); } @Override public AutoCloseable registerCapabilityParser(final int capabilityType, final CapabilityParser parser) { return this.getCapabilityRegistry().registerCapabilityParser(capabilityType, parser); } @Override public AutoCloseable registerCapabilitySerializer(final Class<? extends DataObject> capabilityClass, final CapabilitySerializer serializer) { return this.getCapabilityRegistry().registerCapabilitySerializer(capabilityClass, serializer); } @Override public AutoCloseable registerMessageParser(final int messageType, final MessageParser parser) { return this.getMessageRegistry().registerMessageParser(messageType, parser); } @Override public AutoCloseable registerMessageSerializer(final Class<? extends Notification> messageClass, final MessageSerializer serializer) { return this.getMessageRegistry().registerMessageSerializer(messageClass, serializer); } /** * Each extension requires a specific NextHop handler. Therefore this method has been deprecated for * the method which enforce user to register it. */ @Deprecated @Override public AutoCloseable registerNlriParser(final Class<? extends AddressFamily> afi, final Class<? extends SubsequentAddressFamily> safi, final NlriParser parser) { return this.getNlriRegistry().registerNlriParser(afi, safi, parser, null, null); } @Override public AutoCloseable registerNlriParser(final Class<? extends AddressFamily> afi, final Class<? extends SubsequentAddressFamily> safi, final NlriParser parser, final NextHopParserSerializer nextHopParserSerializer, final Class<? extends CNextHop> cNextHopClass, final Class<? extends CNextHop>... cNextHopClassList) { return this.getNlriRegistry().registerNlriParser(afi, safi, parser, nextHopParserSerializer, cNextHopClass, cNextHopClassList); } @Override public AutoCloseable registerNlriSerializer(final Class<? extends DataObject> nlriClass, final NlriSerializer serializer) { return this.getNlriRegistry().registerNlriSerializer(nlriClass, serializer); } @Override public AutoCloseable registerParameterParser(final int parameterType, final ParameterParser parser) { return this.getParameterRegistry().registerParameterParser(parameterType, parser); } @Override public AutoCloseable registerParameterSerializer(final Class<? extends BgpParameters> paramClass, final ParameterSerializer serializer) { return this.getParameterRegistry().registerParameterSerializer(paramClass, serializer); } @Override public AutoCloseable registerSubsequentAddressFamily(final Class<? extends SubsequentAddressFamily> clazz, final int number) { return this.getSubsequentAddressFamilyRegistry().registerSubsequentAddressFamily(clazz, number); } @Override public ReferenceCache getReferenceCache() { return this.referenceCache; } @Override public AutoCloseable registerExtendedCommunitySerializer(final Class<? extends ExtendedCommunity> extendedCommunityClass, final ExtendedCommunitySerializer serializer) { return this.getExtendedCommunityRegistry().registerExtendedCommunitySerializer(extendedCommunityClass, serializer); } @Override public AutoCloseable registerExtendedCommunityParser(final int type, final int subtype, final ExtendedCommunityParser parser) { return this.getExtendedCommunityRegistry().registerExtendedCommunityParser(type, subtype, parser); } @Override public AutoCloseable registerBgpPrefixSidTlvParser(final int tlvType, final BgpPrefixSidTlvParser parser) { return this.getBgpPrefixSidTlvRegistry().registerBgpPrefixSidTlvParser(tlvType, parser); } @Override public AutoCloseable registerBgpPrefixSidTlvSerializer(final Class<? extends BgpPrefixSidTlv> tlvClass, final BgpPrefixSidTlvSerializer serializer) { return this.getBgpPrefixSidTlvRegistry().registerBgpPrefixSidTlvSerializer(tlvClass, serializer); } }
bgp/parser-spi/src/main/java/org/opendaylight/protocol/bgp/parser/spi/pojo/SimpleBGPExtensionProviderContext.java
/* * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.protocol.bgp.parser.spi.pojo; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import java.util.concurrent.atomic.AtomicReference; import org.opendaylight.protocol.bgp.parser.spi.AttributeParser; import org.opendaylight.protocol.bgp.parser.spi.AttributeSerializer; import org.opendaylight.protocol.bgp.parser.spi.BGPExtensionProviderContext; import org.opendaylight.protocol.bgp.parser.spi.BgpPrefixSidTlvParser; import org.opendaylight.protocol.bgp.parser.spi.BgpPrefixSidTlvSerializer; import org.opendaylight.protocol.bgp.parser.spi.CapabilityParser; import org.opendaylight.protocol.bgp.parser.spi.CapabilitySerializer; import org.opendaylight.protocol.bgp.parser.spi.MessageParser; import org.opendaylight.protocol.bgp.parser.spi.MessageSerializer; import org.opendaylight.protocol.bgp.parser.spi.NextHopParserSerializer; import org.opendaylight.protocol.bgp.parser.spi.NlriParser; import org.opendaylight.protocol.bgp.parser.spi.NlriSerializer; import org.opendaylight.protocol.bgp.parser.spi.ParameterParser; import org.opendaylight.protocol.bgp.parser.spi.ParameterSerializer; import org.opendaylight.protocol.bgp.parser.spi.extended.community.ExtendedCommunityParser; import org.opendaylight.protocol.bgp.parser.spi.extended.community.ExtendedCommunitySerializer; import org.opendaylight.protocol.util.ReferenceCache; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.BgpParameters; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.path.attributes.attributes.bgp.prefix.sid.bgp.prefix.sid.tlvs.BgpPrefixSidTlv; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.AddressFamily; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.SubsequentAddressFamily; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.extended.community.ExtendedCommunity; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.next.hop.CNextHop; import org.opendaylight.yangtools.yang.binding.DataObject; import org.opendaylight.yangtools.yang.binding.Notification; public class SimpleBGPExtensionProviderContext extends SimpleBGPExtensionConsumerContext implements BGPExtensionProviderContext { public static final int DEFAULT_MAXIMUM_CACHED_OBJECTS = 100000; private final AtomicReference<Cache<Object, Object>> cacheRef; private final ReferenceCache referenceCache = new ReferenceCache() { @Override public <T> T getSharedReference(final T object) { final Cache<Object, Object> cache = SimpleBGPExtensionProviderContext.this.cacheRef.get(); @SuppressWarnings("unchecked") final T ret = (T) cache.getIfPresent(object); if (ret == null) { cache.put(object, object); return object; } return ret; } }; public SimpleBGPExtensionProviderContext() { this(DEFAULT_MAXIMUM_CACHED_OBJECTS); } public SimpleBGPExtensionProviderContext(final int maximumCachedObjects) { final Cache<Object, Object> cache = CacheBuilder.newBuilder().maximumSize(maximumCachedObjects).build(); this.cacheRef = new AtomicReference<>(cache); } @Override public AutoCloseable registerAddressFamily(final Class<? extends AddressFamily> clazz, final int number) { return this.getAddressFamilyRegistry().registerAddressFamily(clazz, number); } @Override public AutoCloseable registerAttributeParser(final int attributeType, final AttributeParser parser) { return this.getAttributeRegistry().registerAttributeParser(attributeType, parser); } @Override public AutoCloseable registerAttributeSerializer(final Class<? extends DataObject> attributeClass, final AttributeSerializer serializer) { return this.getAttributeRegistry().registerAttributeSerializer(attributeClass, serializer); } @Override public AutoCloseable registerCapabilityParser(final int capabilityType, final CapabilityParser parser) { return this.getCapabilityRegistry().registerCapabilityParser(capabilityType, parser); } @Override public AutoCloseable registerCapabilitySerializer(final Class<? extends DataObject> capabilityClass, final CapabilitySerializer serializer) { return this.getCapabilityRegistry().registerCapabilitySerializer(capabilityClass, serializer); } @Override public AutoCloseable registerMessageParser(final int messageType, final MessageParser parser) { return this.getMessageRegistry().registerMessageParser(messageType, parser); } @Override public AutoCloseable registerMessageSerializer(final Class<? extends Notification> messageClass, final MessageSerializer serializer) { return this.getMessageRegistry().registerMessageSerializer(messageClass, serializer); } /** * Each extension requires a specific NextHop handler. Therefore this method has been deprecated for * the method which enforce user to register it. */ @Deprecated @Override public AutoCloseable registerNlriParser(final Class<? extends AddressFamily> afi, final Class<? extends SubsequentAddressFamily> safi, final NlriParser parser) { return this.getNlriRegistry().registerNlriParser(afi, safi, parser, null, null); } @Override public AutoCloseable registerNlriParser(final Class<? extends AddressFamily> afi, final Class<? extends SubsequentAddressFamily> safi, final NlriParser parser, final NextHopParserSerializer nextHopParserSerializer, final Class<? extends CNextHop> cNextHopClass, final Class<? extends CNextHop>... cNextHopClassList) { return this.getNlriRegistry().registerNlriParser(afi, safi, parser, nextHopParserSerializer, cNextHopClass); } @Override public AutoCloseable registerNlriSerializer(final Class<? extends DataObject> nlriClass, final NlriSerializer serializer) { return this.getNlriRegistry().registerNlriSerializer(nlriClass, serializer); } @Override public AutoCloseable registerParameterParser(final int parameterType, final ParameterParser parser) { return this.getParameterRegistry().registerParameterParser(parameterType, parser); } @Override public AutoCloseable registerParameterSerializer(final Class<? extends BgpParameters> paramClass, final ParameterSerializer serializer) { return this.getParameterRegistry().registerParameterSerializer(paramClass, serializer); } @Override public AutoCloseable registerSubsequentAddressFamily(final Class<? extends SubsequentAddressFamily> clazz, final int number) { return this.getSubsequentAddressFamilyRegistry().registerSubsequentAddressFamily(clazz, number); } @Override public ReferenceCache getReferenceCache() { return this.referenceCache; } @Override public AutoCloseable registerExtendedCommunitySerializer(final Class<? extends ExtendedCommunity> extendedCommunityClass, final ExtendedCommunitySerializer serializer) { return this.getExtendedCommunityRegistry().registerExtendedCommunitySerializer(extendedCommunityClass, serializer); } @Override public AutoCloseable registerExtendedCommunityParser(final int type, final int subtype, final ExtendedCommunityParser parser) { return this.getExtendedCommunityRegistry().registerExtendedCommunityParser(type, subtype, parser); } @Override public AutoCloseable registerBgpPrefixSidTlvParser(final int tlvType, final BgpPrefixSidTlvParser parser) { return this.getBgpPrefixSidTlvRegistry().registerBgpPrefixSidTlvParser(tlvType, parser); } @Override public AutoCloseable registerBgpPrefixSidTlvSerializer(final Class<? extends BgpPrefixSidTlv> tlvClass, final BgpPrefixSidTlvSerializer serializer) { return this.getBgpPrefixSidTlvRegistry().registerBgpPrefixSidTlvSerializer(tlvClass, serializer); } }
BUG-8548: Pass missing parameter to SimpleBGPExtensionProviderContext#registerNlriParser Change-Id: I625f82d64efa0d2843b94de31c649572be9cacf9 Signed-off-by: Claudio D. Gasparini <[email protected]>
bgp/parser-spi/src/main/java/org/opendaylight/protocol/bgp/parser/spi/pojo/SimpleBGPExtensionProviderContext.java
BUG-8548: Pass missing parameter to
Java
epl-1.0
2989e780b78b82e2ce4497f89be1954ef434cad3
0
mvolaart/openhab,magcode/openhab,johkin/openhab,PolymorhicCode/openhab,mleegwt/openhab,idserda/openhab,kreutpet/openhab,revenz/openhab,sedstef/openhab,dominicdesu/openhab,juri8/openhab,watou/openhab,Jakey69/openhab,jowiho/openhab,jowiho/openhab,aschor/openhab,paolodenti/openhab,Mixajlo/openhab,basriram/openhab,kreutpet/openhab,sitewhere/openhab,revenz/openhab,innoq/openhab,peuter/openhab,marcelrv/openhab,magcode/openhab,georgwiltschek/openhab,kuijp/openhab,sedstef/openhab,openhab/openhab,tomtrath/openhab,paphko/openhab,jhonpaulrocha/openhabss,JoeCob/openhab,tarioch/openhab,tarioch/openhab,hmerk/openhab,fbeke/openhab,jowi24/openhab,docbender/openhab,mash0304/openhab,Jakey69/openhab,falkena/openhab,clanko8285/openhab,maraszm/openhab,RafalLukawiecki/openhab1-addons,Gecko33/openhab,kgoderis/openhab,jowi24/openhab,sedstef/openhab,paulianttila/openhab,maraszm/openhab,robnielsen/openhab,lewie/openhab,smerschjohann/openhab,ollie-dev/openhab,starwarsfan/openhab,lewie/openhab,paolodenti/openhab,jforge/openhab,dbadia/openhab,savageautomate/openhab,digitaldan/openhab,curtisstpierre/openhab,digitaldan/openhab,savageautomate/openhab,CondormanFr/openhab,JoeCob/openhab,marcelerkel/openhab,resetnow/openhab,richbeales/openhab,mleegwt/openhab,AutoMates/openhab,cschneider/openhab,clanko8285/openhab,watou/openhab,doubled-ca/openhab1-addons,maraszm/openhab,lmaertin/openhab,sja/openhab,abrenk/openhab,theoweiss/openhab,abrenk/openhab,cesarmarinhorj/openhab,CrackerStealth/openhab,swatchy2dot0/openhab,wojtus/openhab,saydulk/openhab,eschava/openhab,hemantsangwan/openhab,mattnl/openhab,eschava/openhab,dmize/openhab,resetnow/openhab,vgoldman/openhab,georgwiltschek/openhab,saydulk/openhab,seebag/openhab,aschor/openhab,sibbi77/openhab,CondormanFr/openhab,idserda/openhab,sytone/openhab,querdenker2k/openhab,cvanorman/openhab,Gecko33/openhab,steve-bate/openhab,coolweb/openhab,gilhmauy/openhab,jhonpaulrocha/openhabss,mleegwt/openhab,gunthor/openhab,gunthor/openhab,dbadia/openhab,PolymorhicCode/openhab,TheOriginalAndrobot/openhab,paulianttila/openhab,paphko/openhab,evansj/openhab,elifesy/openhab,lmaertin/openhab,mdbergmann/openhab,hmerk/openhab,QuailAutomation/openhab,dominicdesu/openhab,TheNetStriker/openhab,cslauritsen/openhab,andrey-desman/openhab-hdl,clanko8285/openhab,kuijp/openhab,tomtrath/openhab,dominicdesu/openhab,taupinfada/openhab,paixaop/openhab,dvanherbergen/openhab,tomtrath/openhab,falkena/openhab,robbyb67/openhab,tarioch/openhab,lewie/openhab,computergeek1507/openhab,gilhmauy/openhab,ShanksSGV/openhab,mjsolidarios/openhab,doubled-ca/openhab1-addons,elifesy/openhab,magcode/openhab,Greblys/openhab,lewie/openhab,magcode/openhab,juri8/openhab,foxy82/openhab,hemantsangwan/openhab,Greblys/openhab,kreutpet/openhab,taimos/openhab,mjsolidarios/openhab,dmize/openhab,ShanksSGV/openhab,peuter/openhab,paulianttila/openhab,kaikreuzer/openhab,beowulfe/openhab,wojtus/openhab,cschneider/openhab,smerschjohann/openhab,berndpfrommer/openhab,maraszm/openhab,Gerguis/open,wep4you/openhab,Mixajlo/openhab,dominicdesu/openhab,savageautomate/openhab,holgercn/openhab,Snickermicker/openhab,eschava/openhab,Jakey69/openhab,Gerguis/openhab2,cyclingengineer/openhab,netwolfuk/openhab,resetnow/openhab,dodger777/openhabMod,AutoMates/openhab,svenschaefer74/openhab,digitaldan/openhab,clinique/openhab,innoq/openhab,abrenk/openhab,querdenker2k/openhab,gerrieg/openhab,SwissKid/openhab,idserda/openhab,Mike-Petersen/openhab,seebag/openhab,magcode/openhab,Mike-Petersen/openhab,mleegwt/openhab,steintore/openhab,paphko/openhab,johkin/openhab,mash0304/openhab,theoweiss/openhab,jforge/openhab,Gerguis/open,querdenker2k/openhab,Jakey69/openhab,dfliess/openhab,TheNetStriker/openhab,teichsta/openhab,robnielsen/openhab,evansj/openhab,fbeke/openhab,evansj/openhab,dmize/openhab,cvanorman/openhab,svenschaefer74/openhab,gernoteger/openhab_contributions,openhab/openhab,gilhmauy/openhab,mroeckl/openhab,computergeek1507/openhab,kgoderis/openhab,jhonpaulrocha/openhabss,dominicdesu/openhab,bakrus/openhab,sitewhere/openhab,SwissKid/openhab,jforge/openhab,dmize/openhab,innoq/openhab,berndpfrommer/openhab,ssalonen/openhab,cesarmarinhorj/openhab,MCherifiOSS/openhab,eschava/openhab,ollie-dev/openhab,aidanom1/openhab,cdjackson/openhab,coolweb/openhab,watou/openhab,computergeek1507/openhab,hemantsangwan/openhab,kgoderis/openhab,clinique/openhab,Gerguis/open,aruder77/openhab,taupinfada/openhab,Gerguis/open,druciak/openhab,sytone/openhab,aschor/openhab,wojtus/openhab,johkin/openhab,AutoMates/openhab,robbyb67/openhab,saydulk/openhab,mroeckl/openhab,kreutpet/openhab,taupinfada/openhab,LaurensVanAcker/openhab,docbender/openhab,gerrieg/openhab,cdjackson/openhab,jowi24/openhab,dbadia/openhab,ShanksSGV/openhab,mvolaart/openhab,clanko8285/openhab,frami/openhab,peuter/openhab,aidanom1/openhab,RafalLukawiecki/openhab1-addons,wep4you/openhab,teichsta/openhab,mjsolidarios/openhab,foxy82/openhab,stefanroellin/openhab,maraszm/openhab,paolodenti/openhab,paphko/openhab,lmaertin/openhab,foxy82/openhab,peuter/openhab,querdenker2k/openhab,watou/openhab,TheNetStriker/openhab,mdbergmann/openhab,basriram/openhab,bakrus/openhab,AutoMates/openhab,dmize/openhab,Greblys/openhab,sibbi77/openhab,wurtzel/openhab,xsnrg/openhab,Snickermicker/openhab,sja/openhab,steintore/openhab,revenz/openhab,kgoderis/openhab,gernoteger/openhab_contributions,mroeckl/openhab,LaurensVanAcker/openhab,taimos/openhab,stefanroellin/openhab,paolodenti/openhab,bbesser/openhab1-addons,saydulk/openhab,rmayr/openhab,CrackerStealth/openhab,dbadia/openhab,beowulfe/openhab,g8kmh/openhab,falkena/openhab,CondormanFr/openhab,jforge/openhab,mjsolidarios/openhab,coolweb/openhab,bakrus/openhab,theoweiss/openhab,svenschreier/openhab,savageautomate/openhab,vgoldman/openhab,Gecko33/openhab,georgwiltschek/openhab,mdbergmann/openhab,rmayr/openhab,savageautomate/openhab,aruder77/openhab,PolymorhicCode/openhab,abrenk/openhab,jhonpaulrocha/openhabss,sumnerboy12/openhab,wuellueb/openhab,ivanfmartinez/openhab,JensErat/openhab,beowulfe/openhab,AutoMates/openhab,berndpfrommer/openhab,MitchSUEW/openhab,wojtus/openhab,Gerguis/open,frami/openhab,TheOriginalAndrobot/openhab,ivanfmartinez/openhab,bbesser/openhab1-addons,g8kmh/openhab,starwarsfan/openhab,Jakey69/openhab,robbyb67/openhab,sitewhere/openhab,dvanherbergen/openhab,mattnl/openhab,basriram/openhab,wuellueb/openhab,tomtrath/openhab,robbyb67/openhab,teichsta/openhab,craigham/openhab,lewie/openhab,openhab/openhab,andrey-desman/openhab-hdl,jowiho/openhab,andreasgebauer/openhab,starwarsfan/openhab,JoeCob/openhab,basriram/openhab,kbialek/openhab,JoeCob/openhab,richbeales/openhab,dfliess/openhab,seebag/openhab,juri8/openhab,doubled-ca/openhab1-addons,bakrus/openhab,kgoderis/openhab,falkena/openhab,abrenk/openhab,elifesy/openhab,ShanksSGV/openhab,Greblys/openhab,mash0304/openhab,JensErat/openhab,sedstef/openhab,g8kmh/openhab,gernoteger/openhab_contributions,cslauritsen/openhab,CrackerStealth/openhab,robbyb67/openhab,gernoteger/openhab_contributions,cschneider/openhab,fbeke/openhab,gernoteger/openhab_contributions,mash0304/openhab,sumnerboy12/openhab,mattnl/openhab,maraszm/openhab,marcelerkel/openhab,vgoldman/openhab,RafalLukawiecki/openhab1-addons,Snickermicker/openhab,Gerguis/openhab2,mroeckl/openhab,cvanorman/openhab,jhonpaulrocha/openhabss,beowulfe/openhab,mroeckl/openhab,QuailAutomation/openhab,mdbergmann/openhab,sibbi77/openhab,cyclingengineer/openhab,saydulk/openhab,lmaertin/openhab,paixaop/openhab,eschava/openhab,cslauritsen/openhab,dodger777/openhabMod,CrackerStealth/openhab,CondormanFr/openhab,aschor/openhab,cslauritsen/openhab,kbialek/openhab,richbeales/openhab,JensErat/openhab,craigham/openhab,frami/openhab,steintore/openhab,QuailAutomation/openhab,paixaop/openhab,andreasgebauer/openhab,tarioch/openhab,robnielsen/openhab,netwolfuk/openhab,smerschjohann/openhab,andreasgebauer/openhab,craigham/openhab,PolymorhicCode/openhab,dodger777/openhabMod,andreasgebauer/openhab,druciak/openhab,peuter/openhab,saydulk/openhab,RafalLukawiecki/openhab1-addons,sitewhere/openhab,teichsta/openhab,cesarmarinhorj/openhab,cesarmarinhorj/openhab,hemantsangwan/openhab,marcelrv/openhab,wep4you/openhab,peuter/openhab,JensErat/openhab,PolymorhicCode/openhab,cyclingengineer/openhab,computergeek1507/openhab,rmayr/openhab,gunthor/openhab,PolymorhicCode/openhab,taimos/openhab,sja/openhab,kbialek/openhab,cesarmarinhorj/openhab,AutoMates/openhab,jhonpaulrocha/openhabss,JensErat/openhab,paulianttila/openhab,digitaldan/openhab,sitewhere/openhab,RafalLukawiecki/openhab1-addons,swatchy2dot0/openhab,paphko/openhab,bbesser/openhab1-addons,dodger777/openhabMod,craigham/openhab,dbadia/openhab,marcelerkel/openhab,swatchy2dot0/openhab,MCherifiOSS/openhab,mattnl/openhab,starwarsfan/openhab,SwissKid/openhab,gerrieg/openhab,paixaop/openhab,AutoMates/openhab,clinique/openhab,innoq/openhab,innoq/openhab,gernoteger/openhab_contributions,aruder77/openhab,Gerguis/open,joek/openhab1-addons,robnielsen/openhab,falkena/openhab,resetnow/openhab,tomtrath/openhab,g8kmh/openhab,clanko8285/openhab,kbialek/openhab,mvolaart/openhab,joek/openhab1-addons,mash0304/openhab,georgwiltschek/openhab,ivanfmartinez/openhab,marcelrv/openhab,querdenker2k/openhab,marcelerkel/openhab,gerrieg/openhab,johkin/openhab,sedstef/openhab,andrey-desman/openhab-hdl,mroeckl/openhab,paulianttila/openhab,doubled-ca/openhab1-addons,stefanroellin/openhab,holgercn/openhab,marcelrv/openhab,steve-bate/openhab,georgwiltschek/openhab,tarioch/openhab,gilhmauy/openhab,revenz/openhab,ssalonen/openhab,frami/openhab,magcode/openhab,openhab/openhab,bbesser/openhab1-addons,resetnow/openhab,svenschreier/openhab,cesarmarinhorj/openhab,dfliess/openhab,cvanorman/openhab,evansj/openhab,stefanroellin/openhab,basriram/openhab,jhonpaulrocha/openhabss,robbyb67/openhab,elifesy/openhab,JensErat/openhab,steve-bate/openhab,andreasgebauer/openhab,druciak/openhab,seebag/openhab,QuailAutomation/openhab,teichsta/openhab,Snickermicker/openhab,wuellueb/openhab,svenschaefer74/openhab,joek/openhab1-addons,clanko8285/openhab,sedstef/openhab,digitaldan/openhab,kuijp/openhab,mrguessed/openhab,TheOriginalAndrobot/openhab,clinique/openhab,juri8/openhab,dodger777/openhabMod,kreutpet/openhab,marcelerkel/openhab,joek/openhab1-addons,cesarmarinhorj/openhab,frami/openhab,Gerguis/openhab2,evansj/openhab,kaikreuzer/openhab,LaurensVanAcker/openhab,paixaop/openhab,svenschaefer74/openhab,MCherifiOSS/openhab,MitchSUEW/openhab,aruder77/openhab,bakrus/openhab,abrenk/openhab,sja/openhab,joek/openhab1-addons,innoq/openhab,foxy82/openhab,fbeke/openhab,marcelrv/openhab,andreasgebauer/openhab,andrey-desman/openhab-hdl,teichsta/openhab,tdiekmann/openhab,SwissKid/openhab,frami/openhab,JoeCob/openhab,smerschjohann/openhab,cdjackson/openhab,Mixajlo/openhab,taimos/openhab,ollie-dev/openhab,mrguessed/openhab,wurtzel/openhab,Greblys/openhab,robbyb67/openhab,smerschjohann/openhab,rmayr/openhab,craigham/openhab,mjsolidarios/openhab,dbadia/openhab,georgwiltschek/openhab,beowulfe/openhab,ssalonen/openhab,paulianttila/openhab,sitewhere/openhab,wojtus/openhab,eschava/openhab,cdjackson/openhab,wuellueb/openhab,elifesy/openhab,kaikreuzer/openhab,docbender/openhab,gunthor/openhab,curtisstpierre/openhab,CrackerStealth/openhab,coolweb/openhab,jowi24/openhab,docbender/openhab,mleegwt/openhab,ivanfmartinez/openhab,Gerguis/openhab2,TheNetStriker/openhab,hmerk/openhab,ollie-dev/openhab,netwolfuk/openhab,mleegwt/openhab,svenschaefer74/openhab,clinique/openhab,kaikreuzer/openhab,dfliess/openhab,jowi24/openhab,digitaldan/openhab,mdbergmann/openhab,Gecko33/openhab,elifesy/openhab,dvanherbergen/openhab,aidanom1/openhab,netwolfuk/openhab,TheNetStriker/openhab,Mixajlo/openhab,kuijp/openhab,falkena/openhab,teichsta/openhab,AutoMates/openhab,xsnrg/openhab,CrackerStealth/openhab,kuijp/openhab,JensErat/openhab,svenschreier/openhab,mvolaart/openhab,clinique/openhab,theoweiss/openhab,steve-bate/openhab,Gerguis/open,digitaldan/openhab,tdiekmann/openhab,gilhmauy/openhab,dfliess/openhab,CondormanFr/openhab,juri8/openhab,svenschreier/openhab,xsnrg/openhab,Mike-Petersen/openhab,mjsolidarios/openhab,sumnerboy12/openhab,querdenker2k/openhab,holgercn/openhab,cyclingengineer/openhab,taupinfada/openhab,stefanroellin/openhab,mrguessed/openhab,kbialek/openhab,JoeCob/openhab,resetnow/openhab,aschor/openhab,Mike-Petersen/openhab,ivanfmartinez/openhab,Gecko33/openhab,craigham/openhab,robnielsen/openhab,Greblys/openhab,netwolfuk/openhab,evansj/openhab,SwissKid/openhab,cschneider/openhab,georgwiltschek/openhab,dvanherbergen/openhab,gerrieg/openhab,rmayr/openhab,xsnrg/openhab,Mike-Petersen/openhab,bakrus/openhab,taupinfada/openhab,mash0304/openhab,lmaertin/openhab,lmaertin/openhab,sibbi77/openhab,steve-bate/openhab,RafalLukawiecki/openhab1-addons,TheOriginalAndrobot/openhab,foxy82/openhab,digitaldan/openhab,marcelrv/openhab,richbeales/openhab,mdbergmann/openhab,swatchy2dot0/openhab,Mike-Petersen/openhab,coolweb/openhab,swatchy2dot0/openhab,andrey-desman/openhab-hdl,wojtus/openhab,dvanherbergen/openhab,paolodenti/openhab,aruder77/openhab,juri8/openhab,paolodenti/openhab,sumnerboy12/openhab,jowi24/openhab,dmize/openhab,vgoldman/openhab,starwarsfan/openhab,computergeek1507/openhab,foxy82/openhab,watou/openhab,beowulfe/openhab,starwarsfan/openhab,sytone/openhab,wep4you/openhab,CondormanFr/openhab,idserda/openhab,mrguessed/openhab,cslauritsen/openhab,kgoderis/openhab,maraszm/openhab,revenz/openhab,fbeke/openhab,sibbi77/openhab,cschneider/openhab,LaurensVanAcker/openhab,svenschaefer74/openhab,andrey-desman/openhab-hdl,robnielsen/openhab,ssalonen/openhab,TheNetStriker/openhab,MitchSUEW/openhab,fbeke/openhab,druciak/openhab,tdiekmann/openhab,kbialek/openhab,wurtzel/openhab,jowi24/openhab,gernoteger/openhab_contributions,holgercn/openhab,revenz/openhab,g8kmh/openhab,TheNetStriker/openhab,sumnerboy12/openhab,wep4you/openhab,wurtzel/openhab,jforge/openhab,wurtzel/openhab,cvanorman/openhab,holgercn/openhab,wuellueb/openhab,docbender/openhab,Gecko33/openhab,mvolaart/openhab,vgoldman/openhab,curtisstpierre/openhab,jforge/openhab,doubled-ca/openhab1-addons,cyclingengineer/openhab,kbialek/openhab,marcelrv/openhab,Mixajlo/openhab,openhab/openhab,resetnow/openhab,tomtrath/openhab,mjsolidarios/openhab,Gecko33/openhab,craigham/openhab,sytone/openhab,aschor/openhab,tomtrath/openhab,cyclingengineer/openhab,Gerguis/openhab2,sumnerboy12/openhab,marcelerkel/openhab,dodger777/openhabMod,kaikreuzer/openhab,curtisstpierre/openhab,jforge/openhab,MitchSUEW/openhab,richbeales/openhab,MCherifiOSS/openhab,stefanroellin/openhab,cschneider/openhab,foxy82/openhab,docbender/openhab,openhab/openhab,svenschreier/openhab,cslauritsen/openhab,cyclingengineer/openhab,gilhmauy/openhab,sja/openhab,robbyb67/openhab,mroeckl/openhab,netwolfuk/openhab,kaikreuzer/openhab,seebag/openhab,mash0304/openhab,aidanom1/openhab,MitchSUEW/openhab,xsnrg/openhab,savageautomate/openhab,taupinfada/openhab,dominicdesu/openhab,TheOriginalAndrobot/openhab,andreasgebauer/openhab,andrey-desman/openhab-hdl,revenz/openhab,watou/openhab,LaurensVanAcker/openhab,wurtzel/openhab,holgercn/openhab,richbeales/openhab,druciak/openhab,smerschjohann/openhab,gilhmauy/openhab,curtisstpierre/openhab,watou/openhab,teichsta/openhab,paixaop/openhab,wuellueb/openhab,steintore/openhab,berndpfrommer/openhab,eschava/openhab,sytone/openhab,gerrieg/openhab,LaurensVanAcker/openhab,sja/openhab,wurtzel/openhab,richbeales/openhab,sja/openhab,ShanksSGV/openhab,ollie-dev/openhab,Mike-Petersen/openhab,abrenk/openhab,computergeek1507/openhab,jowiho/openhab,TheOriginalAndrobot/openhab,Snickermicker/openhab,hemantsangwan/openhab,ssalonen/openhab,druciak/openhab,magcode/openhab,tdiekmann/openhab,tdiekmann/openhab,steintore/openhab,sibbi77/openhab,MitchSUEW/openhab,aidanom1/openhab,tomtrath/openhab,berndpfrommer/openhab,hmerk/openhab,dfliess/openhab,curtisstpierre/openhab,juri8/openhab,falkena/openhab,paphko/openhab,kreutpet/openhab,steve-bate/openhab,hmerk/openhab,JoeCob/openhab,vgoldman/openhab,cdjackson/openhab,Jakey69/openhab,fbeke/openhab,idserda/openhab,johkin/openhab,ollie-dev/openhab,lewie/openhab,taimos/openhab,jowiho/openhab,cslauritsen/openhab,gunthor/openhab,hemantsangwan/openhab,mattnl/openhab,theoweiss/openhab,mrguessed/openhab,Snickermicker/openhab,dvanherbergen/openhab,wojtus/openhab,ShanksSGV/openhab,lewie/openhab,seebag/openhab,aruder77/openhab,MCherifiOSS/openhab,swatchy2dot0/openhab,basriram/openhab,mvolaart/openhab,dfliess/openhab,Greblys/openhab,coolweb/openhab,wep4you/openhab,xsnrg/openhab,clinique/openhab,bbesser/openhab1-addons,kgoderis/openhab,dodger777/openhabMod,kuijp/openhab,paixaop/openhab,johkin/openhab,theoweiss/openhab,svenschreier/openhab,MitchSUEW/openhab,cvanorman/openhab,bakrus/openhab,taimos/openhab,dodger777/openhabMod,cschneider/openhab,Gerguis/openhab2,taimos/openhab,peuter/openhab,tarioch/openhab,paixaop/openhab,QuailAutomation/openhab,g8kmh/openhab,rmayr/openhab,maraszm/openhab,aidanom1/openhab,gunthor/openhab,Jakey69/openhab,docbender/openhab,ssalonen/openhab,stefanroellin/openhab,xsnrg/openhab,PolymorhicCode/openhab,marcelerkel/openhab,sytone/openhab,mrguessed/openhab,bakrus/openhab,hemantsangwan/openhab,ivanfmartinez/openhab,tdiekmann/openhab,idserda/openhab,smerschjohann/openhab,lmaertin/openhab,curtisstpierre/openhab,berndpfrommer/openhab,Mixajlo/openhab,johkin/openhab,MCherifiOSS/openhab,starwarsfan/openhab,mleegwt/openhab,saydulk/openhab,doubled-ca/openhab1-addons,sitewhere/openhab,QuailAutomation/openhab,bbesser/openhab1-addons,Gerguis/openhab2,steintore/openhab,aidanom1/openhab,holgercn/openhab,SwissKid/openhab,CondormanFr/openhab,g8kmh/openhab,mattnl/openhab,mdbergmann/openhab,MCherifiOSS/openhab,ShanksSGV/openhab,mroeckl/openhab,hmerk/openhab,gunthor/openhab,coolweb/openhab,cdjackson/openhab,elifesy/openhab,joek/openhab1-addons,jowiho/openhab,cschneider/openhab
/** * Copyright (c) 2010-2013, openHAB.org and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.binding.netatmo.internal; import static org.apache.commons.lang.StringUtils.isNotBlank; import static org.openhab.binding.netatmo.internal.messages.MeasurementRequest.createKey; import java.math.BigDecimal; import java.util.Collection; import java.util.Dictionary; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.openhab.binding.netatmo.NetatmoBindingProvider; import org.openhab.binding.netatmo.internal.messages.DeviceListRequest; import org.openhab.binding.netatmo.internal.messages.DeviceListResponse; import org.openhab.binding.netatmo.internal.messages.DeviceListResponse.Device; import org.openhab.binding.netatmo.internal.messages.DeviceListResponse.Module; import org.openhab.binding.netatmo.internal.messages.MeasurementRequest; import org.openhab.binding.netatmo.internal.messages.MeasurementResponse; import org.openhab.binding.netatmo.internal.messages.NetatmoError; import org.openhab.binding.netatmo.internal.messages.RefreshTokenRequest; import org.openhab.binding.netatmo.internal.messages.RefreshTokenResponse; import org.openhab.binding.netatmo.internal.NetatmoMeasureType; import org.openhab.core.binding.AbstractActiveBinding; import org.openhab.core.library.types.DecimalType; import org.openhab.core.types.State; import org.osgi.service.cm.ConfigurationException; import org.osgi.service.cm.ManagedService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Binding that gets measurements from the Netatmo API every couple of minutes. * * @author Andreas Brenk * @author Thomas.Eichstaedt-Engelen * @author Gaël L'hopital * @since 1.4.0 */ public class NetatmoBinding extends AbstractActiveBinding<NetatmoBindingProvider> implements ManagedService { private static final String DEFAULT_USER_ID = "DEFAULT_USER"; private static final Logger logger = LoggerFactory.getLogger(NetatmoBinding.class); protected static final String CONFIG_CLIENT_ID = "clientid"; protected static final String CONFIG_CLIENT_SECRET = "clientsecret"; protected static final String CONFIG_REFRESH = "refresh"; protected static final String CONFIG_REFRESH_TOKEN = "refreshtoken"; /** * The refresh interval which is used to poll values from the Netatmo server * (optional, defaults to 300000ms) */ private long refreshInterval = 300000; private Map<String, OAuthCredentials> credentialsCache = new HashMap<String, OAuthCredentials>(); /** * {@inheritDoc} */ @Override protected String getName() { return "Netatmo Refresh Service"; } /** * {@inheritDoc} */ @Override protected long getRefreshInterval() { return this.refreshInterval; } /** * {@inheritDoc} */ @SuppressWarnings("incomplete-switch") @Override protected void execute() { logger.debug("Querying Netatmo API"); for (String userid : credentialsCache.keySet()) { OAuthCredentials oauthCredentials = getOAuthCredentials(userid); if (oauthCredentials.noAccessToken()) { // initial run after a restart, so get an access token first oauthCredentials.refreshAccessToken(); } try { if (oauthCredentials.firstExecution) { processDeviceList(oauthCredentials); } Map<String, Map<String, BigDecimal>> deviceMeasureValueMap = processMeasurements(oauthCredentials); for (final NetatmoBindingProvider provider : this.providers) { for (final String itemName : provider.getItemNames()) { final String deviceId = provider.getDeviceId(itemName); final String moduleId = provider.getModuleId(itemName); final NetatmoMeasureType measureType = provider.getMeasureType(itemName); State state = null; switch (measureType) { case TEMPERATURE: case CO2: case HUMIDITY: case NOISE: case PRESSURE: final String requestKey = createKey(deviceId, moduleId); state = new DecimalType(deviceMeasureValueMap.get(requestKey).get(measureType.getMeasure())); break; case BATTERYVP: case RFSTATUS: for (Module module : oauthCredentials.deviceListResponse.getModules()) { if (module.getId().equals(moduleId)) { switch (measureType) { case BATTERYVP: state = new DecimalType(module.getBatteryVp()); break; case RFSTATUS: state = new DecimalType(module.getRfStatus()); break; } } } break; case ALTITUDE: case LATITUDE: case LONGITUDE: case WIFISTATUS: for (Device device : oauthCredentials.deviceListResponse.getDevices()) { if (device.getId().equals(deviceId)) { switch (measureType) { case ALTITUDE: state = new DecimalType(device.getAltitude()); break; case LATITUDE: state = new DecimalType(device.getLatitude()); break; case LONGITUDE: state = new DecimalType(device.getLongitude()); break; case WIFISTATUS: state = new DecimalType(device.getWifiStatus()); break; } } } break; } if (state != null) { this.eventPublisher.postUpdate(itemName, state); } } } } catch (NetatmoException ne) { logger.error(ne.getMessage()); } } } private Map<String, Map<String, BigDecimal>> processMeasurements(OAuthCredentials oauthCredentials) { Map<String, Map<String, BigDecimal>> deviceMeasureValueMap = new HashMap<String, Map<String,BigDecimal>>(); for (final MeasurementRequest request : createMeasurementRequests()) { final MeasurementResponse response = request.execute(); logger.debug("Request: {}", request); logger.debug("Response: {}", response); if (response.isError()) { final NetatmoError error = response.getError(); if (error.isAccessTokenExpired()) { oauthCredentials.refreshAccessToken(); execute(); } else { throw new NetatmoException(error.getMessage()); } break; // abort processing measurement requests } else { processMeasurementResponse(request, response, deviceMeasureValueMap); } } return deviceMeasureValueMap; } private void processDeviceList(OAuthCredentials oauthCredentials) { logger.debug("Request: {}", oauthCredentials.deviceListRequest); logger.debug("Response: {}", oauthCredentials.deviceListResponse); if (oauthCredentials.deviceListResponse.isError()) { final NetatmoError error = oauthCredentials.deviceListResponse.getError(); if (error.isAccessTokenExpired()) { oauthCredentials.refreshAccessToken(); execute(); } else { throw new NetatmoException(error.getMessage()); } return; // abort processing } else { processDeviceListResponse(oauthCredentials.deviceListResponse); oauthCredentials.firstExecution = false; } } /** * Processes an incoming {@link DeviceListResponse}. * <p> */ private void processDeviceListResponse(final DeviceListResponse response) { // Prepare a map of all known device measurements final Map<String, Device> deviceMap = new HashMap<String, Device>(); final Map<String, Set<String>> deviceMeasurements = new HashMap<String, Set<String>>(); for (final Device device : response.getDevices()) { final String deviceId = device.getId(); deviceMap.put(deviceId, device); for (final String measurement : device.getMeasurements()) { if (!deviceMeasurements.containsKey(deviceId)) { deviceMeasurements.put(deviceId, new HashSet<String>()); } deviceMeasurements.get(deviceId).add(measurement); } } // Prepare a map of all known module measurements final Map<String, Module> moduleMap = new HashMap<String, Module>(); final Map<String, Set<String>> moduleMeasurements = new HashMap<String, Set<String>>(); for (final Module module : response.getModules()) { final String moduleId = module.getId(); moduleMap.put(moduleId, module); for (final String measurement : module.getMeasurements()) { if (!moduleMeasurements.containsKey(moduleId)) { moduleMeasurements.put(moduleId, new HashSet<String>()); } moduleMeasurements.get(moduleId).add(measurement); } } // Remove all configured items from the maps for (final NetatmoBindingProvider provider : this.providers) { for (final String itemName : provider.getItemNames()) { final String deviceId = provider.getDeviceId(itemName); final String moduleId = provider.getModuleId(itemName); final NetatmoMeasureType measureType = provider.getMeasureType(itemName); final Set<String> measurements; if (moduleId != null) { measurements = moduleMeasurements.get(moduleId); } else { measurements = deviceMeasurements.get(deviceId); } if (measurements != null) { measurements.remove(measureType.getMeasure()); } } } // Log all unconfigured measurements final StringBuilder message = new StringBuilder(); for (Entry<String, Set<String>> entry : deviceMeasurements.entrySet()) { final String deviceId = entry.getKey(); final Device device = deviceMap.get(deviceId); for (String measurement : entry.getValue()) { message.append("\t" + deviceId + "#" + measurement + " (" + device.getModuleName() + ")\n"); } } for (Entry<String, Set<String>> entry : moduleMeasurements.entrySet()) { final String moduleId = entry.getKey(); final Module module = moduleMap.get(moduleId); for (String measurement : entry.getValue()) { message.append("\t" + module.getMainDevice() + "#" + moduleId + "#" + measurement + " (" + module.getModuleName() + ")\n"); } } if (message.length() > 0) { message.insert(0,"The following Netatmo measurements are not yet configured:\n"); logger.info(message.toString()); } } /** * Creates the necessary requests to query the Netatmo API for all measures * that have a binding. One request can query all measures of a single * device or module. */ private Collection<MeasurementRequest> createMeasurementRequests() { final Map<String, MeasurementRequest> requests = new HashMap<String, MeasurementRequest>(); for (final NetatmoBindingProvider provider : this.providers) { for (final String itemName : provider.getItemNames()) { final String userid = provider.getUserid(itemName); final String deviceId = provider.getDeviceId(itemName); final String moduleId = provider.getModuleId(itemName); final NetatmoMeasureType measureType = provider.getMeasureType(itemName); final String requestKey = createKey(deviceId, moduleId); switch (measureType) { case TEMPERATURE: case CO2: case HUMIDITY: case NOISE: case PRESSURE: OAuthCredentials oauthCredentials = getOAuthCredentials(userid); if (oauthCredentials != null) { if (!requests.containsKey(requestKey)) { requests.put(requestKey, new MeasurementRequest(oauthCredentials.accessToken, deviceId, moduleId)); } requests.get(requestKey).addMeasure(measureType); break; } default: break; } } } return requests.values(); } private void processMeasurementResponse(final MeasurementRequest request, final MeasurementResponse response, Map<String, Map<String, BigDecimal>> deviceMeasureValueMap) { final List<BigDecimal> values = response.getBody().get(0).getValues().get(0); final Map<String, BigDecimal> valueMap = new HashMap<String, BigDecimal>(); int index = 0; for (final String measure : request.getMeasures()) { final BigDecimal value = values.get(index); valueMap.put(measure, value); index++; } deviceMeasureValueMap.put(request.getKey(), valueMap); } /** * Returns the cached {@link OAuthCredentials} for the given {@code userid}. * If their is no such cached {@link OAuthCredentials} element, the cache is * searched with the {@code DEFAULT_USER}. If there is still no cached element * found {@code NULL} is returned. * * @param userid the userid to find the {@link OAuthCredentials} * @return the cached {@link OAuthCredentials} or {@code NULL} */ private OAuthCredentials getOAuthCredentials(String userid) { if (credentialsCache.containsKey(userid)) { return credentialsCache.get(userid); } else { return credentialsCache.get(DEFAULT_USER_ID); } } /** * {@inheritDoc} */ @Override public void updated(final Dictionary<String, ?> config) throws ConfigurationException { if (config != null) { final String refreshIntervalString = (String) config.get(CONFIG_REFRESH); if (isNotBlank(refreshIntervalString)) { this.refreshInterval = Long.parseLong(refreshIntervalString); } Enumeration<String> configKeys = config.keys(); while (configKeys.hasMoreElements()) { String configKey = (String) configKeys.nextElement(); // the config-key enumeration contains additional keys that we // don't want to process here ... if (CONFIG_REFRESH.equals(configKey) || "service.pid".equals(configKey)) { continue; } String userid; String configKeyTail; if (configKey.contains(".")) { String[] keyElements = configKey.split("\\."); userid = keyElements[0]; configKeyTail = keyElements[1]; } else { userid = DEFAULT_USER_ID; configKeyTail = configKey; } OAuthCredentials credentials = credentialsCache.get(userid); if (credentials == null) { credentials = new OAuthCredentials(); credentialsCache.put(userid, credentials); } String value = (String) config.get(configKeyTail); if (CONFIG_CLIENT_ID.equals(configKeyTail)) { credentials.clientId = value; } else if (CONFIG_CLIENT_SECRET.equals(configKeyTail)) { credentials.clientSecret= value; } else if (CONFIG_REFRESH_TOKEN.equals(configKeyTail)) { credentials.refreshToken = value; } else { throw new ConfigurationException( configKey, "the given configKey '" + configKey + "' is unknown"); } } setProperlyConfigured(true); } } /** * This internal class holds the different crendentials necessary for the * OAuth2 flow to work. It also provides basic methods to refresh the access * token. * * @author Thomas.Eichstaedt-Engelen * @since 1.6.0 */ static class OAuthCredentials { /** * The client id to access the Netatmo API. Normally set in * <code>openhab.cfg</code>. * * @see <a href="http://dev.netatmo.com/doc/authentication/usercred">Client * Credentials</a> */ String clientId; /** * The client secret to access the Netatmo API. Normally set in * <code>openhab.cfg</code>. * * @see <a href="http://dev.netatmo.com/doc/authentication/usercred">Client * Credentials</a> */ String clientSecret; /** * The refresh token to access the Netatmo API. Normally set in * <code>openhab.cfg</code>. * * @see <a * href="http://dev.netatmo.com/doc/authentication/usercred">Client&nbsp;Credentials</a> * @see <a * href="http://dev.netatmo.com/doc/authentication/refreshtoken">Refresh&nbsp;Token</a> */ String refreshToken; /** * The access token to access the Netatmo API. Automatically renewed from * the API using the refresh token. * * @see <a * href="http://dev.netatmo.com/doc/authentication/refreshtoken">Refresh * Token</a> * @see #refreshAccessToken() */ String accessToken; DeviceListResponse deviceListResponse = null; DeviceListRequest deviceListRequest = null; boolean firstExecution = true; public boolean noAccessToken() { return this.accessToken == null; } public void refreshAccessToken() { logger.debug("Refreshing access token."); final RefreshTokenRequest request = new RefreshTokenRequest(this.clientId, this.clientSecret, this.refreshToken); logger.debug("Request: {}", request); final RefreshTokenResponse response = request.execute(); logger.debug("Response: {}", response); this.accessToken = response.getAccessToken(); deviceListRequest = new DeviceListRequest(this.accessToken); deviceListResponse = deviceListRequest.execute(); } } }
bundles/binding/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/NetatmoBinding.java
/** * Copyright (c) 2010-2013, openHAB.org and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.binding.netatmo.internal; import static org.apache.commons.lang.StringUtils.isNotBlank; import static org.openhab.binding.netatmo.internal.messages.MeasurementRequest.createKey; import java.math.BigDecimal; import java.util.Collection; import java.util.Dictionary; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.openhab.binding.netatmo.NetatmoBindingProvider; import org.openhab.binding.netatmo.internal.messages.DeviceListRequest; import org.openhab.binding.netatmo.internal.messages.DeviceListResponse; import org.openhab.binding.netatmo.internal.messages.DeviceListResponse.Device; import org.openhab.binding.netatmo.internal.messages.DeviceListResponse.Module; import org.openhab.binding.netatmo.internal.messages.MeasurementRequest; import org.openhab.binding.netatmo.internal.messages.MeasurementResponse; import org.openhab.binding.netatmo.internal.messages.NetatmoError; import org.openhab.binding.netatmo.internal.messages.RefreshTokenRequest; import org.openhab.binding.netatmo.internal.messages.RefreshTokenResponse; import org.openhab.binding.netatmo.internal.NetatmoMeasureType; import org.openhab.core.binding.AbstractActiveBinding; import org.openhab.core.library.types.DecimalType; import org.openhab.core.types.State; import org.osgi.service.cm.ConfigurationException; import org.osgi.service.cm.ManagedService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Binding that gets measurements from the Netatmo API every couple of minutes. * * @author Andreas Brenk * @author Thomas.Eichstaedt-Engelen * @since 1.4.0 */ public class NetatmoBinding extends AbstractActiveBinding<NetatmoBindingProvider> implements ManagedService { private static final String DEFAULT_USER_ID = "DEFAULT_USER"; private static final Logger logger = LoggerFactory.getLogger(NetatmoBinding.class); protected static final String CONFIG_CLIENT_ID = "clientid"; protected static final String CONFIG_CLIENT_SECRET = "clientsecret"; protected static final String CONFIG_REFRESH = "refresh"; protected static final String CONFIG_REFRESH_TOKEN = "refreshtoken"; private static DeviceListResponse deviceListResponse = null; private static DeviceListRequest deviceListRequest = null; /** * The refresh interval which is used to poll values from the Netatmo server * (optional, defaults to 300000ms) */ private long refreshInterval = 300000; private Map<String, OAuthCredentials> credentialsCache = new HashMap<String, OAuthCredentials>(); /** * {@inheritDoc} */ @Override protected String getName() { return "Netatmo Refresh Service"; } /** * {@inheritDoc} */ @Override protected long getRefreshInterval() { return this.refreshInterval; } /** * {@inheritDoc} */ @SuppressWarnings("incomplete-switch") @Override protected void execute() { logger.debug("Querying Netatmo API"); for (String userid : credentialsCache.keySet()) { OAuthCredentials oauthCredentials = getOAuthCredentials(userid); if (oauthCredentials.noAccessToken()) { // initial run after a restart, so get an access token first oauthCredentials.refreshAccessToken(); } try { if (oauthCredentials.firstExecution) { processDeviceList(oauthCredentials); } Map<String, Map<String, BigDecimal>> deviceMeasureValueMap = processMeasurements(oauthCredentials); for (final NetatmoBindingProvider provider : this.providers) { for (final String itemName : provider.getItemNames()) { final String deviceId = provider.getDeviceId(itemName); final String moduleId = provider.getModuleId(itemName); final NetatmoMeasureType measureType = provider.getMeasureType(itemName); State state = null; switch (measureType) { case TEMPERATURE: case CO2: case HUMIDITY: case NOISE: case PRESSURE: final String requestKey = createKey(deviceId, moduleId); state = new DecimalType(deviceMeasureValueMap.get(requestKey).get(measureType.getMeasure())); break; case BATTERYVP: case RFSTATUS: for (Module module : deviceListResponse.getModules()) { if (module.getId().equals(moduleId)) { switch (measureType) { case BATTERYVP: state = new DecimalType(module.getBatteryVp()); break; case RFSTATUS: state = new DecimalType(module.getRfStatus()); break; } } } break; case ALTITUDE: case LATITUDE: case LONGITUDE: case WIFISTATUS: for (Device device : deviceListResponse.getDevices()) { if (device.getId().equals(deviceId)) { switch (measureType) { case ALTITUDE: state = new DecimalType(device.getAltitude()); break; case LATITUDE: state = new DecimalType(device.getLatitude()); break; case LONGITUDE: state = new DecimalType(device.getLongitude()); break; case WIFISTATUS: state = new DecimalType(device.getWifiStatus()); break; } } } break; } if (state != null) { this.eventPublisher.postUpdate(itemName, state); } } } } catch (NetatmoException ne) { logger.error(ne.getMessage()); } } } private Map<String, Map<String, BigDecimal>> processMeasurements(OAuthCredentials oauthCredentials) { Map<String, Map<String, BigDecimal>> deviceMeasureValueMap = new HashMap<String, Map<String,BigDecimal>>(); for (final MeasurementRequest request : createMeasurementRequests()) { final MeasurementResponse response = request.execute(); logger.debug("Request: {}", request); logger.debug("Response: {}", response); if (response.isError()) { final NetatmoError error = response.getError(); if (error.isAccessTokenExpired()) { oauthCredentials.refreshAccessToken(); execute(); } else { throw new NetatmoException(error.getMessage()); } break; // abort processing measurement requests } else { processMeasurementResponse(request, response, deviceMeasureValueMap); } } return deviceMeasureValueMap; } private void processDeviceList(OAuthCredentials oauthCredentials) { final DeviceListRequest request = new DeviceListRequest(oauthCredentials.accessToken); final DeviceListResponse response = request.execute(); logger.debug("Request: {}", request); logger.debug("Response: {}", response); if (response.isError()) { final NetatmoError error = response.getError(); if (error.isAccessTokenExpired()) { oauthCredentials.refreshAccessToken(); execute(); } else { throw new NetatmoException(error.getMessage()); } return; // abort processing } else { processDeviceListResponse(response); oauthCredentials.firstExecution = false; } } /** * Processes an incoming {@link DeviceListResponse}. * <p> */ private void processDeviceListResponse(final DeviceListResponse response) { // Prepare a map of all known device measurements final Map<String, Device> deviceMap = new HashMap<String, Device>(); final Map<String, Set<String>> deviceMeasurements = new HashMap<String, Set<String>>(); for (final Device device : response.getDevices()) { final String deviceId = device.getId(); deviceMap.put(deviceId, device); for (final String measurement : device.getMeasurements()) { if (!deviceMeasurements.containsKey(deviceId)) { deviceMeasurements.put(deviceId, new HashSet<String>()); } deviceMeasurements.get(deviceId).add(measurement); } } // Prepare a map of all known module measurements final Map<String, Module> moduleMap = new HashMap<String, Module>(); final Map<String, Set<String>> moduleMeasurements = new HashMap<String, Set<String>>(); for (final Module module : response.getModules()) { final String moduleId = module.getId(); moduleMap.put(moduleId, module); for (final String measurement : module.getMeasurements()) { if (!moduleMeasurements.containsKey(moduleId)) { moduleMeasurements.put(moduleId, new HashSet<String>()); } moduleMeasurements.get(moduleId).add(measurement); } } // Remove all configured items from the maps for (final NetatmoBindingProvider provider : this.providers) { for (final String itemName : provider.getItemNames()) { final String deviceId = provider.getDeviceId(itemName); final String moduleId = provider.getModuleId(itemName); final NetatmoMeasureType measureType = provider.getMeasureType(itemName); final Set<String> measurements; if (moduleId != null) { measurements = moduleMeasurements.get(moduleId); } else { measurements = deviceMeasurements.get(deviceId); } if (measurements != null) { measurements.remove(measureType.getMeasure()); } } } // Log all unconfigured measurements final StringBuilder message = new StringBuilder(); for (Entry<String, Set<String>> entry : deviceMeasurements.entrySet()) { final String deviceId = entry.getKey(); final Device device = deviceMap.get(deviceId); for (String measurement : entry.getValue()) { message.append("\t" + deviceId + "#" + measurement + " (" + device.getModuleName() + ")\n"); } } for (Entry<String, Set<String>> entry : moduleMeasurements.entrySet()) { final String moduleId = entry.getKey(); final Module module = moduleMap.get(moduleId); for (String measurement : entry.getValue()) { message.append("\t" + module.getMainDevice() + "#" + moduleId + "#" + measurement + " (" + module.getModuleName() + ")\n"); } } if (message.length() > 0) { message.insert(0,"The following Netatmo measurements are not yet configured:\n"); logger.info(message.toString()); } } /** * Creates the necessary requests to query the Netatmo API for all measures * that have a binding. One request can query all measures of a single * device or module. */ private Collection<MeasurementRequest> createMeasurementRequests() { final Map<String, MeasurementRequest> requests = new HashMap<String, MeasurementRequest>(); for (final NetatmoBindingProvider provider : this.providers) { for (final String itemName : provider.getItemNames()) { final String userid = provider.getUserid(itemName); final String deviceId = provider.getDeviceId(itemName); final String moduleId = provider.getModuleId(itemName); final NetatmoMeasureType measureType = provider.getMeasureType(itemName); final String requestKey = createKey(deviceId, moduleId); switch (measureType) { case TEMPERATURE: case CO2: case HUMIDITY: case NOISE: case PRESSURE: OAuthCredentials oauthCredentials = getOAuthCredentials(userid); if (oauthCredentials != null) { if (!requests.containsKey(requestKey)) { requests.put(requestKey, new MeasurementRequest(oauthCredentials.accessToken, deviceId, moduleId)); } requests.get(requestKey).addMeasure(measureType); break; } default: break; } } } return requests.values(); } private void processMeasurementResponse(final MeasurementRequest request, final MeasurementResponse response, Map<String, Map<String, BigDecimal>> deviceMeasureValueMap) { final List<BigDecimal> values = response.getBody().get(0).getValues().get(0); final Map<String, BigDecimal> valueMap = new HashMap<String, BigDecimal>(); int index = 0; for (final String measure : request.getMeasures()) { final BigDecimal value = values.get(index); valueMap.put(measure, value); index++; } deviceMeasureValueMap.put(request.getKey(), valueMap); } /** * Returns the cached {@link OAuthCredentials} for the given {@code userid}. * If their is no such cached {@link OAuthCredentials} element, the cache is * searched with the {@code DEFAULT_USER}. If there is still no cached element * found {@code NULL} is returned. * * @param userid the userid to find the {@link OAuthCredentials} * @return the cached {@link OAuthCredentials} or {@code NULL} */ private OAuthCredentials getOAuthCredentials(String userid) { if (credentialsCache.containsKey(userid)) { return credentialsCache.get(userid); } else { return credentialsCache.get(DEFAULT_USER_ID); } } /** * {@inheritDoc} */ @Override public void updated(final Dictionary<String, ?> config) throws ConfigurationException { if (config != null) { final String refreshIntervalString = (String) config.get(CONFIG_REFRESH); if (isNotBlank(refreshIntervalString)) { this.refreshInterval = Long.parseLong(refreshIntervalString); } Enumeration<String> configKeys = config.keys(); while (configKeys.hasMoreElements()) { String configKey = (String) configKeys.nextElement(); // the config-key enumeration contains additional keys that we // don't want to process here ... if (CONFIG_REFRESH.equals(configKey) || "service.pid".equals(configKey)) { continue; } String userid; String configKeyTail; if (configKey.contains(".")) { String[] keyElements = configKey.split("\\."); userid = keyElements[0]; configKeyTail = keyElements[1]; } else { userid = DEFAULT_USER_ID; configKeyTail = configKey; } OAuthCredentials credentials = credentialsCache.get(userid); if (credentials == null) { credentials = new OAuthCredentials(); credentialsCache.put(userid, credentials); } String value = (String) config.get(configKeyTail); if (CONFIG_CLIENT_ID.equals(configKeyTail)) { credentials.clientId = value; } else if (CONFIG_CLIENT_SECRET.equals(configKeyTail)) { credentials.clientSecret= value; } else if (CONFIG_REFRESH_TOKEN.equals(configKeyTail)) { credentials.refreshToken = value; } else { throw new ConfigurationException( configKey, "the given configKey '" + configKey + "' is unknown"); } } setProperlyConfigured(true); } } /** * This internal class holds the different crendentials necessary for the * OAuth2 flow to work. It also provides basic methods to refresh the access * token. * * @author Thomas.Eichstaedt-Engelen * @since 1.6.0 */ static class OAuthCredentials { /** * The client id to access the Netatmo API. Normally set in * <code>openhab.cfg</code>. * * @see <a href="http://dev.netatmo.com/doc/authentication/usercred">Client * Credentials</a> */ String clientId; /** * The client secret to access the Netatmo API. Normally set in * <code>openhab.cfg</code>. * * @see <a href="http://dev.netatmo.com/doc/authentication/usercred">Client * Credentials</a> */ String clientSecret; /** * The refresh token to access the Netatmo API. Normally set in * <code>openhab.cfg</code>. * * @see <a * href="http://dev.netatmo.com/doc/authentication/usercred">Client&nbsp;Credentials</a> * @see <a * href="http://dev.netatmo.com/doc/authentication/refreshtoken">Refresh&nbsp;Token</a> */ String refreshToken; /** * The access token to access the Netatmo API. Automatically renewed from * the API using the refresh token. * * @see <a * href="http://dev.netatmo.com/doc/authentication/refreshtoken">Refresh * Token</a> * @see #refreshAccessToken() */ String accessToken; boolean firstExecution = true; public boolean noAccessToken() { return this.accessToken == null; } public void refreshAccessToken() { logger.debug("Refreshing access token."); final RefreshTokenRequest request = new RefreshTokenRequest(this.clientId, this.clientSecret, this.refreshToken); logger.debug("Request: {}", request); final RefreshTokenResponse response = request.execute(); logger.debug("Response: {}", response); this.accessToken = response.getAccessToken(); deviceListRequest = new DeviceListRequest(this.accessToken); deviceListResponse = deviceListRequest.execute(); } } }
Modification of NetatmoBinding after merge of PR #1505
bundles/binding/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/NetatmoBinding.java
Modification of NetatmoBinding after merge of PR #1505
Java
epl-1.0
976946eb2e72ed2b9716cabe17c8c31e84424bef
0
Charling-Huang/birt,sguan-actuate/birt,rrimmana/birt-1,rrimmana/birt-1,Charling-Huang/birt,rrimmana/birt-1,Charling-Huang/birt,rrimmana/birt-1,sguan-actuate/birt,sguan-actuate/birt,Charling-Huang/birt,Charling-Huang/birt,rrimmana/birt-1,sguan-actuate/birt,sguan-actuate/birt
/******************************************************************************* * Copyright (c) 2004 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.report.designer.internal.ui.dialogs; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.Iterator; import java.util.List; import org.eclipse.birt.core.exception.BirtException; import org.eclipse.birt.core.script.functionservice.IScriptFunction; import org.eclipse.birt.core.script.functionservice.IScriptFunctionArgument; import org.eclipse.birt.core.script.functionservice.IScriptFunctionCategory; import org.eclipse.birt.core.script.functionservice.impl.FunctionProvider; import org.eclipse.birt.report.designer.core.model.SessionHandleAdapter; import org.eclipse.birt.report.designer.data.ui.aggregation.AggregationUtil; import org.eclipse.birt.report.designer.internal.ui.util.ExceptionHandler; import org.eclipse.birt.report.designer.internal.ui.util.IIndexInfo; import org.eclipse.birt.report.designer.internal.ui.views.memento.Memento; import org.eclipse.birt.report.designer.internal.ui.views.memento.MementoBuilder; import org.eclipse.birt.report.designer.internal.ui.views.memento.MementoElement; import org.eclipse.birt.report.designer.nls.Messages; import org.eclipse.birt.report.designer.ui.IReportGraphicConstants; import org.eclipse.birt.report.designer.ui.ReportPlatformUIImages; import org.eclipse.birt.report.designer.ui.dialogs.IExpressionProvider; import org.eclipse.birt.report.designer.ui.expressions.ExpressionFilter; import org.eclipse.birt.report.designer.ui.expressions.IContextExpressionProvider; import org.eclipse.birt.report.designer.ui.views.ElementAdapterManager; import org.eclipse.birt.report.designer.util.DEUtil; import org.eclipse.birt.report.model.api.DesignElementHandle; import org.eclipse.birt.report.model.api.ModuleHandle; import org.eclipse.birt.report.model.api.ParameterGroupHandle; import org.eclipse.birt.report.model.api.ParameterHandle; import org.eclipse.birt.report.model.api.ReportDesignHandle; import org.eclipse.birt.report.model.api.ReportElementHandle; import org.eclipse.birt.report.model.api.VariableElementHandle; import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants; import org.eclipse.birt.report.model.api.metadata.IArgumentInfo; import org.eclipse.birt.report.model.api.metadata.IArgumentInfoList; import org.eclipse.birt.report.model.api.metadata.IClassInfo; import org.eclipse.birt.report.model.api.metadata.ILocalizableInfo; import org.eclipse.birt.report.model.api.metadata.IMemberInfo; import org.eclipse.birt.report.model.api.metadata.IMethodInfo; import org.eclipse.birt.report.model.api.metadata.IPropertyDefn; import org.eclipse.jface.text.source.SourceViewer; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.DragSource; import org.eclipse.swt.dnd.DragSourceAdapter; import org.eclipse.swt.dnd.DragSourceEvent; import org.eclipse.swt.dnd.DropTarget; import org.eclipse.swt.dnd.DropTargetAdapter; import org.eclipse.swt.dnd.DropTargetEvent; import org.eclipse.swt.dnd.TextTransfer; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseTrackAdapter; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.TreeEvent; import org.eclipse.swt.events.TreeListener; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeItem; import org.eclipse.swt.widgets.Widget; import org.eclipse.ui.IMemento; import org.eclipse.ui.ISharedImages; import com.ibm.icu.text.Collator; /** * Deals with tree part of expression builder. Adds some mouse and DND support * to tree and corresponding source viewer. */ public class ExpressionTreeSupport implements ISelectionChangedListener { // Tree item icon images private static final Image IMAGE_FOLDER = ReportPlatformUIImages.getImage( ISharedImages.IMG_OBJ_FOLDER ); private static final Image IMAGE_OPERATOR = getIconImage( IReportGraphicConstants.ICON_EXPRESSION_OPERATOR ); private static final Image IMAGE_GOLBAL = getIconImage( IReportGraphicConstants.ICON_EXPRESSION_GLOBAL ); private static final Image IMAGE_METHOD = getIconImage( IReportGraphicConstants.ICON_EXPRESSION_METHOD ); private static final Image IMAGE_STATIC_METHOD = getIconImage( IReportGraphicConstants.ICON_EXPRESSION_STATIC_METHOD ); private static final Image IMAGE_CONSTRUCTOR = getIconImage( IReportGraphicConstants.ICON_EXPRESSION_CONSTRUCTOP ); private static final Image IMAGE_MEMBER = getIconImage( IReportGraphicConstants.ICON_EXPRESSION_MEMBER ); private static final Image IMAGE_STATIC_MEMBER = getIconImage( IReportGraphicConstants.ICON_EXPRESSION_STATIC_MEMBER ); /** Arithmetic operators and their descriptions */ private static final String[][] OPERATORS_ASSIGNMENT = new String[][]{ { "=", Messages.getString( "ExpressionProvider.Operator.Assign" ) //$NON-NLS-1$ //$NON-NLS-2$ }, { "+=", Messages.getString( "ExpressionProvider.Operator.AddTo" ) //$NON-NLS-1$ //$NON-NLS-2$ }, { "-=", Messages.getString( "ExpressionProvider.Operator.SubFrom" ) //$NON-NLS-1$ //$NON-NLS-2$ }, { "*=", Messages.getString( "ExpressionProvider.Operator.MultTo" ) //$NON-NLS-1$ //$NON-NLS-2$ }, { "/=", Messages.getString( "ExpressionProvider.Operator.DividingFrom" ) //$NON-NLS-1$ //$NON-NLS-2$ } }; /** Comparison operators and their descriptions */ private static final String[][] OPERATORS_COMPARISON = new String[][]{ { "==", Messages.getString( "ExpressionProvider.Operator.Equals" ) //$NON-NLS-1$ //$NON-NLS-2$ }, { "<", Messages.getString( "ExpressionProvider.Operator.Less" ) //$NON-NLS-1$ //$NON-NLS-2$ }, { "<=",//$NON-NLS-1$ Messages.getString( "ExpressionProvider.Operator.LessEqual" ) //$NON-NLS-1$ }, { "!=",//$NON-NLS-1$ Messages.getString( "ExpressionProvider.Operator.NotEqual" ) //$NON-NLS-1$ }, { ">", Messages.getString( "ExpressionProvider.Operator.Greater" ) //$NON-NLS-1$ //$NON-NLS-2$ }, { ">=",//$NON-NLS-1$ Messages.getString( "ExpressionProvider.Operator.GreaterEquals" ) //$NON-NLS-1$ } }; /** Computational operators and their descriptions */ private static final String[][] OPERATORS_COMPUTATIONAL = new String[][]{ { "+", Messages.getString( "ExpressionProvider.Operator.Add" ) //$NON-NLS-1$ //$NON-NLS-2$ }, { "-", Messages.getString( "ExpressionProvider.Operator.Sub" ) //$NON-NLS-1$ //$NON-NLS-2$ }, { "*", Messages.getString( "ExpressionProvider.Operator.Mult" ) //$NON-NLS-1$ //$NON-NLS-2$ }, { "/",//$NON-NLS-1$ Messages.getString( "ExpressionProvider.Operator.Divides" ) //$NON-NLS-1$ }, { "++X ",//$NON-NLS-1$ Messages.getString( "ExpressionProvider.Operator.Inc" ) //$NON-NLS-1$ }, { "X++ ", Messages.getString( "ExpressionProvider.Operator.ReturnInc" ) //$NON-NLS-1$ //$NON-NLS-2$ }, { "--X ", Messages.getString( "ExpressionProvider.Operator.Dec" ) //$NON-NLS-1$ //$NON-NLS-2$ }, { "X-- ", Messages.getString( "ExpressionProvider.Operator.ReturnDec" ) //$NON-NLS-1$ //$NON-NLS-2$ } }; /** Logical operators and their descriptions */ private static final String[][] OPERATORS_LOGICAL = new String[][]{ { "&&",//$NON-NLS-1$ Messages.getString( "ExpressionProvider.Operator.And" ) //$NON-NLS-1$ }, { "||",//$NON-NLS-1$ Messages.getString( "ExpressionProvider.Operator.Or" ) //$NON-NLS-1$ } }; private static final String TREE_ITEM_CONTEXT = Messages.getString( "ExpressionProvider.Category.Context" ); //$NON-NLS-1$ private static final String TREE_ITEM_OPERATORS = Messages.getString( "ExpressionProvider.Category.Operators" ); //$NON-NLS-1$ private static final String TREE_ITEM_BIRT_OBJECTS = Messages.getString( "ExpressionProvider.Category.BirtObjects" ); //$NON-NLS-1$ private static final String TREE_ITEM_PARAMETERS = Messages.getString( "ExpressionProvider.Category.Parameters" ); //$NON-NLS-1$ private static final String TREE_ITEM_NATIVE_OBJECTS = Messages.getString( "ExpressionProvider.Category.NativeObjects" ); //$NON-NLS-1$ private static final String TREE_ITEM_VARIABLES = Messages.getString( "ExpressionProvider.Category.Variables" ); //$NON-NLS-1$ private static final String TREE_ITEM_LOGICAL = Messages.getString( "ExpressionProvider.Operators.Logical" ); //$NON-NLS-1$ private static final String TREE_ITEM_COMPUTATIONAL = Messages.getString( "ExpressionProvider.Operators.Computational" ); //$NON-NLS-1$ private static final String TREE_ITEM_COMPARISON = Messages.getString( "ExpressionProvider.Operators.Comparison" ); //$NON-NLS-1$ private static final String TREE_ITEM_ASSIGNMENT = Messages.getString( "ExpressionProvider.Operators.Assignment" ); //$NON-NLS-1$ /** Tool tip key of tree item data */ protected static final String ITEM_DATA_KEY_TOOLTIP = "TOOL_TIP"; //$NON-NLS-1$ /** * Text key of tree item data, this data is the text string to be inserted * into the text area */ protected static final String ITEM_DATA_KEY_TEXT = "TEXT"; //$NON-NLS-1$ protected static final String ITEM_DATA_KEY_ENABLED = "ENABLED"; //$NON-NLS-1$ private static final String OBJECTS_TYPE_NATIVE = "native";//$NON-NLS-1$ private static final String OBJECTS_TYPE_BIRT = "birt";//$NON-NLS-1$ private SourceViewer expressionViewer; private Tree tree; private DropTarget dropTarget; private DropTargetAdapter dropTargetAdapter; private Object currentEditObject; private String currentMethodName; private TreeItem contextItem, parametersItem, nativeObejctsItem, birtObjectsItem, operatorsItem, variablesItem; private List<TreeItem> dynamicItems; private List staticFilters; private MementoBuilder builder = new MementoBuilder( ); private Memento viewerMemento; public ExpressionTreeSupport( ) { super( ); } /** * Creates all expression trees in default order */ public void createDefaultExpressionTree( ) { createFilteredExpressionTree( null ); } /** * Creates selected expression trees with given filter list. * * @param filterList * list of filters */ public void createFilteredExpressionTree( List filterList ) { this.staticFilters = filterList; createExpressionTree( ); } public String getElementType( ) { if ( currentEditObject == null ) return null; String displayName = ( (DesignElementHandle) currentEditObject ).getDefn( ) .getDisplayName( ); if ( displayName == null || "".equals( displayName ) )//$NON-NLS-1$ { displayName = ( (DesignElementHandle) currentEditObject ).getDefn( ) .getName( ); } return displayName; } private void createExpressionTree( ) { if ( tree == null || tree.isDisposed( ) ) { return; } List<IExpressionProvider> dynamicContextProviders = null; List<ExpressionFilter> dynamicFilters = null; if ( currentEditObject != null && currentMethodName != null ) { if ( viewerMemento != null ) { IMemento memento = viewerMemento.getChild( getElementType( ) ); if ( memento == null ) { Memento elementMemento = (Memento) viewerMemento.createChild( getElementType( ), MementoElement.Type_Element ); elementMemento.getMementoElement( ) .setValue( getElementType( ) ); } } Object[] adapters = ElementAdapterManager.getAdapters( currentEditObject, IContextExpressionProvider.class ); if ( adapters != null ) { for ( Object adapt : adapters ) { IContextExpressionProvider contextProvider = (IContextExpressionProvider) adapt; if ( contextProvider != null ) { IExpressionProvider exprProvider = contextProvider.getExpressionProvider( currentMethodName ); if ( exprProvider != null ) { if ( dynamicContextProviders == null ) { dynamicContextProviders = new ArrayList<IExpressionProvider>( ); } dynamicContextProviders.add( exprProvider ); } ExpressionFilter exprFilter = contextProvider.getExpressionFilter( currentMethodName ); if ( exprFilter != null ) { if ( dynamicFilters == null ) { dynamicFilters = new ArrayList<ExpressionFilter>( ); } dynamicFilters.add( exprFilter ); } } } } } List<ExpressionFilter> filters = null; if ( staticFilters != null && dynamicFilters != null ) { filters = new ArrayList<ExpressionFilter>( ); filters.addAll( staticFilters ); filters.addAll( dynamicFilters ); } else if ( staticFilters != null ) { filters = staticFilters; } else if ( dynamicFilters != null ) { filters = dynamicFilters; } // flag to check if some bulit-in categories need be removed boolean hasContext = false; boolean hasParameters = false; boolean hasVariables = false; boolean hasNativeObjects = false; boolean hasBirtObjects = false; boolean hasOperators = false; // check and create built-in categories if ( filter( ExpressionFilter.CATEGORY, ExpressionFilter.CATEGORY_CONTEXT, filters ) ) { hasContext = true; clearSubTreeItem( contextItem ); createContextCatagory( ); } if ( filter( ExpressionFilter.CATEGORY, ExpressionFilter.CATEGORY_PARAMETERS, filters ) ) { hasParameters = true; if ( parametersItem == null || parametersItem.isDisposed( ) ) { // only create once createParamtersCategory( ); } } if ( filter( ExpressionFilter.CATEGORY, ExpressionFilter.CATEGORY_VARIABLES, filters ) ) { hasVariables = true; createVariablesCategory( ); } if ( filter( ExpressionFilter.CATEGORY, ExpressionFilter.CATEGORY_NATIVE_OBJECTS, filters ) ) { hasNativeObjects = true; if ( nativeObejctsItem == null || nativeObejctsItem.isDisposed( ) ) { // only create once createNativeObjectsCategory( ); } } if ( filter( ExpressionFilter.CATEGORY, ExpressionFilter.CATEGORY_BIRT_OBJECTS, filters ) ) { hasBirtObjects = true; if ( birtObjectsItem == null || birtObjectsItem.isDisposed( ) ) { // only create once createBirtObjectsCategory( ); } } if ( filter( ExpressionFilter.CATEGORY, ExpressionFilter.CATEGORY_OPERATORS, filters ) ) { hasOperators = true; if ( operatorsItem == null || operatorsItem.isDisposed( ) ) { // only create once createOperatorsCategory( ); } } if ( !hasContext ) { clearTreeItem( contextItem ); } if ( !hasParameters ) { clearTreeItem( parametersItem ); } if ( !hasVariables ) { clearTreeItem( variablesItem ); } if ( !hasNativeObjects ) { clearTreeItem( nativeObejctsItem ); } if ( !hasBirtObjects ) { clearTreeItem( birtObjectsItem ); } if ( !hasOperators ) { clearTreeItem( operatorsItem ); } clearDynamicItems( ); if ( dynamicContextProviders != null ) { updateDynamicItems( dynamicContextProviders ); } restoreSelection( ); } protected void saveSelection( TreeItem selection ) { Memento memento = ( (Memento) viewerMemento.getChild( getElementType( ) ) ); if (memento == null) { return; } MementoElement[] selectPath = createItemPath( selection ); memento.getMementoElement( ).setAttribute( MementoElement.ATTRIBUTE_SELECTED, selectPath ); } protected MementoElement[] createItemPath( TreeItem item ) { MementoElement tempMemento = null; while ( item.getParentItem( ) != null ) { TreeItem parent = item.getParentItem( ); for ( int i = 0; i < parent.getItemCount( ); i++ ) { if ( parent.getItem( i ) == item ) { MementoElement memento = new MementoElement( item.getText( ), item.getText( ), MementoElement.Type_Element ); if ( tempMemento != null ) memento.addChild( tempMemento ); tempMemento = memento; item = parent; break; } } } MementoElement memento = new MementoElement( item.getText( ), item.getText( ), MementoElement.Type_Element ); if ( tempMemento != null ) memento.addChild( tempMemento ); return getNodePath( memento ); } public MementoElement[] getNodePath( MementoElement node ) { ArrayList pathList = new ArrayList( ); MementoElement memento = node; pathList.add( node );// add root while ( memento.getChildren( ).length > 0 ) { pathList.add( memento.getChild( 0 ) ); memento = (MementoElement) memento.getChild( 0 ); } MementoElement[] paths = new MementoElement[pathList.size( )]; pathList.toArray( paths ); return paths; } private void restoreSelection( ) { Memento memento = ( (Memento) viewerMemento.getChild( getElementType( ) ) ); if ( memento == null ) return; expandTreeFromMemento( memento ); Object obj = memento.getMementoElement( ) .getAttribute( MementoElement.ATTRIBUTE_SELECTED ); if ( obj != null ) { for ( int i = 0; i < tree.getItemCount( ); i++ ) { restoreSelectedMemento( tree.getItem( i ), (MementoElement[]) obj ); } } } private void restoreSelectedMemento( TreeItem root, MementoElement[] selectedPath ) { if ( selectedPath.length <= 0 ) return; for ( int i = 0; i < selectedPath.length; i++ ) { MementoElement element = selectedPath[i]; if ( root.getText( ).equals( element.getValue( ) ) ) { continue; } boolean flag = false; for ( int j = 0; j < root.getItemCount( ); j++ ) { if ( root.getItem( j ).getText( ).equals( element.getValue( ) ) ) { root = root.getItem( j ); flag = true; break; } } if ( !flag ) return; } tree.setSelection( root ); } /** * Filters the tree name, given the filter list. * * @param treeName * the tree name to be filtered. * @param filters * the filter list. * @return true if the tree name passes the filter list. */ private boolean filter( Object parent, Object child, List<ExpressionFilter> filters ) { if ( filters == null ) { return true; } for ( ExpressionFilter ft : filters ) { if ( ft != null && !ft.select( parent, child ) ) { return false; } } return true; } /** * Create operators band.Must set Tree before execution. * */ protected void createOperatorsCategory( ) { assert tree != null; int idx = getIndex( birtObjectsItem, nativeObejctsItem, parametersItem, contextItem ); operatorsItem = createTopTreeItem( tree, TREE_ITEM_OPERATORS, idx ); TreeItem subItem = createSubFolderItem( operatorsItem, TREE_ITEM_ASSIGNMENT ); createSubTreeItems( subItem, OPERATORS_ASSIGNMENT, IMAGE_OPERATOR ); subItem = createSubFolderItem( operatorsItem, TREE_ITEM_COMPARISON ); createSubTreeItems( subItem, OPERATORS_COMPARISON, IMAGE_OPERATOR ); subItem = createSubFolderItem( operatorsItem, TREE_ITEM_COMPUTATIONAL ); createSubTreeItems( subItem, OPERATORS_COMPUTATIONAL, IMAGE_OPERATOR ); subItem = createSubFolderItem( operatorsItem, TREE_ITEM_LOGICAL ); createSubTreeItems( subItem, OPERATORS_LOGICAL, IMAGE_OPERATOR ); } /** * Create native object band.Must set Tree before execution. * */ protected void createNativeObjectsCategory( ) { assert tree != null; int idx = getIndex( parametersItem, contextItem ); nativeObejctsItem = createTopTreeItem( tree, TREE_ITEM_NATIVE_OBJECTS, idx ); createObjects( nativeObejctsItem, OBJECTS_TYPE_NATIVE ); } /** * Create parameters band. Must set Tree before execution. * */ protected void createParamtersCategory( ) { assert tree != null; int idx = getIndex( contextItem ); parametersItem = createTopTreeItem( tree, TREE_ITEM_PARAMETERS, idx ); buildParameterTree( ); } private void buildParameterTree( ) { ModuleHandle module = SessionHandleAdapter.getInstance( ) .getReportDesignHandle( ); if ( module == null ) { return; } for ( Iterator iterator = module.getParameters( ).iterator( ); iterator.hasNext( ); ) { ReportElementHandle handle = (ReportElementHandle) iterator.next( ); if ( handle instanceof ParameterHandle ) { createSubTreeItem( parametersItem, DEUtil.getDisplayLabel( handle, false ), ReportPlatformUIImages.getImage( handle ), DEUtil.getExpression( handle ), ( (ParameterHandle) handle ).getHelpText( ), true ); } else if ( handle instanceof ParameterGroupHandle ) { TreeItem groupItem = createSubTreeItem( parametersItem, DEUtil.getDisplayLabel( handle, false ), ReportPlatformUIImages.getImage( handle ), true ); for ( Iterator itor = ( (ParameterGroupHandle) handle ).getParameters( ) .iterator( ); itor.hasNext( ); ) { ParameterHandle parameter = (ParameterHandle) itor.next( ); createSubTreeItem( groupItem, parameter.getDisplayLabel( ), ReportPlatformUIImages.getImage( handle ), DEUtil.getExpression( parameter ), parameter.getDisplayLabel( ), true ); } } } } protected void createVariablesCategory( ) { if ( variablesItem == null || variablesItem.isDisposed( ) ) { int idx = getIndex( contextItem ); variablesItem = createTopTreeItem( tree, TREE_ITEM_VARIABLES, idx ); } buildVariableTree( ); } private void buildVariableTree( ) { clearSubTreeItem( variablesItem ); ModuleHandle handle = SessionHandleAdapter.getInstance( ) .getReportDesignHandle( ); if ( handle instanceof ReportDesignHandle ) { for ( VariableElementHandle variableHandle : ( (ReportDesignHandle) handle ).getPageVariables( ) ) { if ( currentMethodName != null && DesignChoiceConstants.VARIABLE_TYPE_PAGE.equals( variableHandle.getType( ) ) && !( currentMethodName.equals( "onPageStart" ) || currentMethodName.equals( "onPageEnd" ) || currentMethodName.equals( "onRender" ) ) ) continue; createSubTreeItem( variablesItem, DEUtil.getDisplayLabel( variableHandle, false ), ReportPlatformUIImages.getImage( variableHandle ), DEUtil.getExpression( variableHandle ), variableHandle.getDisplayLabel( ), true ); } } restoreSelection( ); } /** * Creates birt object tree. Must set Tree before execution. * */ protected void createBirtObjectsCategory( ) { assert tree != null; int idx = getIndex( nativeObejctsItem, parametersItem, contextItem ); birtObjectsItem = createTopTreeItem( tree, TREE_ITEM_BIRT_OBJECTS, idx ); createObjects( birtObjectsItem, OBJECTS_TYPE_BIRT ); } // /** // * Creates a top tree item // * // * @param parent // * @param text // * @return tree item // */ // private TreeItem createTopTreeItem( Tree parent, String text ) // { // TreeItem item = new TreeItem( parent, SWT.NONE ); // item.setText( text ); // item.setImage( IMAGE_FOLDER ); // item.setData( ITEM_DATA_KEY_TOOLTIP, "" );//$NON-NLS-1$ // return item; // } private TreeItem createTopTreeItem( Tree parent, String text, int index ) { TreeItem item = new TreeItem( parent, SWT.NONE, index ); item.setText( text ); item.setImage( IMAGE_FOLDER ); item.setData( ITEM_DATA_KEY_TOOLTIP, "" );//$NON-NLS-1$ return item; } private TreeItem createSubTreeItem( TreeItem parent, String text, Image image, boolean isEnabled ) { return createSubTreeItem( parent, text, image, null, text, isEnabled ); } private TreeItem createSubTreeItem( TreeItem parent, String text, Image image, String textData, String toolTip, boolean isEnabled ) { TreeItem item = new TreeItem( parent, SWT.NONE ); item.setText( text ); if ( image != null ) { item.setImage( image ); } item.setData( ITEM_DATA_KEY_TOOLTIP, toolTip ); item.setData( ITEM_DATA_KEY_TEXT, textData ); item.setData( ITEM_DATA_KEY_ENABLED, Boolean.valueOf( isEnabled ) ); return item; } private TreeItem createSubFolderItem( TreeItem parent, String text ) { return createSubTreeItem( parent, text, IMAGE_FOLDER, true ); } private TreeItem createSubFolderItem( TreeItem parent, IClassInfo classInfo ) { return createSubTreeItem( parent, classInfo.getDisplayName( ), IMAGE_FOLDER, null, classInfo.getToolTip( ), true ); } private TreeItem createSubFolderItem( TreeItem parent, IScriptFunctionCategory category ) { String categoreName = getCategoryDisplayName( category ); return createSubTreeItem( parent, categoreName, IMAGE_FOLDER, null, category.getDescription( ), true ); } private String getCategoryDisplayName( IScriptFunctionCategory category ) { return category.getName( ) == null ? Messages.getString( "ExpressionTreeSupport.Category.Global" ) //$NON-NLS-1$ : category.getName( ); } private void createSubTreeItems( TreeItem parent, String[][] texts, Image image ) { for ( int i = 0; i < texts.length; i++ ) { createSubTreeItem( parent, texts[i][0], image, texts[i][0], texts[i][1], true ); } } /** * Adds mouse track listener.Must set Tree before execution. * */ public void addMouseTrackListener( ) { assert tree != null; tree.addMouseTrackListener( new MouseTrackAdapter( ) { public void mouseHover( MouseEvent event ) { Widget widget = event.widget; if ( widget == tree ) { Point pt = new Point( event.x, event.y ); TreeItem item = tree.getItem( pt ); if ( item == null ) tree.setToolTipText( "" );//$NON-NLS-1$ else { String text = (String) item.getData( ITEM_DATA_KEY_TOOLTIP ); tree.setToolTipText( text ); } } } } ); } /** * Add double click behaviour. Must set Tree before execution. * */ public void addMouseListener( ) { assert tree != null; tree.addMouseListener( new MouseAdapter( ) { public void mouseDoubleClick( MouseEvent event ) { TreeItem[] selection = getTreeSelection( ); if ( selection == null || selection.length <= 0 ) return; TreeItem item = selection[0]; if ( item != null ) { Object obj = item.getData( ITEM_DATA_KEY_TEXT ); Boolean isEnabled = (Boolean) item.getData( ITEM_DATA_KEY_ENABLED ); if ( obj != null && isEnabled.booleanValue( ) ) { String text = (String) obj; insertText( text ); } } } } ); } protected TreeItem[] getTreeSelection( ) { return tree.getSelection( ); } /** * Adds drag support to tree..Must set tree before execution. */ public void addDragSupportToTree( ) { assert tree != null; DragSource dragSource = new DragSource( tree, DND.DROP_COPY | DND.DROP_MOVE ); dragSource.setTransfer( new Transfer[]{ TextTransfer.getInstance( ) } ); dragSource.addDragListener( new DragSourceAdapter( ) { public void dragStart( DragSourceEvent event ) { TreeItem[] selection = tree.getSelection( ); if ( selection.length <= 0 || selection[0].getData( ITEM_DATA_KEY_TEXT ) == null || !( (Boolean) selection[0].getData( ITEM_DATA_KEY_ENABLED ) ).booleanValue( ) ) { event.doit = false; return; } } public void dragSetData( DragSourceEvent event ) { if ( TextTransfer.getInstance( ) .isSupportedType( event.dataType ) ) { TreeItem[] selection = tree.getSelection( ); if ( selection.length > 0 ) { event.data = selection[0].getData( ITEM_DATA_KEY_TEXT ); } } } } ); } /** * Insert a text string into the text area * * @param text */ protected void insertText( String text ) { StyledText textWidget = expressionViewer.getTextWidget( ); if ( !textWidget.isEnabled( ) ) { return; } int selectionStart = textWidget.getSelection( ).x; if ( text.equalsIgnoreCase( "x++" ) ) //$NON-NLS-1$ { text = textWidget.getSelectionText( ) + "++";//$NON-NLS-1$ } else if ( text.equalsIgnoreCase( "x--" ) )//$NON-NLS-1$ { text = textWidget.getSelectionText( ) + "--";//$NON-NLS-1$ } else if ( text.equalsIgnoreCase( "++x" ) )//$NON-NLS-1$ { text = "++" + textWidget.getSelectionText( );//$NON-NLS-1$ } else if ( text.equalsIgnoreCase( "--x" ) )//$NON-NLS-1$ { text = "--" + textWidget.getSelectionText( );//$NON-NLS-1$ } textWidget.insert( text ); textWidget.setSelection( selectionStart + text.length( ) ); textWidget.setFocus( ); if ( text.endsWith( "()" ) ) //$NON-NLS-1$ { textWidget.setCaretOffset( textWidget.getCaretOffset( ) - 1 ); // Move } } /** * Adds drop support to viewer.Must set viewer before execution. * */ public void addDropSupportToViewer( ) { assert expressionViewer != null; if ( dropTarget == null || dropTarget.isDisposed( ) ) { final StyledText text = expressionViewer.getTextWidget( ); // Doesn't add again if a drop target has been created in the // viewer. if ( text.getData( "DropTarget" ) != null ) //$NON-NLS-1$ { return; } dropTarget = new DropTarget( text, DND.DROP_COPY | DND.DROP_DEFAULT ); dropTarget.setTransfer( new Transfer[]{ TextTransfer.getInstance( ) } ); dropTargetAdapter = new DropTargetAdapter( ) { public void dragEnter( DropTargetEvent event ) { text.setFocus( ); if ( event.detail == DND.DROP_DEFAULT ) event.detail = DND.DROP_COPY; if ( event.detail != DND.DROP_COPY ) event.detail = DND.DROP_NONE; } public void dragOver( DropTargetEvent event ) { event.feedback = DND.FEEDBACK_SCROLL | DND.FEEDBACK_INSERT_BEFORE; } public void dragOperationChanged( DropTargetEvent event ) { dragEnter( event ); } public void drop( DropTargetEvent event ) { if ( event.data instanceof String ) insertText( (String) event.data ); } }; dropTarget.addDropListener( dropTargetAdapter ); } } public void removeDropSupportToViewer( ) { if ( dropTarget != null && !dropTarget.isDisposed( ) ) { if ( dropTargetAdapter != null ) { dropTarget.removeDropListener( dropTargetAdapter ); dropTargetAdapter = null; } dropTarget.dispose( ); dropTarget = null; } } /** * Sets the tree model. * * @param tree */ public void setTree( final Tree tree ) { this.tree = tree; if ( ( viewerMemento = (Memento) builder.getRootMemento( ) .getChild( "ExpressionTreeSupport" ) ) == null ) { viewerMemento = (Memento) builder.getRootMemento( ) .createChild( "ExpressionTreeSupport", MementoElement.Type_Viewer ); } SelectionAdapter treeSelectionListener = new SelectionAdapter( ) { public void widgetDefaultSelected( SelectionEvent e ) { saveSelection( (TreeItem) e.item ); } }; tree.addSelectionListener( treeSelectionListener ); tree.addMouseListener( new MouseAdapter( ) { public void mouseDown( MouseEvent event ) { // only activate if there is a cell editor Point pt = new Point( event.x, event.y ); TreeItem item = tree.getItem( pt ); if ( item != null ) { saveSelection( item ); } } } ); tree.addKeyListener( new KeyAdapter( ) { public void keyReleased( KeyEvent e ) { if ( tree.getSelectionCount( ) > 0 ) saveSelection( tree.getSelection( )[0] ); } } ); TreeListener treeListener = new TreeListener( ) { public void treeCollapsed( TreeEvent e ) { if ( e.item instanceof TreeItem ) { TreeItem item = (TreeItem) e.item; MementoElement[] path = createItemPath( item ); removeNode( ( (Memento) viewerMemento.getChild( getElementType( ) ) ), path ); getTree( ).setSelection( item ); saveSelection( item ); } } public void treeExpanded( TreeEvent e ) { if ( e.item instanceof TreeItem ) { TreeItem item = (TreeItem) e.item; MementoElement[] path = createItemPath( item ); addNode( ( (Memento) viewerMemento.getChild( getElementType( ) ) ), path ); getTree( ).setSelection( item ); saveSelection( item ); } } }; tree.addTreeListener( treeListener ); } public boolean addNode( Memento element, MementoElement[] nodePath ) { if (element == null) { return false; } if ( nodePath != null && nodePath.length > 0 ) { MementoElement memento = element.getMementoElement( ); // if ( !memento.equals( nodePath[0] ) ) // return false; for ( int i = 0; i < nodePath.length; i++ ) { MementoElement child = getChild( memento, nodePath[i] ); if ( child != null ) memento = child; else { memento.addChild( nodePath[i] ); return true; } } return true; } return false; } public boolean removeNode( Memento element, MementoElement[] nodePath ) { if(element == null) { return false; } if ( nodePath != null && nodePath.length > 0 ) { MementoElement memento = element.getMementoElement( ); // if ( !memento.equals( nodePath[0] ) ) // return false; for ( int i = 0; i < nodePath.length; i++ ) { MementoElement child = getChild( memento, nodePath[i] ); if ( child != null ) memento = child; else return false; } memento.getParent( ).removeChild( memento ); return true; } return false; } private void expandTreeFromMemento( Memento memento ) { if ( tree.getItemCount( ) == 0 || memento == null ) return; for ( int i = 0; i < tree.getItemCount( ); i++ ) { TreeItem root = tree.getItem( i ); for ( int j = 0; j < memento.getMementoElement( ).getChildren( ).length; j++ ) { MementoElement child = memento.getMementoElement( ) .getChildren( )[j]; restoreExpandedMemento( root, child ); } } } private void restoreExpandedMemento( TreeItem root, MementoElement memento ) { if ( memento.getKey( ).equals( root.getText( ) ) ) { if ( root.getItemCount( ) > 0 ) { if ( !root.getExpanded( ) ) root.setExpanded( true ); MementoElement[] children = memento.getChildren( ); for ( int i = 0; i < children.length; i++ ) { MementoElement child = children[i]; String key = child.getValue( ).toString( ); for ( int j = 0; j < root.getItemCount( ); j++ ) { TreeItem item = root.getItem( j ); if ( item.getText( ).equals( key ) ) { restoreExpandedMemento( item, child ); break; } } } } } } private MementoElement getChild( MementoElement parent, MementoElement key ) { MementoElement[] children = parent.getChildren( ); for ( int i = 0; i < children.length; i++ ) { if ( children[i].equals( key ) ) return children[i]; } return null; }; protected Tree getTree( ) { return tree; } /** * Sets the viewer to use. * * @param expressionViewer */ public void setExpressionViewer( SourceViewer expressionViewer ) { this.expressionViewer = expressionViewer; } protected SourceViewer getExpressionViewer( ) { return expressionViewer; } /** * Gets an icon image by the key in plugin.properties * * @param id * @return image */ private static Image getIconImage( String id ) { return ReportPlatformUIImages.getImage( id ); } private void createObjects( TreeItem topItem, String objectType ) { for ( Iterator itor = DEUtil.getClasses( ).iterator( ); itor.hasNext( ); ) { IClassInfo classInfo = (IClassInfo) itor.next( ); if ( classInfo.isNative( ) && OBJECTS_TYPE_BIRT.equals( objectType ) || !classInfo.isNative( ) && OBJECTS_TYPE_NATIVE.equals( objectType ) || classInfo.getName( ).equals( "Total" ) ) //$NON-NLS-1$ { continue; } TreeItem subItem = createSubFolderItem( topItem, classInfo ); Image globalImage = null; if ( isGlobal( classInfo.getName( ) ) ) { globalImage = IMAGE_GOLBAL; } ArrayList<Object> childrenList = new ArrayList<Object>( ); IMemberInfo[] members = (IMemberInfo[]) DEUtil.getMembers( classInfo ) .toArray( new IMemberInfo[0] ); for ( int i = 0; i < members.length; i++ ) { childrenList.add( new ILocalizableInfo[]{ classInfo, members[i] } ); } List methodList = new ArrayList( ); methodList.addAll( DEUtil.getMethods( classInfo, true ) ); methodList.addAll( AggregationUtil.getMethods( classInfo ) ); IMethodInfo[] methods = (IMethodInfo[]) methodList.toArray( new IMethodInfo[0] ); for ( int i = 0; i < methods.length; i++ ) { IMethodInfo mi = methods[i]; processMethods( classInfo, mi, childrenList ); } ILocalizableInfo[][] children = childrenList.toArray( new ILocalizableInfo[0][] ); sortLocalizableInfo( children ); for ( int i = 0; i < children.length; i++ ) { Object obj = children[i]; createSubTreeItem( subItem, getDisplayText( obj ), globalImage == null ? getImage( obj ) : globalImage, getInsertText( obj ), getTooltipText( obj ), true ); } } if ( OBJECTS_TYPE_BIRT.equals( objectType ) ) { try { IScriptFunctionCategory[] categorys = FunctionProvider.getCategories( ); Arrays.sort( categorys, new Comparator<IScriptFunctionCategory>( ) { public int compare( IScriptFunctionCategory o1, IScriptFunctionCategory o2 ) { return getCategoryDisplayName( o1 ).compareTo( getCategoryDisplayName( o2 ) ); } } ); if ( categorys != null ) { for ( int i = 0; i < categorys.length; i++ ) { TreeItem subItem = createSubFolderItem( topItem, categorys[i] ); IScriptFunction[] functions = categorys[i].getFunctions( ); Arrays.sort( functions, new Comparator<IScriptFunction>( ) { public int compare( IScriptFunction o1, IScriptFunction o2 ) { return getFunctionDisplayText( o1 ).compareTo( getFunctionDisplayText( o2 ) ); } } ); if ( functions != null ) { for ( int j = 0; j < functions.length; j++ ) { Image image = null; if ( functions[j].isStatic( ) ) { image = IMAGE_STATIC_METHOD; } else { image = IMAGE_METHOD; } createSubTreeItem( subItem, getFunctionDisplayText( functions[j] ), image, getFunctionExpression( categorys[i], functions[j] ), functions[j].getDescription( ), true ); } } } } } catch ( BirtException e ) { ExceptionHandler.handle( e ); } } } private void sortLocalizableInfo( ILocalizableInfo[][] infos ) { Arrays.sort( infos, new Comparator<ILocalizableInfo[]>( ) { private int computeWeight( ILocalizableInfo obj ) { if ( obj instanceof IMemberInfo ) { return ( (IMemberInfo) obj ).isStatic( ) ? 0 : 2; } else if ( obj instanceof IMethodInfo ) { if ( ( (IMethodInfo) obj ).isConstructor( ) ) { return 3; } return ( (IMethodInfo) obj ).isStatic( ) ? 1 : 4; } return 4; } public int compare( ILocalizableInfo[] o1, ILocalizableInfo[] o2 ) { ILocalizableInfo info1 = o1[1]; ILocalizableInfo info2 = o2[1]; int w1 = computeWeight( info1 ); int w2 = computeWeight( info2 ); if ( w1 != w2 ) { return w1 < w2 ? -1 : 1; } return Collator.getInstance( ).compare( getDisplayText( o1 ), getDisplayText( o2 ) ); } } ); } private Image getImage( Object element ) { if ( element instanceof ILocalizableInfo[] ) { ILocalizableInfo info = ( (ILocalizableInfo[]) element )[1]; if ( info instanceof IMethodInfo ) { if ( ( (IMethodInfo) info ).isStatic( ) ) { return IMAGE_STATIC_METHOD; } else if ( ( (IMethodInfo) info ).isConstructor( ) ) { return IMAGE_CONSTRUCTOR; } return IMAGE_METHOD; } if ( info instanceof IMemberInfo ) { if ( ( (IMemberInfo) info ).isStatic( ) ) { return IMAGE_STATIC_MEMBER; } return IMAGE_MEMBER; } } return null; } private String getInsertText( Object element ) { if ( element instanceof VariableElementHandle ) { return ( (VariableElementHandle) element ).getVariableName( ); } if ( element instanceof ILocalizableInfo[] ) { IClassInfo classInfo = (IClassInfo) ( (ILocalizableInfo[]) element )[0]; ILocalizableInfo info = ( (ILocalizableInfo[]) element )[1]; StringBuffer insertText = new StringBuffer( ); if ( info instanceof IMemberInfo ) { IMemberInfo memberInfo = (IMemberInfo) info; if ( memberInfo.isStatic( ) ) { insertText.append( classInfo.getName( ) + "." ); //$NON-NLS-1$ } insertText.append( memberInfo.getName( ) ); } else if ( info instanceof IMethodInfo ) { IMethodInfo methodInfo = (IMethodInfo) info; if ( methodInfo.isStatic( ) ) { insertText.append( classInfo.getName( ) + "." ); //$NON-NLS-1$ } else if ( methodInfo.isConstructor( ) ) { insertText.append( "new " ); //$NON-NLS-1$ } insertText.append( methodInfo.getName( ) ); insertText.append( "()" ); //$NON-NLS-1$ } return insertText.toString( ); } return null; } private String getTooltipText( Object element ) { if ( element instanceof ILocalizableInfo[] ) { ILocalizableInfo info = ( (ILocalizableInfo[]) element )[1]; String tooltip = null; if ( info instanceof IMemberInfo ) { tooltip = ( (IMemberInfo) info ).getToolTip( ); } else if ( info instanceof IMethodInfo ) { tooltip = ( (IMethodInfo) info ).getToolTip( ); } return tooltip == null ? "" : tooltip; //$NON-NLS-1$ } return null; } protected String getDisplayText( Object element ) { if ( element instanceof ILocalizableInfo[] ) { // including class info,method info and member info ILocalizableInfo info = ( (ILocalizableInfo[]) element )[1]; StringBuffer displayText = new StringBuffer( info.getName( ) ); if ( info instanceof IMethodInfo ) { IMethodInfo method = (IMethodInfo) info; displayText.append( "(" ); //$NON-NLS-1$ int argIndex = ( ( (ILocalizableInfo[]) element ).length > 2 ) ? ( ( (IIndexInfo) ( (ILocalizableInfo[]) element )[2] ).getIndex( ) ) : 0; int idx = -1; Iterator argumentListIter = method.argumentListIterator( ); while ( argumentListIter.hasNext( ) ) { IArgumentInfoList arguments = (IArgumentInfoList) argumentListIter.next( ); idx++; if ( idx < argIndex ) { continue; } boolean isFirst = true; for ( Iterator iter = arguments.argumentsIterator( ); iter.hasNext( ); ) { IArgumentInfo argInfo = (IArgumentInfo) iter.next( ); if ( !isFirst ) { displayText.append( ", " ); //$NON-NLS-1$ } isFirst = false; if ( argInfo.getType( ) != null && argInfo.getType( ).length( ) > 0 ) { displayText.append( argInfo.getType( ) + " " //$NON-NLS-1$ + argInfo.getName( ) ); } else displayText.append( argInfo.getName( ) ); } break; } displayText.append( ")" ); //$NON-NLS-1$ if ( !method.isConstructor( ) ) { displayText.append( " : " ); //$NON-NLS-1$ String returnType = method.getReturnType( ); if ( returnType == null || returnType.length( ) == 0 ) { returnType = "void"; //$NON-NLS-1$ } displayText.append( returnType ); } } else if ( info instanceof IMemberInfo ) { String dataType = ( (IMemberInfo) info ).getDataType( ); if ( dataType != null && dataType.length( ) > 0 ) { displayText.append( " : " ); //$NON-NLS-1$ displayText.append( dataType ); } } return displayText.toString( ); } return null; } private boolean isGlobal( String name ) { // TODO global validation is hard coded return name != null && name.startsWith( "Global" ); //$NON-NLS-1$ } private String getFunctionDisplayText( IScriptFunction function ) { String functionStart = function.isConstructor( ) ? "new " : ""; //$NON-NLS-1$//$NON-NLS-2$ StringBuffer displayText = new StringBuffer( functionStart ); displayText.append( function.getName( ) ); IScriptFunctionArgument[] arguments = function.getArguments( ); displayText.append( "(" ); //$NON-NLS-1$ if ( arguments != null ) { for ( int i = 0; i < arguments.length; i++ ) { displayText.append( arguments[i].getName( ) ); if ( i < arguments.length - 1 ) displayText.append( ", " );//$NON-NLS-1$ } } displayText.append( ")" ); //$NON-NLS-1$ return displayText.toString( ); } private String getFunctionExpression( IScriptFunctionCategory category, IScriptFunction function ) { String functionStart = function.isConstructor( ) ? "new " : ""; //$NON-NLS-1$//$NON-NLS-2$ StringBuffer textData = new StringBuffer( functionStart ); if ( function.isStatic( ) ) { if ( category.getName( ) != null ) { textData.append( category.getName( ) + "." ); //$NON-NLS-1$ } } textData.append( function.getName( ) + "()" ); //$NON-NLS-1$ return textData.toString( ); } protected void createContextCatagory( ) { assert tree != null; if ( contextItem == null || contextItem.isDisposed( ) ) { contextItem = createTopTreeItem( tree, TREE_ITEM_CONTEXT, 0 ); } createContextObjects( currentMethodName ); } /** * Creates context objects tree. Context ojects tree is used in JS editor * palette, which displays current object method's arguments. */ protected void createContextObjects( String methodName ) { if ( currentEditObject != null && methodName != null ) { DesignElementHandle handle = (DesignElementHandle) currentEditObject; List args = DEUtil.getDesignElementMethodArgumentsInfo( handle, methodName ); for ( Iterator iter = args.iterator( ); iter.hasNext( ); ) { String argName = ( (IArgumentInfo) iter.next( ) ).getName( ); createSubTreeItem( contextItem, argName, IMAGE_METHOD, argName, "", //$NON-NLS-1$ true ); } } } public void setCurrentEditObject( Object obj ) { this.currentEditObject = obj; } private void clearTreeItem( TreeItem treeItem ) { if ( treeItem == null || treeItem.isDisposed( ) ) { return; } treeItem.dispose( ); } private void clearSubTreeItem( TreeItem treeItem ) { if ( treeItem == null || treeItem.isDisposed( ) ) { return; } TreeItem[] items = treeItem.getItems( ); for ( int i = 0; i < items.length; i++ ) { clearTreeItem( items[i] ); } } private void clearDynamicItems( ) { if ( dynamicItems != null ) { for ( TreeItem ti : dynamicItems ) { clearTreeItem( ti ); } dynamicItems.clear( ); } } /* * (non-Javadoc) * * @see * org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged( * org.eclipse.jface.viewers.SelectionChangedEvent) * * Listen to JS editor method change. */ private int eventFireNum = 0; private int execNum = 0; public void selectionChanged( SelectionChangedEvent event ) { ISelection selection = event.getSelection( ); if ( selection != null ) { Object[] sel = ( (IStructuredSelection) selection ).toArray( ); if ( sel.length == 1 ) { if ( sel[0] instanceof IPropertyDefn ) { final IPropertyDefn elePropDefn = (IPropertyDefn) sel[0]; currentMethodName = elePropDefn.getName( ); eventFireNum++; Display.getDefault( ).timerExec( 100, new Runnable( ) { public void run( ) { execNum++; if ( elePropDefn.getName( ) .equals( currentMethodName ) ) { if ( execNum == eventFireNum ) { createExpressionTree( ); } } if ( execNum >= eventFireNum ) { execNum = 0; eventFireNum = 0; } } } ); } } } } private void updateDynamicItems( List<IExpressionProvider> providers ) { for ( IExpressionProvider exprProvider : providers ) { if ( exprProvider != null ) { createDynamicCategory( exprProvider ); } } } private void createDynamicCategory( IExpressionProvider provider ) { Object[] cats = provider.getCategory( ); if ( cats != null ) { for ( Object cat : cats ) { TreeItem ti = createTopTreeItem( tree, cat, provider ); if ( dynamicItems == null ) { dynamicItems = new ArrayList<TreeItem>( ); } dynamicItems.add( ti ); if ( provider.hasChildren( cat ) ) { createDynamicChildern( ti, cat, provider ); } } } } private void createDynamicChildern( TreeItem parent, Object element, IExpressionProvider provider ) { Object[] children = provider.getChildren( element ); if ( children != null ) { for ( Object child : children ) { if ( provider.hasChildren( child ) ) { TreeItem ti = createSubFolderItem( parent, child, provider ); createDynamicChildern( ti, child, provider ); } else { createSubTreeItem( parent, child, provider ); } } } } private TreeItem createTopTreeItem( Tree tree, Object element, IExpressionProvider provider ) { TreeItem item = new TreeItem( tree, SWT.NONE ); item.setText( provider.getDisplayText( element ) ); item.setImage( provider.getImage( element ) ); item.setData( ITEM_DATA_KEY_TOOLTIP, provider.getTooltipText( element ) ); return item; } private TreeItem createSubFolderItem( TreeItem parent, Object element, IExpressionProvider provider ) { TreeItem item = new TreeItem( parent, SWT.NONE ); item.setText( provider.getDisplayText( element ) ); item.setImage( provider.getImage( element ) ); item.setData( ITEM_DATA_KEY_TOOLTIP, provider.getTooltipText( element ) ); return item; } private TreeItem createSubTreeItem( TreeItem parent, Object element, IExpressionProvider provider ) { TreeItem item = new TreeItem( parent, SWT.NONE ); item.setText( provider.getDisplayText( element ) ); item.setImage( provider.getImage( element ) ); item.setData( ITEM_DATA_KEY_TOOLTIP, provider.getTooltipText( element ) ); item.setData( ITEM_DATA_KEY_TEXT, provider.getInsertText( element ) ); item.setData( ITEM_DATA_KEY_ENABLED, Boolean.TRUE ); return item; } public void updateParametersTree( ) { if ( parametersItem != null && !parametersItem.isDisposed( ) ) { clearSubTreeItem( parametersItem ); buildParameterTree( ); restoreSelection( ); } } private void processMethods( IClassInfo classInfo, IMethodInfo mi, List childrenList ) { Iterator alitr = mi.argumentListIterator( ); int idx = 0; if ( alitr == null ) { childrenList.add( new ILocalizableInfo[]{ classInfo, mi } ); } else { while ( alitr.hasNext( ) ) { alitr.next( ); childrenList.add( new ILocalizableInfo[]{ classInfo, mi, new IIndexInfo( idx++ ) } ); } } } /** * Calculates the first available position according to the given item list. */ private int getIndex( TreeItem... items ) { if ( items != null ) { for ( TreeItem ti : items ) { if ( ti != null && !ti.isDisposed( ) ) { return tree.indexOf( ti ) + 1; } } } return 0; } }
UI/org.eclipse.birt.report.designer.ui/src/org/eclipse/birt/report/designer/internal/ui/dialogs/ExpressionTreeSupport.java
/******************************************************************************* * Copyright (c) 2004 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.report.designer.internal.ui.dialogs; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.Iterator; import java.util.List; import org.eclipse.birt.core.exception.BirtException; import org.eclipse.birt.core.script.functionservice.IScriptFunction; import org.eclipse.birt.core.script.functionservice.IScriptFunctionArgument; import org.eclipse.birt.core.script.functionservice.IScriptFunctionCategory; import org.eclipse.birt.core.script.functionservice.impl.FunctionProvider; import org.eclipse.birt.report.designer.core.model.SessionHandleAdapter; import org.eclipse.birt.report.designer.data.ui.aggregation.AggregationUtil; import org.eclipse.birt.report.designer.internal.ui.util.ExceptionHandler; import org.eclipse.birt.report.designer.internal.ui.util.IIndexInfo; import org.eclipse.birt.report.designer.internal.ui.views.memento.Memento; import org.eclipse.birt.report.designer.internal.ui.views.memento.MementoBuilder; import org.eclipse.birt.report.designer.internal.ui.views.memento.MementoElement; import org.eclipse.birt.report.designer.nls.Messages; import org.eclipse.birt.report.designer.ui.IReportGraphicConstants; import org.eclipse.birt.report.designer.ui.ReportPlatformUIImages; import org.eclipse.birt.report.designer.ui.dialogs.IExpressionProvider; import org.eclipse.birt.report.designer.ui.expressions.ExpressionFilter; import org.eclipse.birt.report.designer.ui.expressions.IContextExpressionProvider; import org.eclipse.birt.report.designer.ui.views.ElementAdapterManager; import org.eclipse.birt.report.designer.util.DEUtil; import org.eclipse.birt.report.model.api.DesignElementHandle; import org.eclipse.birt.report.model.api.ModuleHandle; import org.eclipse.birt.report.model.api.ParameterGroupHandle; import org.eclipse.birt.report.model.api.ParameterHandle; import org.eclipse.birt.report.model.api.ReportDesignHandle; import org.eclipse.birt.report.model.api.ReportElementHandle; import org.eclipse.birt.report.model.api.VariableElementHandle; import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants; import org.eclipse.birt.report.model.api.metadata.IArgumentInfo; import org.eclipse.birt.report.model.api.metadata.IArgumentInfoList; import org.eclipse.birt.report.model.api.metadata.IClassInfo; import org.eclipse.birt.report.model.api.metadata.ILocalizableInfo; import org.eclipse.birt.report.model.api.metadata.IMemberInfo; import org.eclipse.birt.report.model.api.metadata.IMethodInfo; import org.eclipse.birt.report.model.api.metadata.IPropertyDefn; import org.eclipse.jface.text.source.SourceViewer; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.DragSource; import org.eclipse.swt.dnd.DragSourceAdapter; import org.eclipse.swt.dnd.DragSourceEvent; import org.eclipse.swt.dnd.DropTarget; import org.eclipse.swt.dnd.DropTargetAdapter; import org.eclipse.swt.dnd.DropTargetEvent; import org.eclipse.swt.dnd.TextTransfer; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseTrackAdapter; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.TreeEvent; import org.eclipse.swt.events.TreeListener; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeItem; import org.eclipse.swt.widgets.Widget; import org.eclipse.ui.IMemento; import org.eclipse.ui.ISharedImages; import com.ibm.icu.text.Collator; /** * Deals with tree part of expression builder. Adds some mouse and DND support * to tree and corresponding source viewer. */ public class ExpressionTreeSupport implements ISelectionChangedListener { // Tree item icon images private static final Image IMAGE_FOLDER = ReportPlatformUIImages.getImage( ISharedImages.IMG_OBJ_FOLDER ); private static final Image IMAGE_OPERATOR = getIconImage( IReportGraphicConstants.ICON_EXPRESSION_OPERATOR ); private static final Image IMAGE_GOLBAL = getIconImage( IReportGraphicConstants.ICON_EXPRESSION_GLOBAL ); private static final Image IMAGE_METHOD = getIconImage( IReportGraphicConstants.ICON_EXPRESSION_METHOD ); private static final Image IMAGE_STATIC_METHOD = getIconImage( IReportGraphicConstants.ICON_EXPRESSION_STATIC_METHOD ); private static final Image IMAGE_CONSTRUCTOR = getIconImage( IReportGraphicConstants.ICON_EXPRESSION_CONSTRUCTOP ); private static final Image IMAGE_MEMBER = getIconImage( IReportGraphicConstants.ICON_EXPRESSION_MEMBER ); private static final Image IMAGE_STATIC_MEMBER = getIconImage( IReportGraphicConstants.ICON_EXPRESSION_STATIC_MEMBER ); /** Arithmetic operators and their descriptions */ private static final String[][] OPERATORS_ASSIGNMENT = new String[][]{ { "=", Messages.getString( "ExpressionProvider.Operator.Assign" ) //$NON-NLS-1$ //$NON-NLS-2$ }, { "+=", Messages.getString( "ExpressionProvider.Operator.AddTo" ) //$NON-NLS-1$ //$NON-NLS-2$ }, { "-=", Messages.getString( "ExpressionProvider.Operator.SubFrom" ) //$NON-NLS-1$ //$NON-NLS-2$ }, { "*=", Messages.getString( "ExpressionProvider.Operator.MultTo" ) //$NON-NLS-1$ //$NON-NLS-2$ }, { "/=", Messages.getString( "ExpressionProvider.Operator.DividingFrom" ) //$NON-NLS-1$ //$NON-NLS-2$ } }; /** Comparison operators and their descriptions */ private static final String[][] OPERATORS_COMPARISON = new String[][]{ { "==", Messages.getString( "ExpressionProvider.Operator.Equals" ) //$NON-NLS-1$ //$NON-NLS-2$ }, { "<", Messages.getString( "ExpressionProvider.Operator.Less" ) //$NON-NLS-1$ //$NON-NLS-2$ }, { "<=",//$NON-NLS-1$ Messages.getString( "ExpressionProvider.Operator.LessEqual" ) //$NON-NLS-1$ }, { "!=",//$NON-NLS-1$ Messages.getString( "ExpressionProvider.Operator.NotEqual" ) //$NON-NLS-1$ }, { ">", Messages.getString( "ExpressionProvider.Operator.Greater" ) //$NON-NLS-1$ //$NON-NLS-2$ }, { ">=",//$NON-NLS-1$ Messages.getString( "ExpressionProvider.Operator.GreaterEquals" ) //$NON-NLS-1$ } }; /** Computational operators and their descriptions */ private static final String[][] OPERATORS_COMPUTATIONAL = new String[][]{ { "+", Messages.getString( "ExpressionProvider.Operator.Add" ) //$NON-NLS-1$ //$NON-NLS-2$ }, { "-", Messages.getString( "ExpressionProvider.Operator.Sub" ) //$NON-NLS-1$ //$NON-NLS-2$ }, { "*", Messages.getString( "ExpressionProvider.Operator.Mult" ) //$NON-NLS-1$ //$NON-NLS-2$ }, { "/",//$NON-NLS-1$ Messages.getString( "ExpressionProvider.Operator.Divides" ) //$NON-NLS-1$ }, { "++X ",//$NON-NLS-1$ Messages.getString( "ExpressionProvider.Operator.Inc" ) //$NON-NLS-1$ }, { "X++ ", Messages.getString( "ExpressionProvider.Operator.ReturnInc" ) //$NON-NLS-1$ //$NON-NLS-2$ }, { "--X ", Messages.getString( "ExpressionProvider.Operator.Dec" ) //$NON-NLS-1$ //$NON-NLS-2$ }, { "X-- ", Messages.getString( "ExpressionProvider.Operator.ReturnDec" ) //$NON-NLS-1$ //$NON-NLS-2$ } }; /** Logical operators and their descriptions */ private static final String[][] OPERATORS_LOGICAL = new String[][]{ { "&&",//$NON-NLS-1$ Messages.getString( "ExpressionProvider.Operator.And" ) //$NON-NLS-1$ }, { "||",//$NON-NLS-1$ Messages.getString( "ExpressionProvider.Operator.Or" ) //$NON-NLS-1$ } }; private static final String TREE_ITEM_CONTEXT = Messages.getString( "ExpressionProvider.Category.Context" ); //$NON-NLS-1$ private static final String TREE_ITEM_OPERATORS = Messages.getString( "ExpressionProvider.Category.Operators" ); //$NON-NLS-1$ private static final String TREE_ITEM_BIRT_OBJECTS = Messages.getString( "ExpressionProvider.Category.BirtObjects" ); //$NON-NLS-1$ private static final String TREE_ITEM_PARAMETERS = Messages.getString( "ExpressionProvider.Category.Parameters" ); //$NON-NLS-1$ private static final String TREE_ITEM_NATIVE_OBJECTS = Messages.getString( "ExpressionProvider.Category.NativeObjects" ); //$NON-NLS-1$ private static final String TREE_ITEM_VARIABLES = Messages.getString( "ExpressionProvider.Category.Variables" ); //$NON-NLS-1$ private static final String TREE_ITEM_LOGICAL = Messages.getString( "ExpressionProvider.Operators.Logical" ); //$NON-NLS-1$ private static final String TREE_ITEM_COMPUTATIONAL = Messages.getString( "ExpressionProvider.Operators.Computational" ); //$NON-NLS-1$ private static final String TREE_ITEM_COMPARISON = Messages.getString( "ExpressionProvider.Operators.Comparison" ); //$NON-NLS-1$ private static final String TREE_ITEM_ASSIGNMENT = Messages.getString( "ExpressionProvider.Operators.Assignment" ); //$NON-NLS-1$ /** Tool tip key of tree item data */ protected static final String ITEM_DATA_KEY_TOOLTIP = "TOOL_TIP"; //$NON-NLS-1$ /** * Text key of tree item data, this data is the text string to be inserted * into the text area */ protected static final String ITEM_DATA_KEY_TEXT = "TEXT"; //$NON-NLS-1$ protected static final String ITEM_DATA_KEY_ENABLED = "ENABLED"; //$NON-NLS-1$ private static final String OBJECTS_TYPE_NATIVE = "native";//$NON-NLS-1$ private static final String OBJECTS_TYPE_BIRT = "birt";//$NON-NLS-1$ private SourceViewer expressionViewer; private Tree tree; private DropTarget dropTarget; private DropTargetAdapter dropTargetAdapter; private Object currentEditObject; private String currentMethodName; private TreeItem contextItem, parametersItem, nativeObejctsItem, birtObjectsItem, operatorsItem, variablesItem; private List<TreeItem> dynamicItems; private List staticFilters; private MementoBuilder builder = new MementoBuilder( ); private Memento viewerMemento; public ExpressionTreeSupport( ) { super( ); } /** * Creates all expression trees in default order */ public void createDefaultExpressionTree( ) { createFilteredExpressionTree( null ); } /** * Creates selected expression trees with given filter list. * * @param filterList * list of filters */ public void createFilteredExpressionTree( List filterList ) { this.staticFilters = filterList; createExpressionTree( ); } public String getElementType( ) { if ( currentEditObject == null ) return null; String displayName = ( (DesignElementHandle) currentEditObject ).getDefn( ) .getDisplayName( ); if ( displayName == null || "".equals( displayName ) )//$NON-NLS-1$ { displayName = ( (DesignElementHandle) currentEditObject ).getDefn( ) .getName( ); } return displayName; } private void createExpressionTree( ) { if ( tree == null || tree.isDisposed( ) ) { return; } List<IExpressionProvider> dynamicContextProviders = null; List<ExpressionFilter> dynamicFilters = null; if ( currentEditObject != null && currentMethodName != null ) { if ( viewerMemento != null ) { IMemento memento = viewerMemento.getChild( getElementType( ) ); if ( memento == null ) { Memento elementMemento = (Memento) viewerMemento.createChild( getElementType( ), MementoElement.Type_Element ); elementMemento.getMementoElement( ) .setValue( getElementType( ) ); } } Object[] adapters = ElementAdapterManager.getAdapters( currentEditObject, IContextExpressionProvider.class ); if ( adapters != null ) { for ( Object adapt : adapters ) { IContextExpressionProvider contextProvider = (IContextExpressionProvider) adapt; if ( contextProvider != null ) { IExpressionProvider exprProvider = contextProvider.getExpressionProvider( currentMethodName ); if ( exprProvider != null ) { if ( dynamicContextProviders == null ) { dynamicContextProviders = new ArrayList<IExpressionProvider>( ); } dynamicContextProviders.add( exprProvider ); } ExpressionFilter exprFilter = contextProvider.getExpressionFilter( currentMethodName ); if ( exprFilter != null ) { if ( dynamicFilters == null ) { dynamicFilters = new ArrayList<ExpressionFilter>( ); } dynamicFilters.add( exprFilter ); } } } } } List<ExpressionFilter> filters = null; if ( staticFilters != null && dynamicFilters != null ) { filters = new ArrayList<ExpressionFilter>( ); filters.addAll( staticFilters ); filters.addAll( dynamicFilters ); } else if ( staticFilters != null ) { filters = staticFilters; } else if ( dynamicFilters != null ) { filters = dynamicFilters; } // flag to check if some bulit-in categories need be removed boolean hasContext = false; boolean hasParameters = false; boolean hasVariables = false; boolean hasNativeObjects = false; boolean hasBirtObjects = false; boolean hasOperators = false; // check and create built-in categories if ( filter( ExpressionFilter.CATEGORY, ExpressionFilter.CATEGORY_CONTEXT, filters ) ) { hasContext = true; clearSubTreeItem( contextItem ); createContextCatagory( ); } if ( filter( ExpressionFilter.CATEGORY, ExpressionFilter.CATEGORY_PARAMETERS, filters ) ) { hasParameters = true; if ( parametersItem == null || parametersItem.isDisposed( ) ) { // only create once createParamtersCategory( ); } } if ( filter( ExpressionFilter.CATEGORY, ExpressionFilter.CATEGORY_VARIABLES, filters ) ) { hasVariables = true; createVariablesCategory( ); } if ( filter( ExpressionFilter.CATEGORY, ExpressionFilter.CATEGORY_NATIVE_OBJECTS, filters ) ) { hasNativeObjects = true; if ( nativeObejctsItem == null || nativeObejctsItem.isDisposed( ) ) { // only create once createNativeObjectsCategory( ); } } if ( filter( ExpressionFilter.CATEGORY, ExpressionFilter.CATEGORY_BIRT_OBJECTS, filters ) ) { hasBirtObjects = true; if ( birtObjectsItem == null || birtObjectsItem.isDisposed( ) ) { // only create once createBirtObjectsCategory( ); } } if ( filter( ExpressionFilter.CATEGORY, ExpressionFilter.CATEGORY_OPERATORS, filters ) ) { hasOperators = true; if ( operatorsItem == null || operatorsItem.isDisposed( ) ) { // only create once createOperatorsCategory( ); } } if ( !hasContext ) { clearTreeItem( contextItem ); } if ( !hasParameters ) { clearTreeItem( parametersItem ); } if ( !hasVariables ) { clearTreeItem( variablesItem ); } if ( !hasNativeObjects ) { clearTreeItem( nativeObejctsItem ); } if ( !hasBirtObjects ) { clearTreeItem( birtObjectsItem ); } if ( !hasOperators ) { clearTreeItem( operatorsItem ); } clearDynamicItems( ); if ( dynamicContextProviders != null ) { updateDynamicItems( dynamicContextProviders ); } restoreSelection( ); } protected void saveSelection( TreeItem selection ) { MementoElement[] selectPath = createItemPath( selection ); ( (Memento) viewerMemento.getChild( getElementType( ) ) ).getMementoElement( ) .setAttribute( MementoElement.ATTRIBUTE_SELECTED, selectPath ); } protected MementoElement[] createItemPath( TreeItem item ) { MementoElement tempMemento = null; while ( item.getParentItem( ) != null ) { TreeItem parent = item.getParentItem( ); for ( int i = 0; i < parent.getItemCount( ); i++ ) { if ( parent.getItem( i ) == item ) { MementoElement memento = new MementoElement( item.getText( ), item.getText( ), MementoElement.Type_Element ); if ( tempMemento != null ) memento.addChild( tempMemento ); tempMemento = memento; item = parent; break; } } } MementoElement memento = new MementoElement( item.getText( ), item.getText( ), MementoElement.Type_Element ); if ( tempMemento != null ) memento.addChild( tempMemento ); return getNodePath( memento ); } public MementoElement[] getNodePath( MementoElement node ) { ArrayList pathList = new ArrayList( ); MementoElement memento = node; pathList.add( node );// add root while ( memento.getChildren( ).length > 0 ) { pathList.add( memento.getChild( 0 ) ); memento = (MementoElement) memento.getChild( 0 ); } MementoElement[] paths = new MementoElement[pathList.size( )]; pathList.toArray( paths ); return paths; } private void restoreSelection( ) { Memento memento = ( (Memento) viewerMemento.getChild( getElementType( ) ) ); if ( memento == null ) return; expandTreeFromMemento( memento ); Object obj = memento.getMementoElement( ) .getAttribute( MementoElement.ATTRIBUTE_SELECTED ); if ( obj != null ) { for ( int i = 0; i < tree.getItemCount( ); i++ ) { restoreSelectedMemento( tree.getItem( i ), (MementoElement[]) obj ); } } } private void restoreSelectedMemento( TreeItem root, MementoElement[] selectedPath ) { if ( selectedPath.length <= 0 ) return; for ( int i = 0; i < selectedPath.length; i++ ) { MementoElement element = selectedPath[i]; if ( root.getText( ).equals( element.getValue( ) ) ) { continue; } boolean flag = false; for ( int j = 0; j < root.getItemCount( ); j++ ) { if ( root.getItem( j ).getText( ).equals( element.getValue( ) ) ) { root = root.getItem( j ); flag = true; break; } } if ( !flag ) return; } tree.setSelection( root ); } /** * Filters the tree name, given the filter list. * * @param treeName * the tree name to be filtered. * @param filters * the filter list. * @return true if the tree name passes the filter list. */ private boolean filter( Object parent, Object child, List<ExpressionFilter> filters ) { if ( filters == null ) { return true; } for ( ExpressionFilter ft : filters ) { if ( ft != null && !ft.select( parent, child ) ) { return false; } } return true; } /** * Create operators band.Must set Tree before execution. * */ protected void createOperatorsCategory( ) { assert tree != null; int idx = getIndex( birtObjectsItem, nativeObejctsItem, parametersItem, contextItem ); operatorsItem = createTopTreeItem( tree, TREE_ITEM_OPERATORS, idx ); TreeItem subItem = createSubFolderItem( operatorsItem, TREE_ITEM_ASSIGNMENT ); createSubTreeItems( subItem, OPERATORS_ASSIGNMENT, IMAGE_OPERATOR ); subItem = createSubFolderItem( operatorsItem, TREE_ITEM_COMPARISON ); createSubTreeItems( subItem, OPERATORS_COMPARISON, IMAGE_OPERATOR ); subItem = createSubFolderItem( operatorsItem, TREE_ITEM_COMPUTATIONAL ); createSubTreeItems( subItem, OPERATORS_COMPUTATIONAL, IMAGE_OPERATOR ); subItem = createSubFolderItem( operatorsItem, TREE_ITEM_LOGICAL ); createSubTreeItems( subItem, OPERATORS_LOGICAL, IMAGE_OPERATOR ); } /** * Create native object band.Must set Tree before execution. * */ protected void createNativeObjectsCategory( ) { assert tree != null; int idx = getIndex( parametersItem, contextItem ); nativeObejctsItem = createTopTreeItem( tree, TREE_ITEM_NATIVE_OBJECTS, idx ); createObjects( nativeObejctsItem, OBJECTS_TYPE_NATIVE ); } /** * Create parameters band. Must set Tree before execution. * */ protected void createParamtersCategory( ) { assert tree != null; int idx = getIndex( contextItem ); parametersItem = createTopTreeItem( tree, TREE_ITEM_PARAMETERS, idx ); buildParameterTree( ); } private void buildParameterTree( ) { ModuleHandle module = SessionHandleAdapter.getInstance( ) .getReportDesignHandle( ); if ( module == null ) { return; } for ( Iterator iterator = module.getParameters( ).iterator( ); iterator.hasNext( ); ) { ReportElementHandle handle = (ReportElementHandle) iterator.next( ); if ( handle instanceof ParameterHandle ) { createSubTreeItem( parametersItem, DEUtil.getDisplayLabel( handle, false ), ReportPlatformUIImages.getImage( handle ), DEUtil.getExpression( handle ), ( (ParameterHandle) handle ).getHelpText( ), true ); } else if ( handle instanceof ParameterGroupHandle ) { TreeItem groupItem = createSubTreeItem( parametersItem, DEUtil.getDisplayLabel( handle, false ), ReportPlatformUIImages.getImage( handle ), true ); for ( Iterator itor = ( (ParameterGroupHandle) handle ).getParameters( ) .iterator( ); itor.hasNext( ); ) { ParameterHandle parameter = (ParameterHandle) itor.next( ); createSubTreeItem( groupItem, parameter.getDisplayLabel( ), ReportPlatformUIImages.getImage( handle ), DEUtil.getExpression( parameter ), parameter.getDisplayLabel( ), true ); } } } } protected void createVariablesCategory( ) { if ( variablesItem == null || variablesItem.isDisposed( ) ) { int idx = getIndex( contextItem ); variablesItem = createTopTreeItem( tree, TREE_ITEM_VARIABLES, idx ); } buildVariableTree( ); } private void buildVariableTree( ) { clearSubTreeItem( variablesItem ); ModuleHandle handle = SessionHandleAdapter.getInstance( ) .getReportDesignHandle( ); if ( handle instanceof ReportDesignHandle ) { for ( VariableElementHandle variableHandle : ( (ReportDesignHandle) handle ).getPageVariables( ) ) { if ( currentMethodName != null && DesignChoiceConstants.VARIABLE_TYPE_PAGE.equals( variableHandle.getType( ) ) && !( currentMethodName.equals( "onPageStart" ) || currentMethodName.equals( "onPageEnd" ) || currentMethodName.equals( "onRender" ) ) ) continue; createSubTreeItem( variablesItem, DEUtil.getDisplayLabel( variableHandle, false ), ReportPlatformUIImages.getImage( variableHandle ), DEUtil.getExpression( variableHandle ), variableHandle.getDisplayLabel( ), true ); } } restoreSelection( ); } /** * Creates birt object tree. Must set Tree before execution. * */ protected void createBirtObjectsCategory( ) { assert tree != null; int idx = getIndex( nativeObejctsItem, parametersItem, contextItem ); birtObjectsItem = createTopTreeItem( tree, TREE_ITEM_BIRT_OBJECTS, idx ); createObjects( birtObjectsItem, OBJECTS_TYPE_BIRT ); } // /** // * Creates a top tree item // * // * @param parent // * @param text // * @return tree item // */ // private TreeItem createTopTreeItem( Tree parent, String text ) // { // TreeItem item = new TreeItem( parent, SWT.NONE ); // item.setText( text ); // item.setImage( IMAGE_FOLDER ); // item.setData( ITEM_DATA_KEY_TOOLTIP, "" );//$NON-NLS-1$ // return item; // } private TreeItem createTopTreeItem( Tree parent, String text, int index ) { TreeItem item = new TreeItem( parent, SWT.NONE, index ); item.setText( text ); item.setImage( IMAGE_FOLDER ); item.setData( ITEM_DATA_KEY_TOOLTIP, "" );//$NON-NLS-1$ return item; } private TreeItem createSubTreeItem( TreeItem parent, String text, Image image, boolean isEnabled ) { return createSubTreeItem( parent, text, image, null, text, isEnabled ); } private TreeItem createSubTreeItem( TreeItem parent, String text, Image image, String textData, String toolTip, boolean isEnabled ) { TreeItem item = new TreeItem( parent, SWT.NONE ); item.setText( text ); if ( image != null ) { item.setImage( image ); } item.setData( ITEM_DATA_KEY_TOOLTIP, toolTip ); item.setData( ITEM_DATA_KEY_TEXT, textData ); item.setData( ITEM_DATA_KEY_ENABLED, Boolean.valueOf( isEnabled ) ); return item; } private TreeItem createSubFolderItem( TreeItem parent, String text ) { return createSubTreeItem( parent, text, IMAGE_FOLDER, true ); } private TreeItem createSubFolderItem( TreeItem parent, IClassInfo classInfo ) { return createSubTreeItem( parent, classInfo.getDisplayName( ), IMAGE_FOLDER, null, classInfo.getToolTip( ), true ); } private TreeItem createSubFolderItem( TreeItem parent, IScriptFunctionCategory category ) { String categoreName = getCategoryDisplayName( category ); return createSubTreeItem( parent, categoreName, IMAGE_FOLDER, null, category.getDescription( ), true ); } private String getCategoryDisplayName( IScriptFunctionCategory category ) { return category.getName( ) == null ? Messages.getString( "ExpressionTreeSupport.Category.Global" ) //$NON-NLS-1$ : category.getName( ); } private void createSubTreeItems( TreeItem parent, String[][] texts, Image image ) { for ( int i = 0; i < texts.length; i++ ) { createSubTreeItem( parent, texts[i][0], image, texts[i][0], texts[i][1], true ); } } /** * Adds mouse track listener.Must set Tree before execution. * */ public void addMouseTrackListener( ) { assert tree != null; tree.addMouseTrackListener( new MouseTrackAdapter( ) { public void mouseHover( MouseEvent event ) { Widget widget = event.widget; if ( widget == tree ) { Point pt = new Point( event.x, event.y ); TreeItem item = tree.getItem( pt ); if ( item == null ) tree.setToolTipText( "" );//$NON-NLS-1$ else { String text = (String) item.getData( ITEM_DATA_KEY_TOOLTIP ); tree.setToolTipText( text ); } } } } ); } /** * Add double click behaviour. Must set Tree before execution. * */ public void addMouseListener( ) { assert tree != null; tree.addMouseListener( new MouseAdapter( ) { public void mouseDoubleClick( MouseEvent event ) { TreeItem[] selection = getTreeSelection( ); if ( selection == null || selection.length <= 0 ) return; TreeItem item = selection[0]; if ( item != null ) { Object obj = item.getData( ITEM_DATA_KEY_TEXT ); Boolean isEnabled = (Boolean) item.getData( ITEM_DATA_KEY_ENABLED ); if ( obj != null && isEnabled.booleanValue( ) ) { String text = (String) obj; insertText( text ); } } } } ); } protected TreeItem[] getTreeSelection( ) { return tree.getSelection( ); } /** * Adds drag support to tree..Must set tree before execution. */ public void addDragSupportToTree( ) { assert tree != null; DragSource dragSource = new DragSource( tree, DND.DROP_COPY | DND.DROP_MOVE ); dragSource.setTransfer( new Transfer[]{ TextTransfer.getInstance( ) } ); dragSource.addDragListener( new DragSourceAdapter( ) { public void dragStart( DragSourceEvent event ) { TreeItem[] selection = tree.getSelection( ); if ( selection.length <= 0 || selection[0].getData( ITEM_DATA_KEY_TEXT ) == null || !( (Boolean) selection[0].getData( ITEM_DATA_KEY_ENABLED ) ).booleanValue( ) ) { event.doit = false; return; } } public void dragSetData( DragSourceEvent event ) { if ( TextTransfer.getInstance( ) .isSupportedType( event.dataType ) ) { TreeItem[] selection = tree.getSelection( ); if ( selection.length > 0 ) { event.data = selection[0].getData( ITEM_DATA_KEY_TEXT ); } } } } ); } /** * Insert a text string into the text area * * @param text */ protected void insertText( String text ) { StyledText textWidget = expressionViewer.getTextWidget( ); if ( !textWidget.isEnabled( ) ) { return; } int selectionStart = textWidget.getSelection( ).x; if ( text.equalsIgnoreCase( "x++" ) ) //$NON-NLS-1$ { text = textWidget.getSelectionText( ) + "++";//$NON-NLS-1$ } else if ( text.equalsIgnoreCase( "x--" ) )//$NON-NLS-1$ { text = textWidget.getSelectionText( ) + "--";//$NON-NLS-1$ } else if ( text.equalsIgnoreCase( "++x" ) )//$NON-NLS-1$ { text = "++" + textWidget.getSelectionText( );//$NON-NLS-1$ } else if ( text.equalsIgnoreCase( "--x" ) )//$NON-NLS-1$ { text = "--" + textWidget.getSelectionText( );//$NON-NLS-1$ } textWidget.insert( text ); textWidget.setSelection( selectionStart + text.length( ) ); textWidget.setFocus( ); if ( text.endsWith( "()" ) ) //$NON-NLS-1$ { textWidget.setCaretOffset( textWidget.getCaretOffset( ) - 1 ); // Move } } /** * Adds drop support to viewer.Must set viewer before execution. * */ public void addDropSupportToViewer( ) { assert expressionViewer != null; if ( dropTarget == null || dropTarget.isDisposed( ) ) { final StyledText text = expressionViewer.getTextWidget( ); // Doesn't add again if a drop target has been created in the // viewer. if ( text.getData( "DropTarget" ) != null ) //$NON-NLS-1$ { return; } dropTarget = new DropTarget( text, DND.DROP_COPY | DND.DROP_DEFAULT ); dropTarget.setTransfer( new Transfer[]{ TextTransfer.getInstance( ) } ); dropTargetAdapter = new DropTargetAdapter( ) { public void dragEnter( DropTargetEvent event ) { text.setFocus( ); if ( event.detail == DND.DROP_DEFAULT ) event.detail = DND.DROP_COPY; if ( event.detail != DND.DROP_COPY ) event.detail = DND.DROP_NONE; } public void dragOver( DropTargetEvent event ) { event.feedback = DND.FEEDBACK_SCROLL | DND.FEEDBACK_INSERT_BEFORE; } public void dragOperationChanged( DropTargetEvent event ) { dragEnter( event ); } public void drop( DropTargetEvent event ) { if ( event.data instanceof String ) insertText( (String) event.data ); } }; dropTarget.addDropListener( dropTargetAdapter ); } } public void removeDropSupportToViewer( ) { if ( dropTarget != null && !dropTarget.isDisposed( ) ) { if ( dropTargetAdapter != null ) { dropTarget.removeDropListener( dropTargetAdapter ); dropTargetAdapter = null; } dropTarget.dispose( ); dropTarget = null; } } /** * Sets the tree model. * * @param tree */ public void setTree( final Tree tree ) { this.tree = tree; if ( ( viewerMemento = (Memento) builder.getRootMemento( ) .getChild( "ExpressionTreeSupport" ) ) == null ) { viewerMemento = (Memento) builder.getRootMemento( ) .createChild( "ExpressionTreeSupport", MementoElement.Type_Viewer ); } SelectionAdapter treeSelectionListener = new SelectionAdapter( ) { public void widgetDefaultSelected( SelectionEvent e ) { saveSelection( (TreeItem) e.item ); } }; tree.addSelectionListener( treeSelectionListener ); tree.addMouseListener( new MouseAdapter( ) { public void mouseDown( MouseEvent event ) { // only activate if there is a cell editor Point pt = new Point( event.x, event.y ); TreeItem item = tree.getItem( pt ); if ( item != null ) { saveSelection( item ); } } } ); tree.addKeyListener( new KeyAdapter( ) { public void keyReleased( KeyEvent e ) { if ( tree.getSelectionCount( ) > 0 ) saveSelection( tree.getSelection( )[0] ); } } ); TreeListener treeListener = new TreeListener( ) { public void treeCollapsed( TreeEvent e ) { if ( e.item instanceof TreeItem ) { TreeItem item = (TreeItem) e.item; MementoElement[] path = createItemPath( item ); removeNode( ( (Memento) viewerMemento.getChild( getElementType( ) ) ), path ); getTree( ).setSelection( item ); saveSelection( item ); } } public void treeExpanded( TreeEvent e ) { if ( e.item instanceof TreeItem ) { TreeItem item = (TreeItem) e.item; MementoElement[] path = createItemPath( item ); addNode( ( (Memento) viewerMemento.getChild( getElementType( ) ) ), path ); getTree( ).setSelection( item ); saveSelection( item ); } } }; tree.addTreeListener( treeListener ); } public boolean addNode( Memento element, MementoElement[] nodePath ) { if ( nodePath != null && nodePath.length > 0 ) { MementoElement memento = element.getMementoElement( ); // if ( !memento.equals( nodePath[0] ) ) // return false; for ( int i = 0; i < nodePath.length; i++ ) { MementoElement child = getChild( memento, nodePath[i] ); if ( child != null ) memento = child; else { memento.addChild( nodePath[i] ); return true; } } return true; } return false; } public boolean removeNode( Memento element, MementoElement[] nodePath ) { if ( nodePath != null && nodePath.length > 0 ) { MementoElement memento = element.getMementoElement( ); // if ( !memento.equals( nodePath[0] ) ) // return false; for ( int i = 0; i < nodePath.length; i++ ) { MementoElement child = getChild( memento, nodePath[i] ); if ( child != null ) memento = child; else return false; } memento.getParent( ).removeChild( memento ); return true; } return false; } private void expandTreeFromMemento( Memento memento ) { if ( tree.getItemCount( ) == 0 || memento == null ) return; for ( int i = 0; i < tree.getItemCount( ); i++ ) { TreeItem root = tree.getItem( i ); for ( int j = 0; j < memento.getMementoElement( ).getChildren( ).length; j++ ) { MementoElement child = memento.getMementoElement( ) .getChildren( )[j]; restoreExpandedMemento( root, child ); } } } private void restoreExpandedMemento( TreeItem root, MementoElement memento ) { if ( memento.getKey( ).equals( root.getText( ) ) ) { if ( root.getItemCount( ) > 0 ) { if ( !root.getExpanded( ) ) root.setExpanded( true ); MementoElement[] children = memento.getChildren( ); for ( int i = 0; i < children.length; i++ ) { MementoElement child = children[i]; String key = child.getValue( ).toString( ); for ( int j = 0; j < root.getItemCount( ); j++ ) { TreeItem item = root.getItem( j ); if ( item.getText( ).equals( key ) ) { restoreExpandedMemento( item, child ); break; } } } } } } private MementoElement getChild( MementoElement parent, MementoElement key ) { MementoElement[] children = parent.getChildren( ); for ( int i = 0; i < children.length; i++ ) { if ( children[i].equals( key ) ) return children[i]; } return null; }; protected Tree getTree( ) { return tree; } /** * Sets the viewer to use. * * @param expressionViewer */ public void setExpressionViewer( SourceViewer expressionViewer ) { this.expressionViewer = expressionViewer; } protected SourceViewer getExpressionViewer( ) { return expressionViewer; } /** * Gets an icon image by the key in plugin.properties * * @param id * @return image */ private static Image getIconImage( String id ) { return ReportPlatformUIImages.getImage( id ); } private void createObjects( TreeItem topItem, String objectType ) { for ( Iterator itor = DEUtil.getClasses( ).iterator( ); itor.hasNext( ); ) { IClassInfo classInfo = (IClassInfo) itor.next( ); if ( classInfo.isNative( ) && OBJECTS_TYPE_BIRT.equals( objectType ) || !classInfo.isNative( ) && OBJECTS_TYPE_NATIVE.equals( objectType ) || classInfo.getName( ).equals( "Total" ) ) //$NON-NLS-1$ { continue; } TreeItem subItem = createSubFolderItem( topItem, classInfo ); Image globalImage = null; if ( isGlobal( classInfo.getName( ) ) ) { globalImage = IMAGE_GOLBAL; } ArrayList<Object> childrenList = new ArrayList<Object>( ); IMemberInfo[] members = (IMemberInfo[]) DEUtil.getMembers( classInfo ) .toArray( new IMemberInfo[0] ); for ( int i = 0; i < members.length; i++ ) { childrenList.add( new ILocalizableInfo[]{ classInfo, members[i] } ); } List methodList = new ArrayList( ); methodList.addAll( DEUtil.getMethods( classInfo, true ) ); methodList.addAll( AggregationUtil.getMethods( classInfo ) ); IMethodInfo[] methods = (IMethodInfo[]) methodList.toArray( new IMethodInfo[0] ); for ( int i = 0; i < methods.length; i++ ) { IMethodInfo mi = methods[i]; processMethods( classInfo, mi, childrenList ); } ILocalizableInfo[][] children = childrenList.toArray( new ILocalizableInfo[0][] ); sortLocalizableInfo( children ); for ( int i = 0; i < children.length; i++ ) { Object obj = children[i]; createSubTreeItem( subItem, getDisplayText( obj ), globalImage == null ? getImage( obj ) : globalImage, getInsertText( obj ), getTooltipText( obj ), true ); } } if ( OBJECTS_TYPE_BIRT.equals( objectType ) ) { try { IScriptFunctionCategory[] categorys = FunctionProvider.getCategories( ); Arrays.sort( categorys, new Comparator<IScriptFunctionCategory>( ) { public int compare( IScriptFunctionCategory o1, IScriptFunctionCategory o2 ) { return getCategoryDisplayName( o1 ).compareTo( getCategoryDisplayName( o2 ) ); } } ); if ( categorys != null ) { for ( int i = 0; i < categorys.length; i++ ) { TreeItem subItem = createSubFolderItem( topItem, categorys[i] ); IScriptFunction[] functions = categorys[i].getFunctions( ); Arrays.sort( functions, new Comparator<IScriptFunction>( ) { public int compare( IScriptFunction o1, IScriptFunction o2 ) { return getFunctionDisplayText( o1 ).compareTo( getFunctionDisplayText( o2 ) ); } } ); if ( functions != null ) { for ( int j = 0; j < functions.length; j++ ) { Image image = null; if ( functions[j].isStatic( ) ) { image = IMAGE_STATIC_METHOD; } else { image = IMAGE_METHOD; } createSubTreeItem( subItem, getFunctionDisplayText( functions[j] ), image, getFunctionExpression( categorys[i], functions[j] ), functions[j].getDescription( ), true ); } } } } } catch ( BirtException e ) { ExceptionHandler.handle( e ); } } } private void sortLocalizableInfo( ILocalizableInfo[][] infos ) { Arrays.sort( infos, new Comparator<ILocalizableInfo[]>( ) { private int computeWeight( ILocalizableInfo obj ) { if ( obj instanceof IMemberInfo ) { return ( (IMemberInfo) obj ).isStatic( ) ? 0 : 2; } else if ( obj instanceof IMethodInfo ) { if ( ( (IMethodInfo) obj ).isConstructor( ) ) { return 3; } return ( (IMethodInfo) obj ).isStatic( ) ? 1 : 4; } return 4; } public int compare( ILocalizableInfo[] o1, ILocalizableInfo[] o2 ) { ILocalizableInfo info1 = o1[1]; ILocalizableInfo info2 = o2[1]; int w1 = computeWeight( info1 ); int w2 = computeWeight( info2 ); if ( w1 != w2 ) { return w1 < w2 ? -1 : 1; } return Collator.getInstance( ).compare( getDisplayText( o1 ), getDisplayText( o2 ) ); } } ); } private Image getImage( Object element ) { if ( element instanceof ILocalizableInfo[] ) { ILocalizableInfo info = ( (ILocalizableInfo[]) element )[1]; if ( info instanceof IMethodInfo ) { if ( ( (IMethodInfo) info ).isStatic( ) ) { return IMAGE_STATIC_METHOD; } else if ( ( (IMethodInfo) info ).isConstructor( ) ) { return IMAGE_CONSTRUCTOR; } return IMAGE_METHOD; } if ( info instanceof IMemberInfo ) { if ( ( (IMemberInfo) info ).isStatic( ) ) { return IMAGE_STATIC_MEMBER; } return IMAGE_MEMBER; } } return null; } private String getInsertText( Object element ) { if ( element instanceof VariableElementHandle ) { return ( (VariableElementHandle) element ).getVariableName( ); } if ( element instanceof ILocalizableInfo[] ) { IClassInfo classInfo = (IClassInfo) ( (ILocalizableInfo[]) element )[0]; ILocalizableInfo info = ( (ILocalizableInfo[]) element )[1]; StringBuffer insertText = new StringBuffer( ); if ( info instanceof IMemberInfo ) { IMemberInfo memberInfo = (IMemberInfo) info; if ( memberInfo.isStatic( ) ) { insertText.append( classInfo.getName( ) + "." ); //$NON-NLS-1$ } insertText.append( memberInfo.getName( ) ); } else if ( info instanceof IMethodInfo ) { IMethodInfo methodInfo = (IMethodInfo) info; if ( methodInfo.isStatic( ) ) { insertText.append( classInfo.getName( ) + "." ); //$NON-NLS-1$ } else if ( methodInfo.isConstructor( ) ) { insertText.append( "new " ); //$NON-NLS-1$ } insertText.append( methodInfo.getName( ) ); insertText.append( "()" ); //$NON-NLS-1$ } return insertText.toString( ); } return null; } private String getTooltipText( Object element ) { if ( element instanceof ILocalizableInfo[] ) { ILocalizableInfo info = ( (ILocalizableInfo[]) element )[1]; String tooltip = null; if ( info instanceof IMemberInfo ) { tooltip = ( (IMemberInfo) info ).getToolTip( ); } else if ( info instanceof IMethodInfo ) { tooltip = ( (IMethodInfo) info ).getToolTip( ); } return tooltip == null ? "" : tooltip; //$NON-NLS-1$ } return null; } protected String getDisplayText( Object element ) { if ( element instanceof ILocalizableInfo[] ) { // including class info,method info and member info ILocalizableInfo info = ( (ILocalizableInfo[]) element )[1]; StringBuffer displayText = new StringBuffer( info.getName( ) ); if ( info instanceof IMethodInfo ) { IMethodInfo method = (IMethodInfo) info; displayText.append( "(" ); //$NON-NLS-1$ int argIndex = ( ( (ILocalizableInfo[]) element ).length > 2 ) ? ( ( (IIndexInfo) ( (ILocalizableInfo[]) element )[2] ).getIndex( ) ) : 0; int idx = -1; Iterator argumentListIter = method.argumentListIterator( ); while ( argumentListIter.hasNext( ) ) { IArgumentInfoList arguments = (IArgumentInfoList) argumentListIter.next( ); idx++; if ( idx < argIndex ) { continue; } boolean isFirst = true; for ( Iterator iter = arguments.argumentsIterator( ); iter.hasNext( ); ) { IArgumentInfo argInfo = (IArgumentInfo) iter.next( ); if ( !isFirst ) { displayText.append( ", " ); //$NON-NLS-1$ } isFirst = false; if ( argInfo.getType( ) != null && argInfo.getType( ).length( ) > 0 ) { displayText.append( argInfo.getType( ) + " " //$NON-NLS-1$ + argInfo.getName( ) ); } else displayText.append( argInfo.getName( ) ); } break; } displayText.append( ")" ); //$NON-NLS-1$ if ( !method.isConstructor( ) ) { displayText.append( " : " ); //$NON-NLS-1$ String returnType = method.getReturnType( ); if ( returnType == null || returnType.length( ) == 0 ) { returnType = "void"; //$NON-NLS-1$ } displayText.append( returnType ); } } else if ( info instanceof IMemberInfo ) { String dataType = ( (IMemberInfo) info ).getDataType( ); if ( dataType != null && dataType.length( ) > 0 ) { displayText.append( " : " ); //$NON-NLS-1$ displayText.append( dataType ); } } return displayText.toString( ); } return null; } private boolean isGlobal( String name ) { // TODO global validation is hard coded return name != null && name.startsWith( "Global" ); //$NON-NLS-1$ } private String getFunctionDisplayText( IScriptFunction function ) { String functionStart = function.isConstructor( ) ? "new " : ""; //$NON-NLS-1$//$NON-NLS-2$ StringBuffer displayText = new StringBuffer( functionStart ); displayText.append( function.getName( ) ); IScriptFunctionArgument[] arguments = function.getArguments( ); displayText.append( "(" ); //$NON-NLS-1$ if ( arguments != null ) { for ( int i = 0; i < arguments.length; i++ ) { displayText.append( arguments[i].getName( ) ); if ( i < arguments.length - 1 ) displayText.append( ", " );//$NON-NLS-1$ } } displayText.append( ")" ); //$NON-NLS-1$ return displayText.toString( ); } private String getFunctionExpression( IScriptFunctionCategory category, IScriptFunction function ) { String functionStart = function.isConstructor( ) ? "new " : ""; //$NON-NLS-1$//$NON-NLS-2$ StringBuffer textData = new StringBuffer( functionStart ); if ( function.isStatic( ) ) { if ( category.getName( ) != null ) { textData.append( category.getName( ) + "." ); //$NON-NLS-1$ } } textData.append( function.getName( ) + "()" ); //$NON-NLS-1$ return textData.toString( ); } protected void createContextCatagory( ) { assert tree != null; if ( contextItem == null || contextItem.isDisposed( ) ) { contextItem = createTopTreeItem( tree, TREE_ITEM_CONTEXT, 0 ); } createContextObjects( currentMethodName ); } /** * Creates context objects tree. Context ojects tree is used in JS editor * palette, which displays current object method's arguments. */ protected void createContextObjects( String methodName ) { if ( currentEditObject != null && methodName != null ) { DesignElementHandle handle = (DesignElementHandle) currentEditObject; List args = DEUtil.getDesignElementMethodArgumentsInfo( handle, methodName ); for ( Iterator iter = args.iterator( ); iter.hasNext( ); ) { String argName = ( (IArgumentInfo) iter.next( ) ).getName( ); createSubTreeItem( contextItem, argName, IMAGE_METHOD, argName, "", //$NON-NLS-1$ true ); } } } public void setCurrentEditObject( Object obj ) { this.currentEditObject = obj; } private void clearTreeItem( TreeItem treeItem ) { if ( treeItem == null || treeItem.isDisposed( ) ) { return; } treeItem.dispose( ); } private void clearSubTreeItem( TreeItem treeItem ) { if ( treeItem == null || treeItem.isDisposed( ) ) { return; } TreeItem[] items = treeItem.getItems( ); for ( int i = 0; i < items.length; i++ ) { clearTreeItem( items[i] ); } } private void clearDynamicItems( ) { if ( dynamicItems != null ) { for ( TreeItem ti : dynamicItems ) { clearTreeItem( ti ); } dynamicItems.clear( ); } } /* * (non-Javadoc) * * @see * org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged( * org.eclipse.jface.viewers.SelectionChangedEvent) * * Listen to JS editor method change. */ private int eventFireNum = 0; private int execNum = 0; public void selectionChanged( SelectionChangedEvent event ) { ISelection selection = event.getSelection( ); if ( selection != null ) { Object[] sel = ( (IStructuredSelection) selection ).toArray( ); if ( sel.length == 1 ) { if ( sel[0] instanceof IPropertyDefn ) { final IPropertyDefn elePropDefn = (IPropertyDefn) sel[0]; currentMethodName = elePropDefn.getName( ); eventFireNum++; Display.getDefault( ).timerExec( 100, new Runnable( ) { public void run( ) { execNum++; if ( elePropDefn.getName( ) .equals( currentMethodName ) ) { if ( execNum == eventFireNum ) { createExpressionTree( ); } } if ( execNum >= eventFireNum ) { execNum = 0; eventFireNum = 0; } } } ); } } } } private void updateDynamicItems( List<IExpressionProvider> providers ) { for ( IExpressionProvider exprProvider : providers ) { if ( exprProvider != null ) { createDynamicCategory( exprProvider ); } } } private void createDynamicCategory( IExpressionProvider provider ) { Object[] cats = provider.getCategory( ); if ( cats != null ) { for ( Object cat : cats ) { TreeItem ti = createTopTreeItem( tree, cat, provider ); if ( dynamicItems == null ) { dynamicItems = new ArrayList<TreeItem>( ); } dynamicItems.add( ti ); if ( provider.hasChildren( cat ) ) { createDynamicChildern( ti, cat, provider ); } } } } private void createDynamicChildern( TreeItem parent, Object element, IExpressionProvider provider ) { Object[] children = provider.getChildren( element ); if ( children != null ) { for ( Object child : children ) { if ( provider.hasChildren( child ) ) { TreeItem ti = createSubFolderItem( parent, child, provider ); createDynamicChildern( ti, child, provider ); } else { createSubTreeItem( parent, child, provider ); } } } } private TreeItem createTopTreeItem( Tree tree, Object element, IExpressionProvider provider ) { TreeItem item = new TreeItem( tree, SWT.NONE ); item.setText( provider.getDisplayText( element ) ); item.setImage( provider.getImage( element ) ); item.setData( ITEM_DATA_KEY_TOOLTIP, provider.getTooltipText( element ) ); return item; } private TreeItem createSubFolderItem( TreeItem parent, Object element, IExpressionProvider provider ) { TreeItem item = new TreeItem( parent, SWT.NONE ); item.setText( provider.getDisplayText( element ) ); item.setImage( provider.getImage( element ) ); item.setData( ITEM_DATA_KEY_TOOLTIP, provider.getTooltipText( element ) ); return item; } private TreeItem createSubTreeItem( TreeItem parent, Object element, IExpressionProvider provider ) { TreeItem item = new TreeItem( parent, SWT.NONE ); item.setText( provider.getDisplayText( element ) ); item.setImage( provider.getImage( element ) ); item.setData( ITEM_DATA_KEY_TOOLTIP, provider.getTooltipText( element ) ); item.setData( ITEM_DATA_KEY_TEXT, provider.getInsertText( element ) ); item.setData( ITEM_DATA_KEY_ENABLED, Boolean.TRUE ); return item; } public void updateParametersTree( ) { if ( parametersItem != null && !parametersItem.isDisposed( ) ) { clearSubTreeItem( parametersItem ); buildParameterTree( ); restoreSelection( ); } } private void processMethods( IClassInfo classInfo, IMethodInfo mi, List childrenList ) { Iterator alitr = mi.argumentListIterator( ); int idx = 0; if ( alitr == null ) { childrenList.add( new ILocalizableInfo[]{ classInfo, mi } ); } else { while ( alitr.hasNext( ) ) { alitr.next( ); childrenList.add( new ILocalizableInfo[]{ classInfo, mi, new IIndexInfo( idx++ ) } ); } } } /** * Calculates the first available position according to the given item list. */ private int getIndex( TreeItem... items ) { if ( items != null ) { for ( TreeItem ti : items ) { if ( ti != null && !ti.isDisposed( ) ) { return tree.indexOf( ti ) + 1; } } } return 0; } }
Fixed an NPE.
UI/org.eclipse.birt.report.designer.ui/src/org/eclipse/birt/report/designer/internal/ui/dialogs/ExpressionTreeSupport.java
Fixed an NPE.
Java
lgpl-2.1
85a84b967c1d0e9dee48256915bd70964ed66fdb
0
OwlPlatform/java-owl-sensor
/* * Owl Platform Sensor-Aggregator Library for Java * Copyright (C) 2012 Robert Moore and the Owl Platform * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.owlplatform.sensor; import java.net.InetSocketAddress; import java.util.concurrent.ConcurrentLinkedQueue; import org.apache.mina.core.RuntimeIoException; import org.apache.mina.core.future.ConnectFuture; import org.apache.mina.core.session.IdleStatus; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolCodecFilter; import org.apache.mina.filter.executor.ExecutorFilter; import org.apache.mina.transport.socket.SocketConnector; import org.apache.mina.transport.socket.nio.NioSocketConnector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.owlplatform.common.SampleMessage; import com.owlplatform.sensor.listeners.ConnectionListener; import com.owlplatform.sensor.protocol.codecs.AggregatorSensorProtocolCodecFactory; import com.owlplatform.sensor.protocol.messages.HandshakeMessage; /** * A convenience class for interfacing with aggregators as a sensor/hub. Since * most sensors are implemented in C/C++, this class is primarily used by * Aggregators to forward sensor data to another aggregator. * * @author Robert Moore * */ public class SensorAggregatorInterface { /** * A wrapper to take hide the IOAdapter events from classes using the * SensorAggregatorInterface. * * @author Robert Moore * */ private static final class AdapterHandler implements SensorIoAdapter { /** * The actual object that will respond to events. */ private final SensorAggregatorInterface parent; /** * Creates a new AdapterHandler with the specified * {@code SensorAggregatorInterface} to actually handle events. * * @param parent * the real event handler */ public AdapterHandler(SensorAggregatorInterface parent) { if (parent == null) { throw new IllegalArgumentException( "SensorAggregatorInterface cannot be null"); } this.parent = parent; } @Override public void exceptionCaught(IoSession session, Throwable cause) { this.parent.exceptionCaught(session, cause); } @Override public void sensorConnected(IoSession session) { this.parent.sensorConnected(session); } @Override public void sensorDisconnected(IoSession session) { this.parent.sensorDisconnected(session); } @Override public void handshakeMessageReceived(IoSession session, HandshakeMessage handshakeMessage) { this.parent.handshakeMessageReceived(session, handshakeMessage); } @Override public void handshakeMessageSent(IoSession session, HandshakeMessage handshakeMessage) { this.parent.handshakeMessageSent(session, handshakeMessage); } @Override public void sensorSampleReceived(IoSession session, SampleMessage sampleMessage) { this.parent.sensorSampleReceived(session, sampleMessage); } @Override public void sensorSampleSent(IoSession session, SampleMessage sampleMessage) { this.parent.sensorSampleSent(session, sampleMessage); } @Override public void sessionIdle(IoSession session, IdleStatus idleStatus) { this.parent.sessionIdle(session, idleStatus); } } /** * Logging facility for this class. */ private static final Logger log = LoggerFactory .getLogger(SensorAggregatorInterface.class); /** * The object that will pass events to this SensorAggregatorInterface. Used to * hide interface methods. */ private final AdapterHandler handler = new AdapterHandler(this); /** * The handshake sent to the aggregator. */ private HandshakeMessage sentHandshake; /** * The handshake received from the aggregator. */ private HandshakeMessage receivedHandshake; /** * Indicates whether handshakes have been exchanged/checked and the aggregator * can receive sample messages. */ protected boolean canSendSamples = false; /** * How long to wait between connection attempts to the aggregator, in * milliseconds. */ protected long connectionRetryDelay = 10000; /** * Whether or not to try and stay connected to the aggregator. */ protected boolean stayConnected = false; /** * Whether or not to disconnect from the aggregator if an exception is thrown. */ protected boolean disconnectOnException = true; /** * The hostname or IP address of the aggregator. */ private String host; /** * The port number the aggregator is listening on for sensors. */ private int port = -1; /** * The session of the connected aggregator, or {@code null} if no connection * is established. */ private IoSession session; /** * SocketConnector used to connect to the aggregator. */ private SocketConnector connector; /** * IoHandler used by this aggregator interface. */ private SensorIoHandler ioHandler = new SensorIoHandler(this.handler); /** * List (queue) of listeners for connection events for this aggregator * interface. */ private ConcurrentLinkedQueue<ConnectionListener> connectionListeners = new ConcurrentLinkedQueue<ConnectionListener>(); /** * Number of outstanding (buffered) sample messages to be sent on the * Aggregator's session. */ private int maxOutstandingSamples = Integer.MAX_VALUE; /** * A MINA filter containing a thread pool for executing message events * separate from the IO thread. */ private ExecutorFilter executors; /** * How long to wait for a connection to the aggregator to be established. */ protected long connectionTimeout = 1000l; /** * Configures the IO connector to establish a connection to the aggregator. * * @return {@code true} if the connector was created successfully, else * {@code false}. */ protected boolean setConnector() { if (this.host == null) { log.error("No host value set, cannot set up socket connector."); return false; } if (this.port < 0 || this.port > 65535) { log.error("Port value is invalid {}.", Integer.valueOf(this.port)); return false; } // Disconnect if already connected if (this.connector != null) { boolean tmp = this.stayConnected; this.stayConnected = false; this._disconnect(); this.stayConnected = tmp; } this.executors = new ExecutorFilter(1); this.connector = new NioSocketConnector(); this.connector.getSessionConfig().setTcpNoDelay(true); if (!this.connector.getFilterChain().contains( AggregatorSensorProtocolCodecFactory.CODEC_NAME)) { this.connector.getFilterChain().addLast( AggregatorSensorProtocolCodecFactory.CODEC_NAME, new ProtocolCodecFilter(new AggregatorSensorProtocolCodecFactory( false))); } this.connector.getFilterChain().addLast("ExecutorPool", this.executors); this.connector.setHandler(this.ioHandler); log.debug("Connector set up successfully."); return true; } /** * Initiates a connection to the Aggregator (if it is not yet connected). If * {@code #stayConnected} is {@code true}, then this method will NOT return * until a connection is established or the timeout is exceeded. A timeout of * 0 means the configured timeout value will be used. * * @param maxWait * how long to wait (in milliseconds) for the connection to * @return {@code true} if the connection is established within the timeout * period, else {@code false}. */ public boolean connect(long maxWait) { long timeout = maxWait; if (timeout <= 0) { timeout = this.connectionTimeout; } if (this.connector == null) { if (!this.setConnector()) { log.error("Unable to set up connection to the aggregator."); return false; } } if (this.session != null) { log.error("Already connected!"); return false; } long waitTime = timeout; do { long startAttempt = System.currentTimeMillis(); this.connector.setConnectTimeoutMillis(waitTime-5); if (this._connect(waitTime)) { log.debug("Connection succeeded!"); return true; } if (this.stayConnected) { long retryDelay = this.connectionRetryDelay; if (timeout < this.connectionRetryDelay * 2) { retryDelay = timeout / 2; if (retryDelay < 500) { retryDelay = 500; } } try { log.warn(String.format( "Connection to %s:%d failed, waiting %dms before retrying.", this.host, Integer.valueOf(this.port), Long.valueOf(retryDelay))); Thread.sleep(retryDelay); } catch (InterruptedException ie) { // Ignored } waitTime = waitTime - (System.currentTimeMillis() - startAttempt); } } while (this.stayConnected && waitTime > 0); this._disconnect(); this.finishConnection(); return false; } /** * Initiates a connection to the Aggregator (if it is not yet connected). If * {@code #stayConnected} is {@code true}, then this method will NOT return * until a connection is established. If callers wish to remain connected to * the aggregator, it is best to call {@code #setStayConnected(true)} only * after calling this method. * * This method has been replaced by {@link #connect(long)}, and is equivalent * to calling {@code #connect(0)}. * * @return {@code true} if the connection is established, else {@code false}. */ @Deprecated public boolean doConnectionSetup() { return this.connect(0); } /** * Shuts down this connection to the aggregator. This method has been replaced * by {@link #disconnect()}. */ @Deprecated public void doConnectionTearDown() { this.disconnect(); } /** * Disconnects from the aggregator if already connected. */ public void disconnect() { // Make sure we don't automatically reconnect this.stayConnected = false; this._disconnect(); } /** * Establishes a connection to the remote aggregator specified by * {@code #host} and {@code #port}, waiting for the {@code timeout} period * before giving-up, or an infinite amount of time if {@code timeout} is &le; * 0. * * @param timeout * the timeout period in milliseconds to wait for the connection * @return {@code true} if the connection is established successfully, else * {@code false}. */ protected boolean _connect(long timeout) { ConnectFuture connFuture = this.connector.connect(new InetSocketAddress( this.host, this.port)); if (timeout > 0) { if (!connFuture.awaitUninterruptibly(timeout)) { return false; } } else { connFuture.awaitUninterruptibly(); } if (!connFuture.isConnected()) { return false; } try { log.info("Connecting to {}:{}.", this.host, Integer.valueOf(this.port)); this.session = connFuture.getSession(); } catch (RuntimeIoException ioe) { log.error(String.format("Could not create session to aggregator %s:%d.", this.host, Integer.valueOf(this.port)), ioe); return false; } return true; } /** * Disconnects from the aggregator, destroying any sessions and executor * filters that are already created. Resets the connection state. */ protected void _disconnect() { IoSession currentSession = this.session; if (currentSession != null && !currentSession.isClosing()) { log.info("Closing connection to aggregator at {}.", currentSession.getRemoteAddress()); currentSession.close(true); this.session = null; this.sentHandshake = null; this.receivedHandshake = null; this.canSendSamples = false; for (ConnectionListener listener : this.connectionListeners) { listener.connectionInterrupted(this); } } } /** * Registers the listener to receive connection-related events. No effect if * the listener is already registered. * * @param listener * the listener to add. */ public void addConnectionListener(ConnectionListener listener) { if (!this.connectionListeners.contains(listener)) { this.connectionListeners.add(listener); } } /** * Unregisters the listener from receiving connection-related events. No * effect if the listener is not registered. * * @param listener * the listener to remove. */ public void removeConnectionListener(ConnectionListener listener) { if (listener == null) { this.connectionListeners.remove(listener); } } /** * Verifies the received and notifies listeners if the connection is ready to * send samples. If the handshake was invalid, disconnects from the * aggregator. * * @param session * the session that received the message * @param handshakeMessage * the message that was received. */ protected void handshakeMessageReceived(IoSession session, HandshakeMessage handshakeMessage) { log.debug("Received {}", handshakeMessage); this.receivedHandshake = handshakeMessage; Boolean handshakeCheck = this.checkHandshake(); if (handshakeCheck == null) { return; } if (Boolean.TRUE.equals(handshakeCheck)) { this.canSendSamples = true; for (ConnectionListener listener : this.connectionListeners) { listener.readyForSamples(this); } } else if (Boolean.FALSE.equals(handshakeCheck)) { log.warn("Handshakes did not match."); this._disconnect(); } } /** * After the handshake is sent, checks to see if a handshake was received. If * it was, and it was valid, notifies any listeners that the aggregator is * ready to receive samples. * * @param session * the session on which the handshake was sent. * @param handshakeMessage * the handshake message that was sent. */ protected void handshakeMessageSent(IoSession session, HandshakeMessage handshakeMessage) { log.debug("Sent {}", handshakeMessage); this.sentHandshake = handshakeMessage; Boolean handshakeCheck = this.checkHandshake(); if (handshakeCheck == null) { return; } if (Boolean.TRUE.equals(handshakeCheck)) { this.canSendSamples = true; for (ConnectionListener listener : this.connectionListeners) { listener.readyForSamples(this); } } else if (Boolean.FALSE.equals(handshakeCheck)) { log.warn("Handshakes did not match."); this._disconnect(); } } /** * Validates the sent and received handshake messages. If both are present * (sent/received, respectively) and valid, then {@code Boolean.TRUE} is * returned. If {@code null} is returned, then at least one handshake (sent or * received) is missing and the caller may wish to check again in the future. * * @return {@code Boolean.TRUE} if the handshakes are exchanged and valid, * {@code Boolean.FALSE} if the handshakes are exchanged and one or * both are invalid, or {@code null} if one or more handshakes is * missing. */ protected Boolean checkHandshake() { if (this.sentHandshake == null) { log.debug("Sent handshake is null, not checking."); return null; } if (this.receivedHandshake == null) { log.debug("Received handshake is null, not checking."); return null; } if (!this.sentHandshake.equals(this.receivedHandshake)) { log.error( "Handshakes do not match. Closing connection to distributor at {}.", this.session.getRemoteAddress()); boolean prevValue = this.stayConnected; this.stayConnected = false; this._disconnect(); this.stayConnected = prevValue; return Boolean.FALSE; } return Boolean.TRUE; } /** * This is an error in the protocol, since the aggregator should not send * samples to a sensor. * * @param session * the session that received the message. * @param sampleMessage * the sample message received. */ protected void sensorSampleReceived(IoSession session, SampleMessage sampleMessage) { log.error( "Protocol error: Received sample message from the aggregator:\n{}", sampleMessage); this._disconnect(); } /** * Called when the session establishes a connection to the aggregator. Writes * a handshake to the aggregator. * * @param session * the session that connected. */ protected void sensorConnected(IoSession session) { if (this.session == null) { this.session = session; } log.info("Connected to {}.", session.getRemoteAddress()); for (ConnectionListener listener : this.connectionListeners) { listener.connectionEstablished(this); } log.debug("Attempting to write handshake."); this.session.write(HandshakeMessage.getDefaultMessage()); } /** * Called when the session ends. If {@code #stayConnected} is {@code true}, * attempts to reconnect to the aggregator. * * @param session */ protected void sensorDisconnected(IoSession session) { this._disconnect(); while (this.stayConnected) { log.info("Reconnecting to aggregator at {}:{}", this.host, Integer.valueOf(this.port)); try { Thread.sleep(this.connectionRetryDelay); } catch (InterruptedException ie) { // Ignored } if (this.connect(this.connectionTimeout)) { return; } } this.finishConnection(); } /** * Cleans-up any session-related constructs when this interface will no longer * attempt connections to the aggregator. Notifies listener that the * connection has ended permanently. */ protected void finishConnection() { this.connector.dispose(); this.connector = null; for (ConnectionListener listener : this.connectionListeners) { listener.connectionEnded(this); } if (this.executors != null) { this.executors.destroy(); } } /** * No action taken, since there is not a keep-alive in the protocol. * * @param session * the session that is idle. * @param idleStatus * whether the sender, receiver, or both are idle. */ protected void sessionIdle(IoSession session, IdleStatus idleStatus) { // Nothing to do } /** * Returns the wait interval (in milliseconds) between attempts to connect to * the aggregator. * * @return the connection retry interval in milliseconds. */ public long getConnectionRetryDelay() { return this.connectionRetryDelay; } /** * Sets the aggregator connection retry interval in milliseconds. * * @param connectionRetryDelay * the new connection retry interval value. */ public void setConnectionRetryDelay(long connectionRetryDelay) { this.connectionRetryDelay = connectionRetryDelay; } /** * Indicates whether this {@code SensorAggregatorInterface} will automatically * reconnect when the connection is lost. This value is {@code false} by * default. * * @return {@code true} if an automatic reconnect will be attempted, else * {@code false}. */ public boolean isStayConnected() { return this.stayConnected; } /** * Sets whether or not this {@code SensorAggregatorInterface} will * automatically reconnect when the connection is lost. * * @param stayConnected * the new value. */ public void setStayConnected(boolean stayConnected) { this.stayConnected = stayConnected; } /** * Indicates whether this {@code SensorAggregatorInterface} should disconnect * when an exception is caught. The default value is true. * * @return {@code true} if exceptions will cause a disconnect event. */ public boolean isDisconnectOnException() { return this.disconnectOnException; } /** * Sets whether this {@code SensorAggregatorInterface} should disconnect when * exceptions are encountered. * * @param disconnectOnException * the new value. */ public void setDisconnectOnException(boolean disconnectOnException) { this.disconnectOnException = disconnectOnException; } /** * Returns the configured hostname for the aggregator. * * @return the configured hostname for the aggregator, or {@code null} if none * is set. */ public String getHost() { return this.host; } /** * Sets the hostname/IP address for the aggregator. Changes to this value only * take effect on the next attempt to connect. * * @param host * the new hostname/IP address for the aggregator. */ public void setHost(String host) { this.host = host; } /** * Returns the configured port number for the aggregator. * * @return the configured port number for the aggregator, or -1 if it has not * been set. */ public int getPort() { return this.port; } /** * Sets the port number for the aggregator. Changes to this value will not * take effect until the next connection attempt. * * @param port */ public void setPort(int port) { this.port = port; } /** * Simply logs that a sample was sent. * * @param session * the session on which the message was sent. * @param sampleMessage * the sample that was sent. */ protected void sensorSampleSent(IoSession session, SampleMessage sampleMessage) { log.debug("Sent {}", sampleMessage); } /** * Sends a sample to the aggregator. * * @param sampleMessage * the sample to send * @return {@code true} if the sample was written, else {@code false}. */ public boolean sendSample(SampleMessage sampleMessage) { if (!this.canSendSamples) { log.warn("Cannot send samples."); return false; } if (this.session.getScheduledWriteMessages() > this.maxOutstandingSamples) { log.warn("Buffer full, cannot send sample."); return false; } this.session.write(sampleMessage); return true; } /** * Responds to exceptions and errors on the aggregator session. If * {@code #disconnectOnException} is {@code true}, then disconnects from the * aggregator. An OutOfMemory error will force a JVM exit. * * @param session * the session that threw the exception or error. * @param cause * the Throwable that was thrown. */ protected void exceptionCaught(IoSession session, Throwable cause) { log.error("Exception while communicating with " + this + ".", cause); // Nothing to do if we have no memory if (cause instanceof OutOfMemoryError) { System.exit(1); } if (this.disconnectOnException) { this._disconnect(); } } /** * Returns {@code true} if the connection is ready to send sample messages. * Classes that wish to be notified asynchronously when samples can be sent, * should register as a {@code ConnectionListener}. * * @return {@code true} if samples can be sent, else {@code false}. */ public boolean isCanSendSamples() { if (!this.canSendSamples || this.session == null) { return false; } return this.session.getScheduledWriteMessages() < this.maxOutstandingSamples; } /** * The maximum number of sample messages that are allowed to be buffered * before causing a send failure. * * @return the current maximum number of bufferable sample messages. */ public int getMaxOutstandingSamples() { return this.maxOutstandingSamples; } /** * Sets the maximum number of sample messages allowed to be buffered. * * @param maxOutstandingSamples * the new maximum value. */ public void setMaxOutstandingSamples(int maxOutstandingSamples) { this.maxOutstandingSamples = maxOutstandingSamples; } @Override public String toString() { return "Sensor-Aggregator Interface @ " + this.host + ":" + this.port; } }
src/main/java/com/owlplatform/sensor/SensorAggregatorInterface.java
/* * Owl Platform Sensor-Aggregator Library for Java * Copyright (C) 2012 Robert Moore and the Owl Platform * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.owlplatform.sensor; import java.net.InetSocketAddress; import java.util.concurrent.ConcurrentLinkedQueue; import org.apache.mina.core.RuntimeIoException; import org.apache.mina.core.future.ConnectFuture; import org.apache.mina.core.session.IdleStatus; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolCodecFilter; import org.apache.mina.filter.executor.ExecutorFilter; import org.apache.mina.transport.socket.SocketConnector; import org.apache.mina.transport.socket.nio.NioSocketConnector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.owlplatform.common.SampleMessage; import com.owlplatform.sensor.listeners.ConnectionListener; import com.owlplatform.sensor.protocol.codecs.AggregatorSensorProtocolCodecFactory; import com.owlplatform.sensor.protocol.messages.HandshakeMessage; /** * A convenience class for interfacing with aggregators as a sensor/hub. Since * most sensors are implemented in C/C++, this class is primarily used by * Aggregators to forward sensor data to another aggregator. * * @author Robert Moore * */ public class SensorAggregatorInterface { /** * A wrapper to take hide the IOAdapter events from classes using the * SensorAggregatorInterface. * * @author Robert Moore * */ private static final class AdapterHandler implements SensorIoAdapter { /** * The actual object that will respond to events. */ private final SensorAggregatorInterface parent; /** * Creates a new AdapterHandler with the specified * {@code SensorAggregatorInterface} to actually handle events. * * @param parent * the real event handler */ public AdapterHandler(SensorAggregatorInterface parent) { if (parent == null) { throw new IllegalArgumentException( "SensorAggregatorInterface cannot be null"); } this.parent = parent; } @Override public void exceptionCaught(IoSession session, Throwable cause) { this.parent.exceptionCaught(session, cause); } @Override public void sensorConnected(IoSession session) { this.parent.sensorConnected(session); } @Override public void sensorDisconnected(IoSession session) { this.parent.sensorDisconnected(session); } @Override public void handshakeMessageReceived(IoSession session, HandshakeMessage handshakeMessage) { this.parent.handshakeMessageReceived(session, handshakeMessage); } @Override public void handshakeMessageSent(IoSession session, HandshakeMessage handshakeMessage) { this.parent.handshakeMessageSent(session, handshakeMessage); } @Override public void sensorSampleReceived(IoSession session, SampleMessage sampleMessage) { this.parent.sensorSampleReceived(session, sampleMessage); } @Override public void sensorSampleSent(IoSession session, SampleMessage sampleMessage) { this.parent.sensorSampleSent(session, sampleMessage); } @Override public void sessionIdle(IoSession session, IdleStatus idleStatus) { this.parent.sessionIdle(session, idleStatus); } } /** * Logging facility for this class. */ private static final Logger log = LoggerFactory .getLogger(SensorAggregatorInterface.class); /** * The object that will pass events to this SensorAggregatorInterface. Used to * hide interface methods. */ private final AdapterHandler handler = new AdapterHandler(this); /** * The handshake sent to the aggregator. */ private HandshakeMessage sentHandshake; /** * The handshake received from the aggregator. */ private HandshakeMessage receivedHandshake; /** * Indicates whether handshakes have been exchanged/checked and the aggregator * can receive sample messages. */ protected boolean canSendSamples = false; /** * How long to wait between connection attempts to the aggregator, in * milliseconds. */ protected long connectionRetryDelay = 10000; /** * Whether or not to try and stay connected to the aggregator. */ protected boolean stayConnected = false; /** * Whether or not to disconnect from the aggregator if an exception is thrown. */ protected boolean disconnectOnException = true; /** * The hostname or IP address of the aggregator. */ private String host; /** * The port number the aggregator is listening on for sensors. */ private int port = -1; /** * The session of the connected aggregator, or {@code null} if no connection * is established. */ private IoSession session; /** * SocketConnector used to connect to the aggregator. */ private SocketConnector connector; /** * IoHandler used by this aggregator interface. */ private SensorIoHandler ioHandler = new SensorIoHandler(this.handler); /** * List (queue) of listeners for connection events for this aggregator * interface. */ private ConcurrentLinkedQueue<ConnectionListener> connectionListeners = new ConcurrentLinkedQueue<ConnectionListener>(); /** * Number of outstanding (buffered) sample messages to be sent on the * Aggregator's session. */ private int maxOutstandingSamples = Integer.MAX_VALUE; /** * A MINA filter containing a thread pool for executing message events * separate from the IO thread. */ private ExecutorFilter executors; /** * How long to wait for a connection to the aggregator to be established. */ protected long connectionTimeout = 1000l; /** * Configures the IO connector to establish a connection to the aggregator. * * @return {@code true} if the connector was created successfully, else * {@code false}. */ protected boolean setConnector() { if (this.host == null) { log.error("No host value set, cannot set up socket connector."); return false; } if (this.port < 0 || this.port > 65535) { log.error("Port value is invalid {}.", Integer.valueOf(this.port)); return false; } // Disconnect if already connected if (this.connector != null) { boolean tmp = this.stayConnected; this.stayConnected = false; this._disconnect(); this.stayConnected = tmp; } this.executors = new ExecutorFilter(1); this.connector = new NioSocketConnector(); this.connector.getSessionConfig().setTcpNoDelay(true); if (!this.connector.getFilterChain().contains( AggregatorSensorProtocolCodecFactory.CODEC_NAME)) { this.connector.getFilterChain().addLast( AggregatorSensorProtocolCodecFactory.CODEC_NAME, new ProtocolCodecFilter(new AggregatorSensorProtocolCodecFactory( false))); } this.connector.getFilterChain().addLast("ExecutorPool", this.executors); this.connector.setHandler(this.ioHandler); log.debug("Connector set up successfully."); return true; } /** * Initiates a connection to the Aggregator (if it is not yet connected). If * {@code #stayConnected} is {@code true}, then this method will NOT return * until a connection is established or the timeout is exceeded. A timeout of * 0 means the configured timeout value will be used. * * @param maxWait * how long to wait (in milliseconds) for the connection to * @return {@code true} if the connection is established within the timeout * period, else {@code false}. */ public boolean connect(long maxWait) { long timeout = maxWait; if (timeout <= 0) { timeout = this.connectionTimeout; } if (this.connector == null) { if (!this.setConnector()) { log.error("Unable to set up connection to the aggregator."); return false; } } if (this.session != null) { log.error("Already connected!"); return false; } long waitTime = timeout; do { long startAttempt = System.currentTimeMillis(); this.connector.setConnectTimeoutMillis(waitTime-5); if (this._connect(waitTime)) { log.debug("Connection succeeded!"); return true; } if (this.stayConnected) { long retryDelay = this.connectionRetryDelay; if (timeout < this.connectionRetryDelay * 2) { retryDelay = timeout / 2; if (retryDelay < 500) { retryDelay = 500; } } try { log.warn(String.format( "Connection to %s:%d failed, waiting %dms before retrying.", this.host, Integer.valueOf(this.port), Long.valueOf(retryDelay))); Thread.sleep(retryDelay); } catch (InterruptedException ie) { // Ignored } waitTime = waitTime - (System.currentTimeMillis() - startAttempt); } } while (this.stayConnected && waitTime > 0); this._disconnect(); this.finishConnection(); return false; } /** * Initiates a connection to the Aggregator (if it is not yet connected). If * {@code #stayConnected} is {@code true}, then this method will NOT return * until a connection is established. If callers wish to remain connected to * the aggregator, it is best to call {@code #setStayConnected(true)} only * after calling this method. * * This method has been replaced by {@link #connect(long)}, and is equivalent * to calling {@code #connect(0)}. * * @return {@code true} if the connection is established, else {@code false}. */ @Deprecated public boolean doConnectionSetup() { return this.connect(0); } /** * Shuts down this connection to the aggregator. This method has been replaced * by {@link #disconnect()}. */ @Deprecated public void doConnectionTearDown() { this.disconnect(); } /** * Disconnects from the aggregator if already connected. */ public void disconnect() { // Make sure we don't automatically reconnect this.stayConnected = false; this._disconnect(); } /** * Establishes a connection to the remote aggregator specified by * {@code #host} and {@code #port}, waiting for the {@code timeout} period * before giving-up, or an infinite amount of time if {@code timeout} is &le; * 0. * * @param timeout * the timeout period in milliseconds to wait for the connection * @return {@code true} if the connection is established successfully, else * {@code false}. */ protected boolean _connect(long timeout) { ConnectFuture connFuture = this.connector.connect(new InetSocketAddress( this.host, this.port)); if (timeout > 0) { if (!connFuture.awaitUninterruptibly(timeout)) { return false; } } else { connFuture.awaitUninterruptibly(); } if (!connFuture.isConnected()) { return false; } try { log.info("Connecting to {}:{}.", this.host, Integer.valueOf(this.port)); this.session = connFuture.getSession(); } catch (RuntimeIoException ioe) { log.error(String.format("Could not create session to aggregator %s:%d.", this.host, Integer.valueOf(this.port)), ioe); return false; } return true; } /** * Disconnects from the aggregator, destroying any sessions and executor * filters that are already created. Resets the connection state. */ protected void _disconnect() { if (this.session != null) { log.info("Closing connection to aggregator at {}.", this.session.getRemoteAddress()); this.session.close(true); this.session = null; this.sentHandshake = null; this.receivedHandshake = null; this.canSendSamples = false; for (ConnectionListener listener : this.connectionListeners) { listener.connectionInterrupted(this); } } } /** * Registers the listener to receive connection-related events. No effect if * the listener is already registered. * * @param listener * the listener to add. */ public void addConnectionListener(ConnectionListener listener) { if (!this.connectionListeners.contains(listener)) { this.connectionListeners.add(listener); } } /** * Unregisters the listener from receiving connection-related events. No * effect if the listener is not registered. * * @param listener * the listener to remove. */ public void removeConnectionListener(ConnectionListener listener) { if (listener == null) { this.connectionListeners.remove(listener); } } /** * Verifies the received and notifies listeners if the connection is ready to * send samples. If the handshake was invalid, disconnects from the * aggregator. * * @param session * the session that received the message * @param handshakeMessage * the message that was received. */ protected void handshakeMessageReceived(IoSession session, HandshakeMessage handshakeMessage) { log.debug("Received {}", handshakeMessage); this.receivedHandshake = handshakeMessage; Boolean handshakeCheck = this.checkHandshake(); if (handshakeCheck == null) { return; } if (Boolean.TRUE.equals(handshakeCheck)) { this.canSendSamples = true; for (ConnectionListener listener : this.connectionListeners) { listener.readyForSamples(this); } } else if (Boolean.FALSE.equals(handshakeCheck)) { log.warn("Handshakes did not match."); this._disconnect(); } } /** * After the handshake is sent, checks to see if a handshake was received. If * it was, and it was valid, notifies any listeners that the aggregator is * ready to receive samples. * * @param session * the session on which the handshake was sent. * @param handshakeMessage * the handshake message that was sent. */ protected void handshakeMessageSent(IoSession session, HandshakeMessage handshakeMessage) { log.debug("Sent {}", handshakeMessage); this.sentHandshake = handshakeMessage; Boolean handshakeCheck = this.checkHandshake(); if (handshakeCheck == null) { return; } if (Boolean.TRUE.equals(handshakeCheck)) { this.canSendSamples = true; for (ConnectionListener listener : this.connectionListeners) { listener.readyForSamples(this); } } else if (Boolean.FALSE.equals(handshakeCheck)) { log.warn("Handshakes did not match."); this._disconnect(); } } /** * Validates the sent and received handshake messages. If both are present * (sent/received, respectively) and valid, then {@code Boolean.TRUE} is * returned. If {@code null} is returned, then at least one handshake (sent or * received) is missing and the caller may wish to check again in the future. * * @return {@code Boolean.TRUE} if the handshakes are exchanged and valid, * {@code Boolean.FALSE} if the handshakes are exchanged and one or * both are invalid, or {@code null} if one or more handshakes is * missing. */ protected Boolean checkHandshake() { if (this.sentHandshake == null) { log.debug("Sent handshake is null, not checking."); return null; } if (this.receivedHandshake == null) { log.debug("Received handshake is null, not checking."); return null; } if (!this.sentHandshake.equals(this.receivedHandshake)) { log.error( "Handshakes do not match. Closing connection to distributor at {}.", this.session.getRemoteAddress()); boolean prevValue = this.stayConnected; this.stayConnected = false; this._disconnect(); this.stayConnected = prevValue; return Boolean.FALSE; } return Boolean.TRUE; } /** * This is an error in the protocol, since the aggregator should not send * samples to a sensor. * * @param session * the session that received the message. * @param sampleMessage * the sample message received. */ protected void sensorSampleReceived(IoSession session, SampleMessage sampleMessage) { log.error( "Protocol error: Received sample message from the aggregator:\n{}", sampleMessage); this._disconnect(); } /** * Called when the session establishes a connection to the aggregator. Writes * a handshake to the aggregator. * * @param session * the session that connected. */ protected void sensorConnected(IoSession session) { if (this.session == null) { this.session = session; } log.info("Connected to {}.", session.getRemoteAddress()); for (ConnectionListener listener : this.connectionListeners) { listener.connectionEstablished(this); } log.debug("Attempting to write handshake."); this.session.write(HandshakeMessage.getDefaultMessage()); } /** * Called when the session ends. If {@code #stayConnected} is {@code true}, * attempts to reconnect to the aggregator. * * @param session */ protected void sensorDisconnected(IoSession session) { this._disconnect(); while (this.stayConnected) { log.info("Reconnecting to aggregator at {}:{}", this.host, Integer.valueOf(this.port)); try { Thread.sleep(this.connectionRetryDelay); } catch (InterruptedException ie) { // Ignored } if (this.connect(this.connectionTimeout)) { return; } } this.finishConnection(); } /** * Cleans-up any session-related constructs when this interface will no longer * attempt connections to the aggregator. Notifies listener that the * connection has ended permanently. */ protected void finishConnection() { this.connector.dispose(); this.connector = null; for (ConnectionListener listener : this.connectionListeners) { listener.connectionEnded(this); } if (this.executors != null) { this.executors.destroy(); } } /** * No action taken, since there is not a keep-alive in the protocol. * * @param session * the session that is idle. * @param idleStatus * whether the sender, receiver, or both are idle. */ protected void sessionIdle(IoSession session, IdleStatus idleStatus) { // Nothing to do } /** * Returns the wait interval (in milliseconds) between attempts to connect to * the aggregator. * * @return the connection retry interval in milliseconds. */ public long getConnectionRetryDelay() { return this.connectionRetryDelay; } /** * Sets the aggregator connection retry interval in milliseconds. * * @param connectionRetryDelay * the new connection retry interval value. */ public void setConnectionRetryDelay(long connectionRetryDelay) { this.connectionRetryDelay = connectionRetryDelay; } /** * Indicates whether this {@code SensorAggregatorInterface} will automatically * reconnect when the connection is lost. This value is {@code false} by * default. * * @return {@code true} if an automatic reconnect will be attempted, else * {@code false}. */ public boolean isStayConnected() { return this.stayConnected; } /** * Sets whether or not this {@code SensorAggregatorInterface} will * automatically reconnect when the connection is lost. * * @param stayConnected * the new value. */ public void setStayConnected(boolean stayConnected) { this.stayConnected = stayConnected; } /** * Indicates whether this {@code SensorAggregatorInterface} should disconnect * when an exception is caught. The default value is true. * * @return {@code true} if exceptions will cause a disconnect event. */ public boolean isDisconnectOnException() { return this.disconnectOnException; } /** * Sets whether this {@code SensorAggregatorInterface} should disconnect when * exceptions are encountered. * * @param disconnectOnException * the new value. */ public void setDisconnectOnException(boolean disconnectOnException) { this.disconnectOnException = disconnectOnException; } /** * Returns the configured hostname for the aggregator. * * @return the configured hostname for the aggregator, or {@code null} if none * is set. */ public String getHost() { return this.host; } /** * Sets the hostname/IP address for the aggregator. Changes to this value only * take effect on the next attempt to connect. * * @param host * the new hostname/IP address for the aggregator. */ public void setHost(String host) { this.host = host; } /** * Returns the configured port number for the aggregator. * * @return the configured port number for the aggregator, or -1 if it has not * been set. */ public int getPort() { return this.port; } /** * Sets the port number for the aggregator. Changes to this value will not * take effect until the next connection attempt. * * @param port */ public void setPort(int port) { this.port = port; } /** * Simply logs that a sample was sent. * * @param session * the session on which the message was sent. * @param sampleMessage * the sample that was sent. */ protected void sensorSampleSent(IoSession session, SampleMessage sampleMessage) { log.debug("Sent {}", sampleMessage); } /** * Sends a sample to the aggregator. * * @param sampleMessage * the sample to send * @return {@code true} if the sample was written, else {@code false}. */ public boolean sendSample(SampleMessage sampleMessage) { if (!this.canSendSamples) { log.warn("Cannot send samples."); return false; } if (this.session.getScheduledWriteMessages() > this.maxOutstandingSamples) { log.warn("Buffer full, cannot send sample."); return false; } this.session.write(sampleMessage); return true; } /** * Responds to exceptions and errors on the aggregator session. If * {@code #disconnectOnException} is {@code true}, then disconnects from the * aggregator. An OutOfMemory error will force a JVM exit. * * @param session * the session that threw the exception or error. * @param cause * the Throwable that was thrown. */ protected void exceptionCaught(IoSession session, Throwable cause) { log.error("Exception while communicating with " + this + ".", cause); // Nothing to do if we have no memory if (cause instanceof OutOfMemoryError) { System.exit(1); } if (this.disconnectOnException) { this._disconnect(); } } /** * Returns {@code true} if the connection is ready to send sample messages. * Classes that wish to be notified asynchronously when samples can be sent, * should register as a {@code ConnectionListener}. * * @return {@code true} if samples can be sent, else {@code false}. */ public boolean isCanSendSamples() { if (!this.canSendSamples || this.session == null) { return false; } return this.session.getScheduledWriteMessages() < this.maxOutstandingSamples; } /** * The maximum number of sample messages that are allowed to be buffered * before causing a send failure. * * @return the current maximum number of bufferable sample messages. */ public int getMaxOutstandingSamples() { return this.maxOutstandingSamples; } /** * Sets the maximum number of sample messages allowed to be buffered. * * @param maxOutstandingSamples * the new maximum value. */ public void setMaxOutstandingSamples(int maxOutstandingSamples) { this.maxOutstandingSamples = maxOutstandingSamples; } @Override public String toString() { return "Sensor-Aggregator Interface @ " + this.host + ":" + this.port; } }
Using stack reference to session on disconnect.
src/main/java/com/owlplatform/sensor/SensorAggregatorInterface.java
Using stack reference to session on disconnect.
Java
apache-2.0
052cae36b4d12bcb5bfa4608c15d8ff354ae2251
0
akjava/gwt-bvh
package com.akjava.gwt.bvh.client; /* * Copyright (C) 2011 [email protected] * * 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. */ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.akjava.bvh.client.BVH; import com.akjava.bvh.client.BVHNode; import com.akjava.bvh.client.BVHParser; import com.akjava.bvh.client.BVHParser.ParserListener; import com.akjava.bvh.client.Channels; import com.akjava.bvh.client.NameAndChannel; import com.akjava.bvh.client.Vec3; import com.akjava.gwt.bvh.client.list.BVHFileWidget; import com.akjava.gwt.bvh.client.list.DataList; import com.akjava.gwt.bvh.client.list.DataList.ChangeSelectionListener; import com.akjava.gwt.bvh.client.list.DataList.DataListRenderer; import com.akjava.gwt.html5.client.HTML5InputRange; import com.akjava.gwt.html5.client.extra.HTML5Builder; import com.akjava.gwt.html5.client.file.File; import com.akjava.gwt.html5.client.file.FileHandler; import com.akjava.gwt.html5.client.file.FileReader; import com.akjava.gwt.html5.client.file.FileUtils; import com.akjava.gwt.lib.client.widget.cell.util.Benchmark; import com.akjava.gwt.three.client.THREE; import com.akjava.gwt.three.client.core.Geometry; import com.akjava.gwt.three.client.core.Intersect; import com.akjava.gwt.three.client.core.Matrix4; import com.akjava.gwt.three.client.core.Object3D; import com.akjava.gwt.three.client.core.Projector; import com.akjava.gwt.three.client.core.Vector3; import com.akjava.gwt.three.client.gwt.Clock; import com.akjava.gwt.three.client.gwt.Object3DUtils; import com.akjava.gwt.three.client.gwt.SimpleDemoEntryPoint; import com.akjava.gwt.three.client.lights.Light; import com.akjava.gwt.three.client.objects.Mesh; import com.akjava.gwt.three.client.renderers.WebGLRenderer; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.JsArray; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ChangeHandler; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.MouseMoveEvent; import com.google.gwt.event.dom.client.MouseUpEvent; import com.google.gwt.event.dom.client.MouseUpHandler; import com.google.gwt.http.client.Request; import com.google.gwt.http.client.RequestBuilder; import com.google.gwt.http.client.RequestCallback; import com.google.gwt.http.client.RequestException; import com.google.gwt.http.client.Response; import com.google.gwt.http.client.URL; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.CheckBox; import com.google.gwt.user.client.ui.FileUpload; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.Panel; import com.google.gwt.user.client.ui.PopupPanel; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; /** * Entry point classes define <code>onModuleLoad()</code>. */ public class GWTBVH extends SimpleDemoEntryPoint { final Projector projector=THREE.Projector(); @Override public void onMouseClick(ClickEvent event) { int x=event.getX(); int y=event.getY(); /* if(inEdge(x,y)){ screenMove(x,y); return; }*/ JsArray<Intersect> intersects=projector.pickIntersects(event.getX(), event.getY(), screenWidth, screenHeight, camera,scene); for(int i=0;i<intersects.length();i++){ Intersect sect=intersects.get(i); select(sect.getObject()); break; } } Object3D selectedObject; private void select(Object3D selected){ selectedObject=selected; meshScaleX.setValue((int) (selectedObject.getScale().getX()*10)); meshScaleY.setValue((int) (selectedObject.getScale().getY()*10)); meshScaleZ.setValue((int) (selectedObject.getScale().getZ()*10)); positionX.setValue((int) (selectedObject.getPosition().getX()*10)); positionY.setValue((int) (selectedObject.getPosition().getY()*10)); positionZ.setValue((int) (selectedObject.getPosition().getZ()*10)); } @Override public void onMouseMove(MouseMoveEvent event) { // TODO Auto-generated method stub } private int defaultZ=200; Map<String,Vector3> boneSizeMap=new HashMap<String,Vector3>(); private Object3D rootGroup,boneContainer,backgroundContainer; @Override public void initializeOthers(WebGLRenderer renderer) { cameraY=10; defaultZoom=5; canvas.setClearColorHex(0xcccccc); scene.add(THREE.AmbientLight(0x888888)); Light pointLight = THREE.PointLight(0xffffff); pointLight.setPosition(0, 10, 300); scene.add(pointLight); doLoad("80_72"); rootGroup=THREE.Object3D(); scene.add(rootGroup); backgroundContainer=THREE.Object3D(); rootGroup.add(backgroundContainer); Geometry geo=THREE.PlaneGeometry(100, 100,20,20); Mesh mesh=THREE.Mesh(geo, THREE.MeshBasicMaterial().color(0x666666).wireFrame(true).build()); //mesh.setPosition(0, -17, 0); mesh.setRotation(Math.toRadians(-90), 0, 0); backgroundContainer.add(mesh); boneContainer=THREE.Object3D(); rootGroup.add(boneContainer); /* BVHParser parser=new BVHParser(); //String singleBvh=Bundles.INSTANCE.single_basic().getText(); //String singleBvh=Bundles.INSTANCE.twolink_n_rz().getText(); //String singleBvh=Bundles.INSTANCE.twolink_full().getText(); //String singleBvh=Bundles.INSTANCE.fourlink_branch().getText(); String singleBvh=Bundles.INSTANCE.twelve01().getText(); try { jointMap=new HashMap<String,Object3D>(); bvh = parser.parse(singleBvh); BVHNode node=bvh.getHiearchy(); root=THREE.Object3D(); scene.add(root); doLog(root,node); // //jointMap.get("Hips").setRotation(Math.toRadians(7.1338),Math.toRadians(-1.8542),Math.toRadians( -7.8190)); //doPose(bvh,"-0.3899 17.5076 7.8007 0 0 0 0 0 0 -21 0 0 0 0 0 0 0 0 0 0 0 0 0 0 21 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -16 0 0 21 0 0 11 0 0 0 -8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0"); //doPose(bvh,"-0.3899 17.5076 7.8007 -7.8190 -1.8542 7.1338 0.0000 0.0000 0.0000 -20.0095 -34.8717 23.1818 0.0543 -1.5040 -4.1368 -5.1851 39.6153 -34.2618 0.1274 2.3012 6.3387 0.0000 0.0000 0.0000 27.9815 23.6282 8.6217 -0.0094 -0.6245 1.7162 0.4741 -16.6281 -18.3131 -0.0041 -0.4123 1.1330 4.5929 -0.1445 3.0131 1.7537 0.3513 -8.5234 -0.7284 -0.1282 -10.7842 -14.7495 -15.2891 1.4491 15.1151 -23.2999 16.3175 5.0944 -11.3477 8.3590 -0.0000 -0.0000 0.0000 -91.7499 11.2503 9.6316 11.7870 -19.4845 -2.0307 -0.0000 -0.0000 23.6415 17.7243 -7.2146 -2.2985 -7.1250 0.0000 -0.0000 -6.6264 22.4256 3.6210 -0.0000 -0.0000 0.0000 92.9366 -10.7837 -16.0742 -9.0830 15.2927 -1.2219 0.0000 0.0000 58.8395 3.1909 -29.5170 -1.5733 7.1250 -0.0000 -0.0000 36.2824 -55.5617 -10.3909"); //doPose(bvh,"-0.5011 17.6282 7.6163 -6.2586 -15.2051 5.4723 0.0000 0.0000 0.0000 -21.3981 -26.0192 22.4790 0.0292 -1.1029 -3.0320 -3.3535 38.5451 -41.4272 0.6169 5.0265 13.9840 0.0000 0.0000 0.0000 24.7397 22.1958 5.0034 -0.0966 -2.0046 5.5183 -0.3873 -3.4522 -13.5373 -0.2228 3.0387 -8.3865 3.1625 -2.9263 2.2948 2.9237 -3.5238 -7.9690 1.7270 -1.8496 -9.7328 3.3763 2.5058 -7.4595 13.0244 0.5160 17.4961 3.6704 1.4696 6.5682 -0.0000 0.0000 0.0000 -42.7751 -56.6315 -8.6834 50.4538 -53.1769 -26.5370 -0.0000 0.0000 -77.6575 14.7878 7.4808 1.9684 -7.1250 0.0000 -0.0000 -10.2345 37.5343 1.9047 -0.0000 0.0000 0.0000 76.3877 59.4476 93.5538 -141.2974 47.2822 -102.5201 0.0000 -0.0000 -31.1956 -12.8820 -58.8974 11.0797 7.1250 -0.0000 -0.0000 91.0580 -76.5215 -77.2227"); doPose(bvh,bvh.getMotion().getMotions().get(0)); Matrix4 mx=THREE.Matrix4(); mx.setRotationFromEuler(THREE.Vector3(Math.toRadians(23.1818),Math.toRadians(-34.8717),Math.toRadians(-20.0095)), "ZYX"); Vector3 rot=THREE.Vector3(0, 0, 0); rot.setRotationFromMatrix(mx); double x=Math.toDegrees(rot.getX()); double y=Math.toDegrees(rot.getY()); double z=Math.toDegrees(rot.getZ()); GWT.log(x+","+y+","+z); //jointMap.get("LeftUpLeg").setRotation(rot.getX(), rot.getY(), rot.getZ()); //jointMap.get("LeftUpLeg").setRotation(Math.toRadians(23.1818),Math.toRadians(-34.8717),Math.toRadians(-20.0095)); //jointMap.get("RightUpLeg").getRotation(Math.toRadians(23.1818),Math.toRadians(-34.8717),Math.toRadians(-20.0095)); } catch (InvalidLineException e) { log(e.getMessage()); e.printStackTrace(); } */ // ctime=System.currentTimeMillis(); } private void doZYX(Object3D target,String lastOrder){ Vector3 vec=target.getRotation(); Matrix4 mx=THREE.Matrix4(); mx.setRotationFromEuler(vec, lastOrder); vec.setRotationFromMatrix(mx); } /* private void doPose(BVH bvh,String line){ String[] tmp=line.split(" "); double[] vs=BVHParser.toDouble(tmp); Object3D oldTarget=null; String lastOrder=null; for(int i=0;i<vs.length;i++){ NameAndChannel nchannel=bvh.getNameAndChannels().get(i); lastOrder=nchannel.getOrder(); Object3D target=jointMap.get(nchannel.getName()); switch(nchannel.getChannel()){ case Channels.XROTATION: target.getRotation().setX(Math.toRadians(vs[i])); break; case Channels.YROTATION: target.getRotation().setY(Math.toRadians(vs[i])); break; case Channels.ZROTATION: target.getRotation().setZ(Math.toRadians(vs[i])); break; } if(oldTarget!=null && oldTarget!=target){ doZYX(oldTarget,lastOrder); } oldTarget=target; } doZYX(oldTarget,lastOrder);//do last one }*/ private void doPose(BVH bvh,double[] vs){ Object3D oldTarget=null; String lastOrder=null; for(int i=0;i<vs.length;i++){ NameAndChannel nchannel=bvh.getNameAndChannels().get(i); lastOrder=nchannel.getOrder(); Object3D target=jointMap.get(nchannel.getName()); switch(nchannel.getChannel()){ case Channels.XROTATION: target.getRotation().setX(Math.toRadians(vs[i])); break; case Channels.YROTATION: target.getRotation().setY(Math.toRadians(vs[i])); break; case Channels.ZROTATION: target.getRotation().setZ(Math.toRadians(vs[i])); break; case Channels.XPOSITION: if(translatePosition.getValue()){ target.getPosition().setX(vs[i]); }else{ target.getPosition().setX(0); } break; case Channels.YPOSITION: if(translatePosition.getValue()){ target.getPosition().setY(vs[i]); }else{ target.getPosition().setY(0); } break; case Channels.ZPOSITION: if(translatePosition.getValue()){ target.getPosition().setZ(vs[i]); }else{ target.getPosition().setZ(0); } break; } if(oldTarget!=null && oldTarget!=target){ doZYX(oldTarget,lastOrder); } oldTarget=target; } doZYX(oldTarget,lastOrder);//do last one } private Map<String,Object3D> jointMap; public Mesh createLine(Vec3 from,Vec3 to){ Geometry lineG = THREE.Geometry(); lineG.vertices().push(THREE.Vertex(THREE.Vector3(from.getX(), from.getY(), from.getY()))); lineG.vertices().push(THREE.Vertex(THREE.Vector3(to.getX(), to.getY(), to.getZ()))); Mesh line=THREE.Line(lineG, THREE.LineBasicMaterial().color(0).build()); return line; } public void doLog(Object3D parent,BVHNode node){ GWT.log(node.getName()+","+node.getOffset()+",endsite:"+node.getEndSite()); GWT.log(node.getChannels().toString()); Object3D group=THREE.Object3D(); Mesh mesh=THREE.Mesh(THREE.CubeGeometry(.3,.3, .3), THREE.MeshLambertMaterial().color(0xffffff).build()); group.add(mesh); mesh.setName(node.getName()); //initial position group.setPosition(THREE.Vector3(node.getOffset().getX(), node.getOffset().getY(), node.getOffset().getZ())); jointMap.put(node.getName(), group); Mesh l1=createLine(new Vec3(),node.getOffset()); parent.add(l1); if(node.getEndSite()!=null){ Mesh end=THREE.Mesh(THREE.CubeGeometry(.1, .1, .1), THREE.MeshBasicMaterial().color(0x008800).build()); end.setPosition(THREE.Vector3(node.getEndSite().getX(), node.getEndSite().getY(), node.getEndSite().getZ())); group.add(end); Geometry lineG = THREE.Geometry(); lineG.vertices().push(THREE.Vertex(THREE.Vector3(0, 0, 0))); lineG.vertices().push(THREE.Vertex(THREE.Vector3(node.getEndSite().getX(), node.getEndSite().getY(), node.getEndSite().getZ()))); Mesh line=THREE.Line(lineG, THREE.LineBasicMaterial().color(0).build()); group.add(line); } parent.add(group); List<BVHNode> joints=node.getJoints(); if(joints!=null){ for(BVHNode joint:joints){ doLog(group,joint); } } } private Label loadingLabel=new Label(); private CheckBox translatePosition; private HTML5InputRange positionYRange; private HTML5InputRange meshScaleX; private HTML5InputRange meshScaleY; private HTML5InputRange meshScaleZ; private HTML5InputRange positionX; private HTML5InputRange positionY; private HTML5InputRange positionZ; private PopupPanel bottomPanel; protected boolean playing; private HTML5InputRange positionXRange; private HTML5InputRange positionZRange; private CheckBox drawBackground; private void loadBVH(String path){ Benchmark.start("load"); RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(path)); loadingLabel.setText("loading-data"); try { builder.sendRequest(null, new RequestCallback() { @Override public void onResponseReceived(Request request, Response response) { String bvhText=response.getText(); //log("loaded:"+Benchmark.end("load")); //useless spend allmost time with request and spliting. parseBVH(bvhText); loadingLabel.setText(""); } @Override public void onError(Request request, Throwable exception) { Window.alert("load faild:"); } }); } catch (RequestException e) { log(e.getMessage()); e.printStackTrace(); } } private void setEmptyBone(){ if(boneRoot!=null){ boneContainer.remove(boneRoot); } boneRoot=null; bvh=null; } private void parseBVH(String bvhText){ final BVHParser parser=new BVHParser(); jointMap=new HashMap<String,Object3D>(); parser.parseAsync(bvhText, new ParserListener() { @Override public void onSuccess(BVH bv) { bvh=bv; bvh.setSkips(skipFrames); BVHNode node=bvh.getHiearchy(); if(boneRoot!=null){ boneContainer.remove(boneRoot); } boneRoot=THREE.Object3D(); boneContainer.add(boneRoot); doLog(boneRoot,node); int poseIndex=0; if(ignoreFirst.getValue()){ poseIndex=1; } clock.update(); updatePoseIndex(poseIndex); doPose(bvh,bvh.getFrameAt(poseIndex)); currentFrameRange.setMax(bvh.getFrames()-1); } @Override public void onFaild(String message) { log(message); } }); } /* timer style * parser.initialize(); bvhText=bvhText.replace("\r", ""); final String lines[]=bvhText.split("\n"); final int pLine=lines.length/20; Timer timer=new Timer(){ int index=0; boolean parsing; @Override public synchronized void run() { if(parsing){ return; } parsing=true; loadingLabel.setText(index+"/"+lines.length); GWT.log("called:"+index+","+pLine); try { parser.parseLines(lines, index, index+pLine); if(index>=lines.length){ //done bvh=parser.getBvh(); BVHNode node=bvh.getHiearchy(); if(root!=null){ scene.remove(root); } root=THREE.Object3D(); scene.add(root); doLog(root,node); doPose(bvh,bvh.getMotion().getMotions().get(0)); poseIndex=0; cancel(); }else{ index+=pLine; } } catch (InvalidLineException e) { log(e.getMessage()); } parsing=false; } }; timer.scheduleRepeating(20); */ private long getFrameTime(int index){ long time=(long) (bvh.getFrameTime()*index*1000); return time; } private double getPlaySpeed(){ String v=speedBox.getItemText(speedBox.getSelectedIndex()); double r=1; try{ r=Double.parseDouble(v.substring(2)); }catch(Exception e){} return r; } private double playSpeed=1; private void createBottomPanel(){ bottomPanel = new PopupPanel(); bottomPanel.setVisible(true); bottomPanel.setSize("650px", "40px"); VerticalPanel main=new VerticalPanel(); bottomPanel.add(main); bottomPanel.show(); HorizontalPanel upperPanel=new HorizontalPanel(); upperPanel.setVerticalAlignment(HorizontalPanel.ALIGN_MIDDLE); main.add(upperPanel); upperPanel.add(new Label("Speed")); speedBox = new ListBox(); speedBox.addItem("x 0.25"); speedBox.addItem("x 0.5"); speedBox.addItem("x 1"); speedBox.addItem("x 2"); speedBox.addItem("x 4"); speedBox.addItem("x 10"); speedBox.setSelectedIndex(2); speedBox.addChangeHandler(new ChangeHandler() { @Override public void onChange(ChangeEvent event) { playSpeed=getPlaySpeed(); } }); upperPanel.add(speedBox); abLoopCheck = new CheckBox("A/B Loop"); upperPanel.add(abLoopCheck); final Button asA=new Button("A:"); asA.setWidth("60px"); upperPanel.add(asA); asA.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { aFrame=currentFrameRange.getValue(); asA.setText("A:"+(aFrame+1)); } }); final Button asB=new Button("B:"); asB.setWidth("60px"); upperPanel.add(asB); asB.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { bFrame=currentFrameRange.getValue(); asB.setText("B:"+(bFrame+1)); } }); upperPanel.add(new Label("Skip every frame:")); final TextBox skipFrameBox=new TextBox(); skipFrameBox.setWidth("40px"); upperPanel.add(skipFrameBox); Button updateSkipBt=new Button("Update skips"); upperPanel.add(updateSkipBt); updateSkipBt.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { String v=skipFrameBox.getValue(); int sp=0; try{ sp=Integer.parseInt(v); }catch(Exception e){ } setBvhSkips(sp); } }); HorizontalPanel pPanel=new HorizontalPanel(); main.add(pPanel); pPanel.setVerticalAlignment(HorizontalPanel.ALIGN_MIDDLE); playing=true; final Button playButton=new Button("Play"); playButton.setEnabled(false); final Button stopButton=new Button("Stop"); playButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { clock.update(); //ctime=System.currentTimeMillis()-getFrameTime(); playing=true; playButton.setEnabled(false); stopButton.setEnabled(true); } }); pPanel.add(playButton); stopButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { playing=false; playButton.setEnabled(true); stopButton.setEnabled(false); } }); pPanel.add(stopButton); final Button prevButton=new Button("Prev"); prevButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { int c=currentFrameRange.getValue(); c--; /* if(c==0 && ignoreFirst.getValue()){ c=1; }*/ if(c<0){ c=0; } currentFrameRange.setValue(c); updatePoseIndex(currentFrameRange.getValue()); } }); pPanel.add(prevButton); final Button nextButton=new Button("Next"); nextButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { int c=currentFrameRange.getValue(); c++; if(c>=bvh.getFrames()){ c=bvh.getFrames()-1; } currentFrameRange.setValue(c); updatePoseIndex(currentFrameRange.getValue()); } }); pPanel.add(nextButton); currentFrameRange = new HTML5InputRange(0,1000,0); currentFrameRange.setWidth("420px"); pPanel.add(currentFrameRange); currentFrameRange.addMouseUpHandler(new MouseUpHandler() { @Override public void onMouseUp(MouseUpEvent event) { updatePoseIndex(currentFrameRange.getValue()); } }); currentFrameLabel = new Label(); pPanel.add(currentFrameLabel); super.leftBottom(bottomPanel); } private int aFrame; private int bFrame; private int skipFrames; private void setBvhSkips(int skips){ //TODO //set global for newload skipFrames=skips; //set current bvh bvh.setSkips(skips); updatePoseIndex(0); currentFrameRange.setMax(bvh.getFrames()-1); //update labels } @Override public void createControl(Panel parent) { parent.add(loadingLabel); drawBackground = new CheckBox("Draw Background"); parent.add(drawBackground); drawBackground.setValue(true); translatePosition = new CheckBox("Translate Position"); parent.add(translatePosition); translatePosition.setValue(true); ignoreFirst = new CheckBox("Ignore First Frame(Usually Pose)"); ignoreFirst.setValue(true); parent.add(ignoreFirst); HorizontalPanel h1=new HorizontalPanel(); rotationRange = new HTML5InputRange(-180,180,0); parent.add(HTML5Builder.createRangeLabel("X-Rotate:", rotationRange)); parent.add(h1); h1.add(rotationRange); Button reset=new Button("Reset"); reset.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { rotationRange.setValue(0); } }); h1.add(reset); HorizontalPanel h2=new HorizontalPanel(); rotationYRange = new HTML5InputRange(-180,180,0); parent.add(HTML5Builder.createRangeLabel("Y-Rotate:", rotationYRange)); parent.add(h2); h2.add(rotationYRange); Button reset2=new Button("Reset"); reset2.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { rotationYRange.setValue(0); } }); h2.add(reset2); HorizontalPanel h3=new HorizontalPanel(); rotationZRange = new HTML5InputRange(-180,180,0); parent.add(HTML5Builder.createRangeLabel("Z-Rotate:", rotationZRange)); parent.add(h3); h3.add(rotationZRange); Button reset3=new Button("Reset"); reset3.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { rotationZRange.setValue(0); } }); h3.add(reset3); HorizontalPanel h4=new HorizontalPanel(); positionXRange = new HTML5InputRange(-50,50,0); parent.add(HTML5Builder.createRangeLabel("X-Position:", positionXRange)); parent.add(h4); h4.add(positionXRange); Button reset4=new Button("Reset"); reset4.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { positionXRange.setValue(0); } }); h4.add(reset4); HorizontalPanel h5=new HorizontalPanel(); positionYRange = new HTML5InputRange(-50,50,0); parent.add(HTML5Builder.createRangeLabel("Y-Position:", positionYRange)); parent.add(h5); h5.add(positionYRange); Button reset5=new Button("Reset"); reset5.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { positionYRange.setValue(0); } }); h5.add(reset5); HorizontalPanel h6=new HorizontalPanel(); positionZRange = new HTML5InputRange(-50,50,0); parent.add(HTML5Builder.createRangeLabel("Z-Position:", positionZRange)); parent.add(h6); h6.add(positionZRange); Button reset6=new Button("Reset"); reset6.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { positionZRange.setValue(0); } }); h6.add(reset6); parent.add(new Label("Load BVH File")); FileUpload file=new FileUpload(); file.setHeight("50px"); file.getElement().setAttribute("multiple", "multiple"); file.addChangeHandler(new ChangeHandler() { @Override public void onChange(ChangeEvent event) { //Benchmark.start("load"); JsArray<File> files=FileUtils.toFile(event.getNativeEvent()); for(int i=0;i<files.length();i++){ bvhFileList.add(files.get(i)); } dataList.setDatas(bvhFileList); dataList.setSelection(files.get(0)); //bvhCellList.setRowCount(bvhFileList.size(), true); //bvhCellList.setRowData(bvhFileList); //fileSelectionModel.setSelected(files.get(0), true); /* log("length:"+files.length()); GWT.log(files.get(0).getFileName()); GWT.log(files.get(0).getFileType()); GWT.log(""+files.get(0).getFileSize()); log(event.getNativeEvent()); final FileReader reader=FileReader.createFileReader(); reader.setOnLoad(new FileHandler() { @Override public void onLoad() { //log("load:"+Benchmark.end("load")); //GWT.log(reader.getResultAsString()); parseBVH(reader.getResultAsString()); } }); reader.readAsText(files.get(0),"utf-8"); */ } }); parent.add(file); HorizontalPanel fileControl=new HorizontalPanel(); parent.add(fileControl); Button prevBt=new Button("Prev"); prevBt.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { if(bvhFileList.size()==0){ return; } File file=dataList.getSelection(); int index=bvhFileList.indexOf(file); index--; if(index<0){ index=bvhFileList.size()-1; } dataList.setSelection(bvhFileList.get(index)); } }); fileControl.add(prevBt); Button nextBt=new Button("Next"); nextBt.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { doNextMotion(); } }); fileControl.add(nextBt); fileControl.add(new Label("Auto Play")); loopTime = new ListBox(); loopTime.addItem("None"); loopTime.addItem("1"); loopTime.addItem("3"); loopTime.addItem("10"); loopTime.setSelectedIndex(0); fileControl.add(loopTime); file.setStylePrimaryName("fileborder"); /* meshScaleX = new HTML5InputRange(0,150,3); parent.add(HTML5Builder.createRangeLabel("Scale-x", meshScaleX)); parent.add(meshScaleX); meshScaleY = new HTML5InputRange(0,150,3); parent.add(HTML5Builder.createRangeLabel("Scale-y", meshScaleY)); parent.add(meshScaleY); meshScaleZ = new HTML5InputRange(0,150,3); parent.add(HTML5Builder.createRangeLabel("Scale-z", meshScaleZ)); parent.add(meshScaleZ); positionX = new HTML5InputRange(-150,150,0); parent.add(HTML5Builder.createRangeLabel("Position-x", positionX)); parent.add(positionX); positionY = new HTML5InputRange(-150,150,0); parent.add(HTML5Builder.createRangeLabel("Position-y", positionY)); parent.add(positionY); positionZ = new HTML5InputRange(-150,150,0); parent.add(HTML5Builder.createRangeLabel("Position-z", positionZ)); parent.add(positionZ); */ dataList = new DataList<File>(new DataListRenderer<File>(){ @Override public Widget createWidget(File data,DataList<File> dataList) { return new BVHFileWidget(data,dataList); }}); dataList.setHeight("60px"); parent.add(dataList); dataList.setListener(new ChangeSelectionListener<File>() { @Override public void onChangeSelection(File data) { final FileReader reader=FileReader.createFileReader(); reader.setOnLoad(new FileHandler() { @Override public void onLoad() { parseBVH(reader.getResultAsString()); } }); reader.readAsText(data,"utf-8"); } }); HorizontalPanel dataControls=new HorizontalPanel(); parent.add(dataControls); Button remove=new Button("Remove"); remove.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { if(bvhFileList.size()==0){ return; } File file=dataList.getSelection(); int index=bvhFileList.indexOf(file); bvhFileList.remove(file); if(index>=bvhFileList.size()){ index=0; } dataList.setDatas(bvhFileList); if(bvhFileList.size()!=0){ dataList.setSelection(bvhFileList.get(index)); }else{ setEmptyBone(); } } }); dataControls.add(remove); createBottomPanel(); showControl(); } private void doNextMotion(){ if(bvhFileList.size()==0){ return; } File file=dataList.getSelection(); int index=bvhFileList.indexOf(file); index++; if(index>bvhFileList.size()-1){ index=0; } dataList.setSelection(bvhFileList.get(index)); } protected void doLoad(String itemText) { String[] g_n=itemText.split("_"); loadBVH("bvhs/"+g_n[0]+"/"+itemText+".bvh"); } private HTML5InputRange rotationRange; private HTML5InputRange rotationYRange; private HTML5InputRange rotationZRange; Object3D boneRoot; private BVH bvh; private CheckBox ignoreFirst; //private long ctime; private HTML5InputRange currentFrameRange; private Label currentFrameLabel; //private int poseIndex; private void updatePoseIndex(int index){ //poseIndex=index; currentFrameRange.setValue(index); currentFrameLabel.setText((index+1)+"/"+bvh.getFrames()); doPose(bvh,bvh.getFrameAt(index)); } Clock clock=new Clock(); private List<File> bvhFileList=new ArrayList<File>(); //private CellList<File> bvhCellList; //private SingleSelectionModel<File> fileSelectionModel; private DataList<File> dataList; private int currentLoop=0; private ListBox loopTime; private ListBox speedBox; private long remainTime; private CheckBox abLoopCheck; @Override protected void beforeUpdate(WebGLRenderer renderer) { /* if(selectedObject!=null){ double sx=(double)meshScaleX.getValue()/10; double sy=(double)meshScaleY.getValue()/10; double sz=(double)meshScaleZ.getValue()/10; double px=(double)positionX.getValue()/10; double py=(double)positionY.getValue()/10; double pz=(double)positionZ.getValue()/10; selectedObject.setScale(sx, sy, sz); selectedObject.setPosition(px,py,pz); } */ //camera.getPosition().setY(cameraY); //camera.getPosition().setY(cameraX);//MOVE UP? //cameraY=positionYRange.getValue(); //cameraX=positionXRange.getValue(); //validate ab-check boolean abLoop=abLoopCheck.getValue(); if(abLoop){ if(aFrame>=bFrame){ abLoopCheck.setValue(false); } if(aFrame>bvh.getFrames()-1 || bFrame>bvh.getFrames()-1){ abLoopCheck.setValue(false); } } Object3DUtils.setVisibleAll(backgroundContainer, drawBackground.getValue()); //backgroundContainer.setVisible(); boneContainer.setPosition(positionXRange.getValue(), positionYRange.getValue(), positionZRange.getValue()); if(boneRoot!=null){ rootGroup.getRotation().set(Math.toRadians(rotationRange.getValue()),Math.toRadians(rotationYRange.getValue()),Math.toRadians(rotationZRange.getValue())); } if(bvh!=null){ if(playing){ long last=clock.delta()+remainTime; double ftime=(bvh.getFrameTime()*1000/playSpeed); if(ftime==0){ return; //somehow frame become strange } int frame=(int) (last/ftime); remainTime=(long) (last-(ftime*frame)); // log(""+frame); //GWT.log(ftime+","+frame+","+remainTime); int minFrame=0; int maxFrame=bvh.getFrames(); if(abLoop){ minFrame=aFrame; maxFrame=bFrame; } if(frame>0){ int index=currentFrameRange.getValue()+frame; boolean overLoop=index>=maxFrame; index=(index-minFrame)%(maxFrame-minFrame); index+=minFrame; if(ignoreFirst.getValue() && index==0 &&minFrame==0){ index=1; } updatePoseIndex(index); if(overLoop && bvhFileList.size()>1 && !abLoop){ //next Frame try{ int maxLoop=Integer.parseInt(loopTime.getItemText(loopTime.getSelectedIndex())); //log("maxloop:"+maxLoop); if(maxLoop>0){ currentLoop++; if(currentLoop>=maxLoop){ currentLoop=0; doNextMotion(); } } }catch(Exception e){} } } /* double delta=(double)(System.currentTimeMillis()-ctime)/1000; delta%=bvh.getMotion().getDuration(); poseIndex = (int) (delta/bvh.getMotion().getFrameTime()); */ } } } @Override public void resized(int width, int height) { super.resized(width, height); leftBottom(bottomPanel); } @Override public String getHtml(){ return super.getHtml()+" Sample BVH File from <a href='https://sites.google.com/a/cgspeed.com/cgspeed/motion-capture/cmu-bvh-conversion'>CMU Graphics Lab Motion Capture Database</a>"; } }
src/com/akjava/gwt/bvh/client/GWTBVH.java
package com.akjava.gwt.bvh.client; /* * Copyright (C) 2011 [email protected] * * 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. */ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.akjava.bvh.client.BVH; import com.akjava.bvh.client.BVHNode; import com.akjava.bvh.client.BVHParser; import com.akjava.bvh.client.BVHParser.ParserListener; import com.akjava.bvh.client.Channels; import com.akjava.bvh.client.NameAndChannel; import com.akjava.bvh.client.Vec3; import com.akjava.gwt.bvh.client.list.BVHFileWidget; import com.akjava.gwt.bvh.client.list.DataList; import com.akjava.gwt.bvh.client.list.DataList.ChangeSelectionListener; import com.akjava.gwt.bvh.client.list.DataList.DataListRenderer; import com.akjava.gwt.html5.client.HTML5InputRange; import com.akjava.gwt.html5.client.extra.HTML5Builder; import com.akjava.gwt.html5.client.file.File; import com.akjava.gwt.html5.client.file.FileHandler; import com.akjava.gwt.html5.client.file.FileReader; import com.akjava.gwt.html5.client.file.FileUtils; import com.akjava.gwt.lib.client.widget.cell.util.Benchmark; import com.akjava.gwt.three.client.THREE; import com.akjava.gwt.three.client.core.Geometry; import com.akjava.gwt.three.client.core.Intersect; import com.akjava.gwt.three.client.core.Matrix4; import com.akjava.gwt.three.client.core.Object3D; import com.akjava.gwt.three.client.core.Projector; import com.akjava.gwt.three.client.core.Vector3; import com.akjava.gwt.three.client.gwt.Clock; import com.akjava.gwt.three.client.gwt.Object3DUtils; import com.akjava.gwt.three.client.gwt.SimpleDemoEntryPoint; import com.akjava.gwt.three.client.lights.Light; import com.akjava.gwt.three.client.objects.Mesh; import com.akjava.gwt.three.client.renderers.WebGLRenderer; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.JsArray; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ChangeHandler; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.MouseMoveEvent; import com.google.gwt.event.dom.client.MouseUpEvent; import com.google.gwt.event.dom.client.MouseUpHandler; import com.google.gwt.http.client.Request; import com.google.gwt.http.client.RequestBuilder; import com.google.gwt.http.client.RequestCallback; import com.google.gwt.http.client.RequestException; import com.google.gwt.http.client.Response; import com.google.gwt.http.client.URL; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.CheckBox; import com.google.gwt.user.client.ui.FileUpload; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.Panel; import com.google.gwt.user.client.ui.PopupPanel; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; /** * Entry point classes define <code>onModuleLoad()</code>. */ public class GWTBVH extends SimpleDemoEntryPoint { final Projector projector=THREE.Projector(); @Override public void onMouseClick(ClickEvent event) { int x=event.getX(); int y=event.getY(); /* if(inEdge(x,y)){ screenMove(x,y); return; }*/ JsArray<Intersect> intersects=projector.pickIntersects(event.getX(), event.getY(), screenWidth, screenHeight, camera,scene); for(int i=0;i<intersects.length();i++){ Intersect sect=intersects.get(i); select(sect.getObject()); break; } } Object3D selectedObject; private void select(Object3D selected){ selectedObject=selected; meshScaleX.setValue((int) (selectedObject.getScale().getX()*10)); meshScaleY.setValue((int) (selectedObject.getScale().getY()*10)); meshScaleZ.setValue((int) (selectedObject.getScale().getZ()*10)); positionX.setValue((int) (selectedObject.getPosition().getX()*10)); positionY.setValue((int) (selectedObject.getPosition().getY()*10)); positionZ.setValue((int) (selectedObject.getPosition().getZ()*10)); } @Override public void onMouseMove(MouseMoveEvent event) { // TODO Auto-generated method stub } private int defaultZ=200; Map<String,Vector3> boneSizeMap=new HashMap<String,Vector3>(); private Object3D rootGroup,boneContainer,backgroundContainer; @Override public void initializeOthers(WebGLRenderer renderer) { cameraY=10; defaultZoom=5; canvas.setClearColorHex(0xcccccc); scene.add(THREE.AmbientLight(0x888888)); Light pointLight = THREE.PointLight(0xffffff); pointLight.setPosition(0, 10, 300); scene.add(pointLight); doLoad("80_72"); rootGroup=THREE.Object3D(); scene.add(rootGroup); backgroundContainer=THREE.Object3D(); rootGroup.add(backgroundContainer); Geometry geo=THREE.PlaneGeometry(100, 100,20,20); Mesh mesh=THREE.Mesh(geo, THREE.MeshBasicMaterial().color(0x666666).wireFrame(true).build()); //mesh.setPosition(0, -17, 0); mesh.setRotation(Math.toRadians(-90), 0, 0); backgroundContainer.add(mesh); boneContainer=THREE.Object3D(); rootGroup.add(boneContainer); /* BVHParser parser=new BVHParser(); //String singleBvh=Bundles.INSTANCE.single_basic().getText(); //String singleBvh=Bundles.INSTANCE.twolink_n_rz().getText(); //String singleBvh=Bundles.INSTANCE.twolink_full().getText(); //String singleBvh=Bundles.INSTANCE.fourlink_branch().getText(); String singleBvh=Bundles.INSTANCE.twelve01().getText(); try { jointMap=new HashMap<String,Object3D>(); bvh = parser.parse(singleBvh); BVHNode node=bvh.getHiearchy(); root=THREE.Object3D(); scene.add(root); doLog(root,node); // //jointMap.get("Hips").setRotation(Math.toRadians(7.1338),Math.toRadians(-1.8542),Math.toRadians( -7.8190)); //doPose(bvh,"-0.3899 17.5076 7.8007 0 0 0 0 0 0 -21 0 0 0 0 0 0 0 0 0 0 0 0 0 0 21 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -16 0 0 21 0 0 11 0 0 0 -8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0"); //doPose(bvh,"-0.3899 17.5076 7.8007 -7.8190 -1.8542 7.1338 0.0000 0.0000 0.0000 -20.0095 -34.8717 23.1818 0.0543 -1.5040 -4.1368 -5.1851 39.6153 -34.2618 0.1274 2.3012 6.3387 0.0000 0.0000 0.0000 27.9815 23.6282 8.6217 -0.0094 -0.6245 1.7162 0.4741 -16.6281 -18.3131 -0.0041 -0.4123 1.1330 4.5929 -0.1445 3.0131 1.7537 0.3513 -8.5234 -0.7284 -0.1282 -10.7842 -14.7495 -15.2891 1.4491 15.1151 -23.2999 16.3175 5.0944 -11.3477 8.3590 -0.0000 -0.0000 0.0000 -91.7499 11.2503 9.6316 11.7870 -19.4845 -2.0307 -0.0000 -0.0000 23.6415 17.7243 -7.2146 -2.2985 -7.1250 0.0000 -0.0000 -6.6264 22.4256 3.6210 -0.0000 -0.0000 0.0000 92.9366 -10.7837 -16.0742 -9.0830 15.2927 -1.2219 0.0000 0.0000 58.8395 3.1909 -29.5170 -1.5733 7.1250 -0.0000 -0.0000 36.2824 -55.5617 -10.3909"); //doPose(bvh,"-0.5011 17.6282 7.6163 -6.2586 -15.2051 5.4723 0.0000 0.0000 0.0000 -21.3981 -26.0192 22.4790 0.0292 -1.1029 -3.0320 -3.3535 38.5451 -41.4272 0.6169 5.0265 13.9840 0.0000 0.0000 0.0000 24.7397 22.1958 5.0034 -0.0966 -2.0046 5.5183 -0.3873 -3.4522 -13.5373 -0.2228 3.0387 -8.3865 3.1625 -2.9263 2.2948 2.9237 -3.5238 -7.9690 1.7270 -1.8496 -9.7328 3.3763 2.5058 -7.4595 13.0244 0.5160 17.4961 3.6704 1.4696 6.5682 -0.0000 0.0000 0.0000 -42.7751 -56.6315 -8.6834 50.4538 -53.1769 -26.5370 -0.0000 0.0000 -77.6575 14.7878 7.4808 1.9684 -7.1250 0.0000 -0.0000 -10.2345 37.5343 1.9047 -0.0000 0.0000 0.0000 76.3877 59.4476 93.5538 -141.2974 47.2822 -102.5201 0.0000 -0.0000 -31.1956 -12.8820 -58.8974 11.0797 7.1250 -0.0000 -0.0000 91.0580 -76.5215 -77.2227"); doPose(bvh,bvh.getMotion().getMotions().get(0)); Matrix4 mx=THREE.Matrix4(); mx.setRotationFromEuler(THREE.Vector3(Math.toRadians(23.1818),Math.toRadians(-34.8717),Math.toRadians(-20.0095)), "ZYX"); Vector3 rot=THREE.Vector3(0, 0, 0); rot.setRotationFromMatrix(mx); double x=Math.toDegrees(rot.getX()); double y=Math.toDegrees(rot.getY()); double z=Math.toDegrees(rot.getZ()); GWT.log(x+","+y+","+z); //jointMap.get("LeftUpLeg").setRotation(rot.getX(), rot.getY(), rot.getZ()); //jointMap.get("LeftUpLeg").setRotation(Math.toRadians(23.1818),Math.toRadians(-34.8717),Math.toRadians(-20.0095)); //jointMap.get("RightUpLeg").getRotation(Math.toRadians(23.1818),Math.toRadians(-34.8717),Math.toRadians(-20.0095)); } catch (InvalidLineException e) { log(e.getMessage()); e.printStackTrace(); } */ // ctime=System.currentTimeMillis(); } private void doZYX(Object3D target,String lastOrder){ Vector3 vec=target.getRotation(); Matrix4 mx=THREE.Matrix4(); mx.setRotationFromEuler(vec, lastOrder); vec.setRotationFromMatrix(mx); } /* private void doPose(BVH bvh,String line){ String[] tmp=line.split(" "); double[] vs=BVHParser.toDouble(tmp); Object3D oldTarget=null; String lastOrder=null; for(int i=0;i<vs.length;i++){ NameAndChannel nchannel=bvh.getNameAndChannels().get(i); lastOrder=nchannel.getOrder(); Object3D target=jointMap.get(nchannel.getName()); switch(nchannel.getChannel()){ case Channels.XROTATION: target.getRotation().setX(Math.toRadians(vs[i])); break; case Channels.YROTATION: target.getRotation().setY(Math.toRadians(vs[i])); break; case Channels.ZROTATION: target.getRotation().setZ(Math.toRadians(vs[i])); break; } if(oldTarget!=null && oldTarget!=target){ doZYX(oldTarget,lastOrder); } oldTarget=target; } doZYX(oldTarget,lastOrder);//do last one }*/ private void doPose(BVH bvh,double[] vs){ Object3D oldTarget=null; String lastOrder=null; for(int i=0;i<vs.length;i++){ NameAndChannel nchannel=bvh.getNameAndChannels().get(i); lastOrder=nchannel.getOrder(); Object3D target=jointMap.get(nchannel.getName()); switch(nchannel.getChannel()){ case Channels.XROTATION: target.getRotation().setX(Math.toRadians(vs[i])); break; case Channels.YROTATION: target.getRotation().setY(Math.toRadians(vs[i])); break; case Channels.ZROTATION: target.getRotation().setZ(Math.toRadians(vs[i])); break; case Channels.XPOSITION: if(translatePosition.getValue()){ target.getPosition().setX(vs[i]); }else{ target.getPosition().setX(0); } break; case Channels.YPOSITION: if(translatePosition.getValue()){ target.getPosition().setY(vs[i]); }else{ target.getPosition().setY(0); } break; case Channels.ZPOSITION: if(translatePosition.getValue()){ target.getPosition().setZ(vs[i]); }else{ target.getPosition().setZ(0); } break; } if(oldTarget!=null && oldTarget!=target){ doZYX(oldTarget,lastOrder); } oldTarget=target; } doZYX(oldTarget,lastOrder);//do last one } private Map<String,Object3D> jointMap; public Mesh createLine(Vec3 from,Vec3 to){ Geometry lineG = THREE.Geometry(); lineG.vertices().push(THREE.Vertex(THREE.Vector3(from.getX(), from.getY(), from.getY()))); lineG.vertices().push(THREE.Vertex(THREE.Vector3(to.getX(), to.getY(), to.getZ()))); Mesh line=THREE.Line(lineG, THREE.LineBasicMaterial().color(0).build()); return line; } public void doLog(Object3D parent,BVHNode node){ GWT.log(node.getName()+","+node.getOffset()+",endsite:"+node.getEndSite()); GWT.log(node.getChannels().toString()); Object3D group=THREE.Object3D(); Mesh mesh=THREE.Mesh(THREE.CubeGeometry(.3,.3, .3), THREE.MeshLambertMaterial().color(0xffffff).build()); group.add(mesh); mesh.setName(node.getName()); //initial position group.setPosition(THREE.Vector3(node.getOffset().getX(), node.getOffset().getY(), node.getOffset().getZ())); jointMap.put(node.getName(), group); Mesh l1=createLine(new Vec3(),node.getOffset()); parent.add(l1); if(node.getEndSite()!=null){ Mesh end=THREE.Mesh(THREE.CubeGeometry(.1, .1, .1), THREE.MeshBasicMaterial().color(0x008800).build()); end.setPosition(THREE.Vector3(node.getEndSite().getX(), node.getEndSite().getY(), node.getEndSite().getZ())); group.add(end); Geometry lineG = THREE.Geometry(); lineG.vertices().push(THREE.Vertex(THREE.Vector3(0, 0, 0))); lineG.vertices().push(THREE.Vertex(THREE.Vector3(node.getEndSite().getX(), node.getEndSite().getY(), node.getEndSite().getZ()))); Mesh line=THREE.Line(lineG, THREE.LineBasicMaterial().color(0).build()); group.add(line); } parent.add(group); List<BVHNode> joints=node.getJoints(); if(joints!=null){ for(BVHNode joint:joints){ doLog(group,joint); } } } private Label loadingLabel=new Label(); private CheckBox translatePosition; private HTML5InputRange positionYRange; private HTML5InputRange meshScaleX; private HTML5InputRange meshScaleY; private HTML5InputRange meshScaleZ; private HTML5InputRange positionX; private HTML5InputRange positionY; private HTML5InputRange positionZ; private PopupPanel bottomPanel; protected boolean playing; private HTML5InputRange positionXRange; private HTML5InputRange positionZRange; private CheckBox drawBackground; private void loadBVH(String path){ Benchmark.start("load"); RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(path)); loadingLabel.setText("loading-data"); try { builder.sendRequest(null, new RequestCallback() { @Override public void onResponseReceived(Request request, Response response) { String bvhText=response.getText(); //log("loaded:"+Benchmark.end("load")); //useless spend allmost time with request and spliting. parseBVH(bvhText); loadingLabel.setText(""); } @Override public void onError(Request request, Throwable exception) { Window.alert("load faild:"); } }); } catch (RequestException e) { log(e.getMessage()); e.printStackTrace(); } } private void setEmptyBone(){ if(boneRoot!=null){ boneContainer.remove(boneRoot); } boneRoot=null; bvh=null; } private void parseBVH(String bvhText){ final BVHParser parser=new BVHParser(); jointMap=new HashMap<String,Object3D>(); parser.parseAsync(bvhText, new ParserListener() { @Override public void onSuccess(BVH bv) { bvh=bv; bvh.setSkips(skipFrames); BVHNode node=bvh.getHiearchy(); if(boneRoot!=null){ boneContainer.remove(boneRoot); } boneRoot=THREE.Object3D(); boneContainer.add(boneRoot); doLog(boneRoot,node); int poseIndex=0; if(ignoreFirst.getValue()){ poseIndex=1; } clock.update(); updatePoseIndex(poseIndex); doPose(bvh,bvh.getFrameAt(poseIndex)); currentFrameRange.setMax(bvh.getFrames()-1); } @Override public void onFaild(String message) { log(message); } }); } /* timer style * parser.initialize(); bvhText=bvhText.replace("\r", ""); final String lines[]=bvhText.split("\n"); final int pLine=lines.length/20; Timer timer=new Timer(){ int index=0; boolean parsing; @Override public synchronized void run() { if(parsing){ return; } parsing=true; loadingLabel.setText(index+"/"+lines.length); GWT.log("called:"+index+","+pLine); try { parser.parseLines(lines, index, index+pLine); if(index>=lines.length){ //done bvh=parser.getBvh(); BVHNode node=bvh.getHiearchy(); if(root!=null){ scene.remove(root); } root=THREE.Object3D(); scene.add(root); doLog(root,node); doPose(bvh,bvh.getMotion().getMotions().get(0)); poseIndex=0; cancel(); }else{ index+=pLine; } } catch (InvalidLineException e) { log(e.getMessage()); } parsing=false; } }; timer.scheduleRepeating(20); */ private long getFrameTime(int index){ long time=(long) (bvh.getFrameTime()*index*1000); return time; } private double getPlaySpeed(){ String v=speedBox.getItemText(speedBox.getSelectedIndex()); double r=1; try{ r=Double.parseDouble(v.substring(2)); }catch(Exception e){} return r; } private double playSpeed=1; private void createBottomPanel(){ bottomPanel = new PopupPanel(); bottomPanel.setVisible(true); bottomPanel.setSize("720px", "40px"); VerticalPanel main=new VerticalPanel(); bottomPanel.add(main); bottomPanel.show(); HorizontalPanel upperPanel=new HorizontalPanel(); upperPanel.setVerticalAlignment(HorizontalPanel.ALIGN_MIDDLE); main.add(upperPanel); upperPanel.add(new Label("Speed")); speedBox = new ListBox(); speedBox.addItem("x 0.25"); speedBox.addItem("x 0.5"); speedBox.addItem("x 1"); speedBox.addItem("x 2"); speedBox.addItem("x 4"); speedBox.addItem("x 10"); speedBox.setSelectedIndex(2); speedBox.addChangeHandler(new ChangeHandler() { @Override public void onChange(ChangeEvent event) { playSpeed=getPlaySpeed(); } }); upperPanel.add(speedBox); CheckBox abcheck=new CheckBox("A/B Loop"); upperPanel.add(abcheck); final Button asA=new Button("A:"); asA.setWidth("60px"); upperPanel.add(asA); asA.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { asA.setText("A:"+currentFrameRange.getValue()); } }); Button asB=new Button("B:"); asB.setWidth("60px"); upperPanel.add(asB); upperPanel.add(new Label("Skip every frame:")); final TextBox skipFrameBox=new TextBox(); skipFrameBox.setWidth("40px"); upperPanel.add(skipFrameBox); Button updateSkipBt=new Button("Update skips"); upperPanel.add(updateSkipBt); updateSkipBt.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { String v=skipFrameBox.getValue(); int sp=0; try{ sp=Integer.parseInt(v); }catch(Exception e){ } setBvhSkips(sp); } }); HorizontalPanel pPanel=new HorizontalPanel(); main.add(pPanel); pPanel.setVerticalAlignment(HorizontalPanel.ALIGN_MIDDLE); playing=true; final Button playButton=new Button("Play"); playButton.setEnabled(false); final Button stopButton=new Button("Stop"); playButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { clock.update(); //ctime=System.currentTimeMillis()-getFrameTime(); playing=true; playButton.setEnabled(false); stopButton.setEnabled(true); } }); pPanel.add(playButton); stopButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { playing=false; playButton.setEnabled(true); stopButton.setEnabled(false); } }); pPanel.add(stopButton); final Button prevButton=new Button("Prev"); prevButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { int c=currentFrameRange.getValue(); c--; /* if(c==0 && ignoreFirst.getValue()){ c=1; }*/ if(c<0){ c=0; } currentFrameRange.setValue(c); updatePoseIndex(currentFrameRange.getValue()); } }); pPanel.add(prevButton); final Button nextButton=new Button("Next"); nextButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { int c=currentFrameRange.getValue(); c++; if(c>=bvh.getFrames()){ c=bvh.getFrames()-1; } currentFrameRange.setValue(c); updatePoseIndex(currentFrameRange.getValue()); } }); pPanel.add(nextButton); currentFrameRange = new HTML5InputRange(0,1000,0); currentFrameRange.setWidth("450px"); pPanel.add(currentFrameRange); currentFrameRange.addMouseUpHandler(new MouseUpHandler() { @Override public void onMouseUp(MouseUpEvent event) { updatePoseIndex(currentFrameRange.getValue()); } }); currentFrameLabel = new Label(); pPanel.add(currentFrameLabel); super.leftBottom(bottomPanel); } private int skipFrames; private void setBvhSkips(int skips){ //TODO //set global for newload skipFrames=skips; //set current bvh bvh.setSkips(skips); updatePoseIndex(0); currentFrameRange.setMax(bvh.getFrames()-1); //update labels } @Override public void createControl(Panel parent) { parent.add(loadingLabel); drawBackground = new CheckBox("Draw Background"); parent.add(drawBackground); drawBackground.setValue(true); translatePosition = new CheckBox("Translate Position"); parent.add(translatePosition); translatePosition.setValue(true); ignoreFirst = new CheckBox("Ignore First Frame(Usually Pose)"); ignoreFirst.setValue(true); parent.add(ignoreFirst); HorizontalPanel h1=new HorizontalPanel(); rotationRange = new HTML5InputRange(-180,180,0); parent.add(HTML5Builder.createRangeLabel("X-Rotate:", rotationRange)); parent.add(h1); h1.add(rotationRange); Button reset=new Button("Reset"); reset.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { rotationRange.setValue(0); } }); h1.add(reset); HorizontalPanel h2=new HorizontalPanel(); rotationYRange = new HTML5InputRange(-180,180,0); parent.add(HTML5Builder.createRangeLabel("Y-Rotate:", rotationYRange)); parent.add(h2); h2.add(rotationYRange); Button reset2=new Button("Reset"); reset2.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { rotationYRange.setValue(0); } }); h2.add(reset2); HorizontalPanel h3=new HorizontalPanel(); rotationZRange = new HTML5InputRange(-180,180,0); parent.add(HTML5Builder.createRangeLabel("Z-Rotate:", rotationZRange)); parent.add(h3); h3.add(rotationZRange); Button reset3=new Button("Reset"); reset3.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { rotationZRange.setValue(0); } }); h3.add(reset3); HorizontalPanel h4=new HorizontalPanel(); positionXRange = new HTML5InputRange(-50,50,0); parent.add(HTML5Builder.createRangeLabel("X-Position:", positionXRange)); parent.add(h4); h4.add(positionXRange); Button reset4=new Button("Reset"); reset4.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { positionXRange.setValue(0); } }); h4.add(reset4); HorizontalPanel h5=new HorizontalPanel(); positionYRange = new HTML5InputRange(-50,50,0); parent.add(HTML5Builder.createRangeLabel("Y-Position:", positionYRange)); parent.add(h5); h5.add(positionYRange); Button reset5=new Button("Reset"); reset5.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { positionYRange.setValue(0); } }); h5.add(reset5); HorizontalPanel h6=new HorizontalPanel(); positionZRange = new HTML5InputRange(-50,50,0); parent.add(HTML5Builder.createRangeLabel("Z-Position:", positionZRange)); parent.add(h6); h6.add(positionZRange); Button reset6=new Button("Reset"); reset6.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { positionZRange.setValue(0); } }); h6.add(reset6); parent.add(new Label("Load BVH File")); FileUpload file=new FileUpload(); file.setHeight("50px"); file.getElement().setAttribute("multiple", "multiple"); file.addChangeHandler(new ChangeHandler() { @Override public void onChange(ChangeEvent event) { //Benchmark.start("load"); JsArray<File> files=FileUtils.toFile(event.getNativeEvent()); for(int i=0;i<files.length();i++){ bvhFileList.add(files.get(i)); } dataList.setDatas(bvhFileList); dataList.setSelection(files.get(0)); //bvhCellList.setRowCount(bvhFileList.size(), true); //bvhCellList.setRowData(bvhFileList); //fileSelectionModel.setSelected(files.get(0), true); /* log("length:"+files.length()); GWT.log(files.get(0).getFileName()); GWT.log(files.get(0).getFileType()); GWT.log(""+files.get(0).getFileSize()); log(event.getNativeEvent()); final FileReader reader=FileReader.createFileReader(); reader.setOnLoad(new FileHandler() { @Override public void onLoad() { //log("load:"+Benchmark.end("load")); //GWT.log(reader.getResultAsString()); parseBVH(reader.getResultAsString()); } }); reader.readAsText(files.get(0),"utf-8"); */ } }); parent.add(file); HorizontalPanel fileControl=new HorizontalPanel(); parent.add(fileControl); Button prevBt=new Button("Prev"); prevBt.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { if(bvhFileList.size()==0){ return; } File file=dataList.getSelection(); int index=bvhFileList.indexOf(file); index--; if(index<0){ index=bvhFileList.size()-1; } dataList.setSelection(bvhFileList.get(index)); } }); fileControl.add(prevBt); Button nextBt=new Button("Next"); nextBt.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { doNextMotion(); } }); fileControl.add(nextBt); fileControl.add(new Label("Auto Play")); loopTime = new ListBox(); loopTime.addItem("None"); loopTime.addItem("1"); loopTime.addItem("3"); loopTime.addItem("10"); loopTime.setSelectedIndex(0); fileControl.add(loopTime); file.setStylePrimaryName("fileborder"); /* meshScaleX = new HTML5InputRange(0,150,3); parent.add(HTML5Builder.createRangeLabel("Scale-x", meshScaleX)); parent.add(meshScaleX); meshScaleY = new HTML5InputRange(0,150,3); parent.add(HTML5Builder.createRangeLabel("Scale-y", meshScaleY)); parent.add(meshScaleY); meshScaleZ = new HTML5InputRange(0,150,3); parent.add(HTML5Builder.createRangeLabel("Scale-z", meshScaleZ)); parent.add(meshScaleZ); positionX = new HTML5InputRange(-150,150,0); parent.add(HTML5Builder.createRangeLabel("Position-x", positionX)); parent.add(positionX); positionY = new HTML5InputRange(-150,150,0); parent.add(HTML5Builder.createRangeLabel("Position-y", positionY)); parent.add(positionY); positionZ = new HTML5InputRange(-150,150,0); parent.add(HTML5Builder.createRangeLabel("Position-z", positionZ)); parent.add(positionZ); */ dataList = new DataList<File>(new DataListRenderer<File>(){ @Override public Widget createWidget(File data,DataList<File> dataList) { return new BVHFileWidget(data,dataList); }}); dataList.setHeight("60px"); parent.add(dataList); dataList.setListener(new ChangeSelectionListener<File>() { @Override public void onChangeSelection(File data) { final FileReader reader=FileReader.createFileReader(); reader.setOnLoad(new FileHandler() { @Override public void onLoad() { parseBVH(reader.getResultAsString()); } }); reader.readAsText(data,"utf-8"); } }); HorizontalPanel dataControls=new HorizontalPanel(); parent.add(dataControls); Button remove=new Button("Remove"); remove.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { if(bvhFileList.size()==0){ return; } File file=dataList.getSelection(); int index=bvhFileList.indexOf(file); bvhFileList.remove(file); if(index>=bvhFileList.size()){ index=0; } dataList.setDatas(bvhFileList); if(bvhFileList.size()!=0){ dataList.setSelection(bvhFileList.get(index)); }else{ setEmptyBone(); } } }); dataControls.add(remove); createBottomPanel(); showControl(); } private void doNextMotion(){ if(bvhFileList.size()==0){ return; } File file=dataList.getSelection(); int index=bvhFileList.indexOf(file); index++; if(index>bvhFileList.size()-1){ index=0; } dataList.setSelection(bvhFileList.get(index)); } protected void doLoad(String itemText) { String[] g_n=itemText.split("_"); loadBVH("bvhs/"+g_n[0]+"/"+itemText+".bvh"); } private HTML5InputRange rotationRange; private HTML5InputRange rotationYRange; private HTML5InputRange rotationZRange; Object3D boneRoot; private BVH bvh; private CheckBox ignoreFirst; //private long ctime; private HTML5InputRange currentFrameRange; private Label currentFrameLabel; //private int poseIndex; private void updatePoseIndex(int index){ //poseIndex=index; currentFrameRange.setValue(index); currentFrameLabel.setText((index+1)+"/"+bvh.getFrames()); doPose(bvh,bvh.getFrameAt(index)); } Clock clock=new Clock(); private List<File> bvhFileList=new ArrayList<File>(); //private CellList<File> bvhCellList; //private SingleSelectionModel<File> fileSelectionModel; private DataList<File> dataList; private int currentLoop=0; private ListBox loopTime; private ListBox speedBox; private long remainTime; @Override protected void beforeUpdate(WebGLRenderer renderer) { /* if(selectedObject!=null){ double sx=(double)meshScaleX.getValue()/10; double sy=(double)meshScaleY.getValue()/10; double sz=(double)meshScaleZ.getValue()/10; double px=(double)positionX.getValue()/10; double py=(double)positionY.getValue()/10; double pz=(double)positionZ.getValue()/10; selectedObject.setScale(sx, sy, sz); selectedObject.setPosition(px,py,pz); } */ //camera.getPosition().setY(cameraY); //camera.getPosition().setY(cameraX);//MOVE UP? //cameraY=positionYRange.getValue(); //cameraX=positionXRange.getValue(); Object3DUtils.setVisibleAll(backgroundContainer, drawBackground.getValue()); //backgroundContainer.setVisible(); boneContainer.setPosition(positionXRange.getValue(), positionYRange.getValue(), positionZRange.getValue()); if(boneRoot!=null){ rootGroup.getRotation().set(Math.toRadians(rotationRange.getValue()),Math.toRadians(rotationYRange.getValue()),Math.toRadians(rotationZRange.getValue())); } if(bvh!=null){ if(playing){ long last=clock.delta()+remainTime; double ftime=(bvh.getFrameTime()*1000/playSpeed); if(ftime==0){ return; //somehow frame become strange } int frame=(int) (last/ftime); remainTime=(long) (last-(ftime*frame)); // log(""+frame); //GWT.log(ftime+","+frame+","+remainTime); if(frame>0){ int index=currentFrameRange.getValue()+frame; boolean overLoop=index>=bvh.getFrames(); index%=bvh.getFrames(); if(ignoreFirst.getValue() && index==0){ index=1; } updatePoseIndex(index); if(overLoop && bvhFileList.size()>1){ //next Frame try{ int maxLoop=Integer.parseInt(loopTime.getItemText(loopTime.getSelectedIndex())); //log("maxloop:"+maxLoop); if(maxLoop>0){ currentLoop++; if(currentLoop>=maxLoop){ currentLoop=0; doNextMotion(); } } }catch(Exception e){} } } /* double delta=(double)(System.currentTimeMillis()-ctime)/1000; delta%=bvh.getMotion().getDuration(); poseIndex = (int) (delta/bvh.getMotion().getFrameTime()); */ } } } @Override public void resized(int width, int height) { super.resized(width, height); leftBottom(bottomPanel); } @Override public String getHtml(){ return super.getHtml()+" Sample BVH File from <a href='https://sites.google.com/a/cgspeed.com/cgspeed/motion-capture/cmu-bvh-conversion'>CMU Graphics Lab Motion Capture Database</a>"; } }
support a/b loop
src/com/akjava/gwt/bvh/client/GWTBVH.java
support a/b loop
Java
apache-2.0
158b038b644247f7f82cbd7b8630c1a0866a851f
0
jbb-project/jbb,jbb-project/jbb
package org.jbb.lib.properties; import org.aeonbits.owner.ConfigFactory; public final class ModuleConfigFactory { private static final SystemProperties SYSTEM_PROPERTIES = ConfigFactory.create( SystemProperties.class, System.getProperties(), System.getenv()); private ModuleConfigFactory() { // util class... } public static <T extends ModuleConfig> T create(Class<? extends T> clazz) { return ConfigFactory.create(clazz); // TODO add PropertyChangeListener for logging } public static SystemProperties systemProperties() { return SYSTEM_PROPERTIES; } }
implementation/libs/jbb-lib-properties/src/main/java/org/jbb/lib/properties/ModuleConfigFactory.java
package org.jbb.lib.properties; import org.aeonbits.owner.ConfigFactory; public final class ModuleConfigFactory { private final static SystemProperties SYSTEM_PROPERTIES = ConfigFactory.create( SystemProperties.class, System.getProperties(), System.getenv()); private ModuleConfigFactory() { // util class... } public static <T extends ModuleConfig> T create(Class<? extends T> clazz) { return ConfigFactory.create(clazz); // TODO add PropertyChangeListener for logging } public static SystemProperties systemProperties() { return SYSTEM_PROPERTIES; } }
Sonar code smell
implementation/libs/jbb-lib-properties/src/main/java/org/jbb/lib/properties/ModuleConfigFactory.java
Sonar code smell
Java
apache-2.0
946255403de4501ced3f98124ae4e2448b25faad
0
tieusangaka/Clean-Contacts,billy1108/Clean-Contacts,Dreezydraig/Clean-Contacts,PaNaVTEC/Clean-Contacts,antoniolg/Clean-Contacts,0359xiaodong/Clean-Contacts,PaNaVTEC/Clean-Contacts
package me.panavtec.cleancontacts.modules.main; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.widget.TextView; import com.carlosdelachica.easyrecycleradapters.adapter.EasyRecyclerAdapter; import com.carlosdelachica.easyrecycleradapters.recycler_view_manager.EasyRecyclerViewManager; import java.util.Arrays; import java.util.List; import javax.inject.Inject; import butterknife.InjectView; import me.panavtec.cleancontacts.R; import me.panavtec.cleancontacts.domain.entities.Contact; import me.panavtec.cleancontacts.modules.main.adapters.ContactViewHolderFactory; import me.panavtec.cleancontacts.presentation.main.MainPresenter; import me.panavtec.cleancontacts.presentation.main.MainView; import me.panavtec.cleancontacts.ui.BaseActivity; import me.panavtec.cleancontacts.ui.errors.ErrorManager; import me.panavtec.cleancontacts.ui.imageloader.ImageLoader; import me.panavtec.cleancontacts.ui.items.ContactViewHolder; public class MainActivity extends BaseActivity implements MainView, SwipeRefreshLayout.OnRefreshListener { @Inject MainPresenter presenter; @Inject ErrorManager errorManager; @Inject ImageLoader imageLoader; @InjectView(R.id.swipeRefreshLayout) SwipeRefreshLayout swipeRefreshLayout; @InjectView(R.id.recyclerView) RecyclerView recyclerView; @InjectView(R.id.empty_list) TextView emptyList; @InjectView(R.id.toolbar) Toolbar toolbar; private EasyRecyclerViewManager recyclerViewManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initUi(); presenter.onCreate(); } private void initUi() { initToolbar(); initRecyclerView(); initRefreshLayout(); } private void initToolbar() { if (toolbar != null) { setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(false); } } private void initRecyclerView() { ContactViewHolderFactory contactViewHolderFactory = new ContactViewHolderFactory(this, imageLoader); EasyRecyclerAdapter adapter = new EasyRecyclerAdapter(contactViewHolderFactory, Contact.class, ContactViewHolder.class); recyclerViewManager = new EasyRecyclerViewManager.Builder(recyclerView, adapter) .emptyLoadingListTextView(emptyList) .loadingListTextColor(android.R.color.white) .build(); } private void initRefreshLayout() { swipeRefreshLayout.setOnRefreshListener(this); recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() { public void onScrollStateChanged(RecyclerView recyclerView, int newState) { } public void onScrolled(RecyclerView recyclerView, int dx, int dy) { int topRowVerticalPosition = recyclerView == null || recyclerView.getChildCount() == 0 ? 0 : recyclerView.getChildAt(0).getTop(); swipeRefreshLayout.setEnabled(topRowVerticalPosition >= 0); } }); } @Override public int onCreateViewId() { return R.layout.activity_main; } @Override protected void onResume() { super.onResume(); presenter.onResume(); } @Override protected void onPause() { super.onPause(); presenter.onPause(); } @Override public void refreshContactsList(List<Contact> contacts) { recyclerViewManager.addAll(contacts); swipeRefreshLayout.setRefreshing(false); } @Override public void showGetContactsError() { errorManager.showError(getString(R.string.err_getting_contacts)); } @Override public void onRefresh() { presenter.onRefresh(); recyclerViewManager.onRefresh(); swipeRefreshLayout.setRefreshing(true); } @Override protected List<Object> getModules() { return Arrays.<Object>asList(new MainModule(this)); } }
app/src/main/java/me/panavtec/cleancontacts/modules/main/MainActivity.java
package me.panavtec.cleancontacts.modules.main; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.widget.TextView; import com.carlosdelachica.easyrecycleradapters.adapter.EasyRecyclerAdapter; import com.carlosdelachica.easyrecycleradapters.recycler_view_manager.EasyRecyclerViewManager; import java.util.Arrays; import java.util.List; import javax.inject.Inject; import butterknife.InjectView; import me.panavtec.cleancontacts.R; import me.panavtec.cleancontacts.domain.entities.Contact; import me.panavtec.cleancontacts.modules.main.adapters.ContactViewHolderFactory; import me.panavtec.cleancontacts.presentation.main.MainPresenter; import me.panavtec.cleancontacts.presentation.main.MainView; import me.panavtec.cleancontacts.ui.BaseActivity; import me.panavtec.cleancontacts.ui.errors.ErrorManager; import me.panavtec.cleancontacts.ui.imageloader.ImageLoader; import me.panavtec.cleancontacts.ui.items.ContactViewHolder; public class MainActivity extends BaseActivity implements MainView, SwipeRefreshLayout.OnRefreshListener { @Inject MainPresenter presenter; @Inject ErrorManager errorManager; @Inject ImageLoader imageLoader; @InjectView(R.id.swipeRefreshLayout) SwipeRefreshLayout swipeRefreshLayout; @InjectView(R.id.recyclerView) RecyclerView recyclerView; @InjectView(R.id.empty_list) TextView emptyList; @InjectView(R.id.toolbar) Toolbar toolbar; private EasyRecyclerViewManager recyclerViewManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initUi(); presenter.onCreate(); } private void initUi() { initToolbar(); initRecyclerView(); initRefreshLayout(); } private void initRefreshLayout() { swipeRefreshLayout.setOnRefreshListener(this); recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() { public void onScrollStateChanged(RecyclerView recyclerView, int newState) { } public void onScrolled(RecyclerView recyclerView, int dx, int dy) { int topRowVerticalPosition = recyclerView == null || recyclerView.getChildCount() == 0 ? 0 : recyclerView.getChildAt(0).getTop(); swipeRefreshLayout.setEnabled(topRowVerticalPosition >= 0); } }); } private void initToolbar() { if (toolbar != null) { setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(false); } } private void initRecyclerView() { ContactViewHolderFactory contactViewHolderFactory = new ContactViewHolderFactory(this, imageLoader); EasyRecyclerAdapter adapter = new EasyRecyclerAdapter(contactViewHolderFactory, Contact.class, ContactViewHolder.class); recyclerViewManager = new EasyRecyclerViewManager.Builder(recyclerView, adapter) .emptyLoadingListTextView(emptyList) .loadingListTextColor(android.R.color.white) .build(); } @Override public int onCreateViewId() { return R.layout.activity_main; } @Override protected void onResume() { super.onResume(); presenter.onResume(); } @Override protected void onPause() { super.onPause(); presenter.onPause(); } @Override public void refreshContactsList(List<Contact> contacts) { recyclerViewManager.addAll(contacts); swipeRefreshLayout.setRefreshing(false); } @Override public void showGetContactsError() { errorManager.showError(getString(R.string.err_getting_contacts)); } @Override public void onRefresh() { presenter.onRefresh(); recyclerViewManager.onRefresh(); swipeRefreshLayout.setRefreshing(true); } @Override protected List<Object> getModules() { return Arrays.<Object>asList(new MainModule(this)); } }
Moves method to correct place
app/src/main/java/me/panavtec/cleancontacts/modules/main/MainActivity.java
Moves method to correct place
Java
apache-2.0
b6e3dd64975f66f462b987aa8e45f1872a9bb119
0
ProgrammerDan/json-simple
package org.json.simple.parser; /** * ParseException explains why and where the error occurs in source JSON text. * * @author FangYidong<[email protected]> * */ public class ParseException extends Exception { private static final long serialVersionUID = -7880698968187728547L; public static final int ERROR_UNEXPECTED_CHAR = 0; public static final int ERROR_UNEXPECTED_TOKEN = 1; public static final int ERROR_UNEXPECTED_EXCEPTION = 2; private int errorType; private Object unexpectedObject; private int position; public ParseException(int errorType){ this(-1, errorType, null); } public ParseException(int errorType, Object unexpectedObject){ this(-1, errorType, unexpectedObject); } public ParseException(int position, int errorType, Object unexpectedObject){ this.position = position; this.errorType = errorType; this.unexpectedObject = unexpectedObject; } public int getErrorType() { return errorType; } public void setErrorType(int errorType) { this.errorType = errorType; } /** * @see org.json.simple.parser.JSONParser#getPosition() * * @return The character position (starting with 0) of the input where the error occurs. */ public int getPosition() { return position; } public void setPosition(int position) { this.position = position; } /** * @see org.json.simple.parser.Yytoken * * @return One of the following base on the value of errorType: * ERROR_UNEXPECTED_CHAR java.lang.Character * ERROR_UNEXPECTED_TOKEN org.json.simple.parser.Yytoken * ERROR_UNEXPECTED_EXCEPTION java.lang.Exception */ public Object getUnexpectedObject() { return unexpectedObject; } public void setUnexpectedObject(Object unexpectedObject) { this.unexpectedObject = unexpectedObject; } public String getMessage() { StringBuffer sb = new StringBuffer(); switch(errorType){ case ERROR_UNEXPECTED_CHAR: sb.append("Unexpected character (").append(unexpectedObject).append(") at position ").append(position).append("."); break; case ERROR_UNEXPECTED_TOKEN: sb.append("Unexpected token ").append(unexpectedObject).append(" at position ").append(position).append("."); break; case ERROR_UNEXPECTED_EXCEPTION: sb.append("Unexpected exception at position ").append(position).append(": ").append(unexpectedObject); break; default: sb.append("Unkown error at position ").append(position).append("."); break; } return sb.toString(); } }
src/main/java/org/json/simple/parser/ParseException.java
package org.json.simple.parser; /** * ParseException explains why and where the error occurs in source JSON text. * * @author FangYidong<[email protected]> * */ public class ParseException extends Exception { private static final long serialVersionUID = -7880698968187728548L; public static final int ERROR_UNEXPECTED_CHAR = 0; public static final int ERROR_UNEXPECTED_TOKEN = 1; public static final int ERROR_UNEXPECTED_EXCEPTION = 2; private int errorType; private Object unexpectedObject; private int position; public ParseException(int errorType){ this(-1, errorType, null); } public ParseException(int errorType, Object unexpectedObject){ this(-1, errorType, unexpectedObject); } public ParseException(int position, int errorType, Object unexpectedObject){ this.position = position; this.errorType = errorType; this.unexpectedObject = unexpectedObject; } public int getErrorType() { return errorType; } public void setErrorType(int errorType) { this.errorType = errorType; } /** * @see org.json.simple.parser.JSONParser#getPosition() * * @return The character position (starting with 0) of the input where the error occurs. */ public int getPosition() { return position; } public void setPosition(int position) { this.position = position; } /** * @see org.json.simple.parser.Yytoken * * @return One of the following base on the value of errorType: * ERROR_UNEXPECTED_CHAR java.lang.Character * ERROR_UNEXPECTED_TOKEN org.json.simple.parser.Yytoken * ERROR_UNEXPECTED_EXCEPTION java.lang.Exception */ public Object getUnexpectedObject() { return unexpectedObject; } public void setUnexpectedObject(Object unexpectedObject) { this.unexpectedObject = unexpectedObject; } public String toString(){ StringBuffer sb = new StringBuffer(); switch(errorType){ case ERROR_UNEXPECTED_CHAR: sb.append("Unexpected character (").append(unexpectedObject).append(") at position ").append(position).append("."); break; case ERROR_UNEXPECTED_TOKEN: sb.append("Unexpected token ").append(unexpectedObject).append(" at position ").append(position).append("."); break; case ERROR_UNEXPECTED_EXCEPTION: sb.append("Unexpected exception at position ").append(position).append(": ").append(unexpectedObject); break; default: sb.append("Unkown error at position ").append(position).append("."); break; } return sb.toString(); } }
Return a description of the exception via getMessage. git-svn-id: 5e6063538803623c6d6d55af6c36a1e86365bd2c@214 b68fe964-5755-0410-a06c-9fee2ea08261
src/main/java/org/json/simple/parser/ParseException.java
Return a description of the exception via getMessage.
Java
apache-2.0
9b77c7f1b208284c39c07ab69ffbabb23d6a6b6e
0
rkorpachyov/maven-plugins,johnmccabe/maven-plugins,zigarn/maven-plugins,criteo-forks/maven-plugins,edwardmlyte/maven-plugins,Orange-OpenSource/maven-plugins,apache/maven-plugins,mikkokar/maven-plugins,mcculls/maven-plugins,sonatype/maven-plugins,ptahchiev/maven-plugins,ptahchiev/maven-plugins,krosenvold/maven-plugins,kidaa/maven-plugins,mcculls/maven-plugins,apache/maven-plugins,kikinteractive/maven-plugins,kidaa/maven-plugins,ptahchiev/maven-plugins,zigarn/maven-plugins,Orange-OpenSource/maven-plugins,mikkokar/maven-plugins,krosenvold/maven-plugins,kidaa/maven-plugins,lennartj/maven-plugins,Orange-OpenSource/maven-plugins,edwardmlyte/maven-plugins,edwardmlyte/maven-plugins,lennartj/maven-plugins,HubSpot/maven-plugins,HubSpot/maven-plugins,hazendaz/maven-plugins,apache/maven-plugins,mikkokar/maven-plugins,PressAssociation/maven-plugins,sonatype/maven-plugins,johnmccabe/maven-plugins,omnidavesz/maven-plugins,restlet/maven-plugins,mikkokar/maven-plugins,kikinteractive/maven-plugins,lennartj/maven-plugins,krosenvold/maven-plugins,omnidavesz/maven-plugins,mcculls/maven-plugins,PressAssociation/maven-plugins,kidaa/maven-plugins,krosenvold/maven-plugins,edwardmlyte/maven-plugins,mcculls/maven-plugins,restlet/maven-plugins,apache/maven-plugins,ptahchiev/maven-plugins,sonatype/maven-plugins,johnmccabe/maven-plugins,zigarn/maven-plugins,PressAssociation/maven-plugins,hazendaz/maven-plugins,criteo-forks/maven-plugins,lennartj/maven-plugins,rkorpachyov/maven-plugins,criteo-forks/maven-plugins,HubSpot/maven-plugins,zigarn/maven-plugins,rkorpachyov/maven-plugins,hazendaz/maven-plugins,restlet/maven-plugins,hazendaz/maven-plugins,johnmccabe/maven-plugins,hgschmie/apache-maven-plugins,HubSpot/maven-plugins,hgschmie/apache-maven-plugins,restlet/maven-plugins,Orange-OpenSource/maven-plugins,hgschmie/apache-maven-plugins,rkorpachyov/maven-plugins,apache/maven-plugins,omnidavesz/maven-plugins,hgschmie/apache-maven-plugins,hazendaz/maven-plugins,criteo-forks/maven-plugins,kikinteractive/maven-plugins,sonatype/maven-plugins,PressAssociation/maven-plugins,rkorpachyov/maven-plugins,omnidavesz/maven-plugins
package org.apache.maven.plugin.checkstyle; /* * 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. */ import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.ResourceBundle; import org.apache.maven.doxia.sink.Sink; import org.apache.maven.doxia.sink.SinkEventAttributeSet; import org.apache.maven.doxia.sink.SinkEventAttributes; import org.apache.maven.doxia.tools.SiteTool; import org.apache.maven.plugin.checkstyle.exec.CheckstyleResults; import org.apache.maven.plugin.logging.Log; import org.apache.maven.plugin.logging.SystemStreamLog; import org.codehaus.plexus.util.StringUtils; import com.puppycrawl.tools.checkstyle.api.AuditEvent; import com.puppycrawl.tools.checkstyle.api.CheckstyleException; import com.puppycrawl.tools.checkstyle.api.Configuration; import com.puppycrawl.tools.checkstyle.api.SeverityLevel; /** * Generate a report based on CheckstyleResults. * * @version $Id$ */ public class CheckstyleReportGenerator { private Log log; private final File basedir; private final ResourceBundle bundle; private final Sink sink; private SeverityLevel severityLevel; private Configuration checkstyleConfig; private boolean enableRulesSummary; private boolean enableSeveritySummary; private boolean enableFilesSummary; private boolean enableRSS; private final SiteTool siteTool; private String xrefLocation; private List<String> treeWalkerNames = Collections.singletonList( "TreeWalker" ); private final IconTool iconTool; public CheckstyleReportGenerator( Sink sink, ResourceBundle bundle, File basedir, SiteTool siteTool ) { this.bundle = bundle; this.sink = sink; this.basedir = basedir; this.siteTool = siteTool; this.enableRulesSummary = true; this.enableSeveritySummary = true; this.enableFilesSummary = true; this.enableRSS = true; this.iconTool = new IconTool( sink, bundle ); } public Log getLog() { if ( this.log == null ) { this.log = new SystemStreamLog(); } return this.log; } public void setLog( Log log ) { this.log = log; } private String getTitle() { String title; if ( getSeverityLevel() == null ) { title = bundle.getString( "report.checkstyle.title" ); } else { title = bundle.getString( "report.checkstyle.severity_title" ) + severityLevel.getName(); } return title; } public void generateReport( CheckstyleResults results ) { doHeading(); if ( getSeverityLevel() == null ) { if ( enableSeveritySummary ) { doSeveritySummary( results ); } if ( enableFilesSummary ) { doFilesSummary( results ); } if ( enableRulesSummary ) { doRulesSummary( results ); } } doDetails( results ); sink.body_(); sink.flush(); sink.close(); } private void doHeading() { sink.head(); sink.title(); sink.text( getTitle() ); sink.title_(); sink.head_(); sink.body(); sink.section1(); sink.sectionTitle1(); sink.text( getTitle() ); sink.sectionTitle1_(); sink.paragraph(); sink.text( bundle.getString( "report.checkstyle.checkstylelink" ) + " " ); sink.link( "http://checkstyle.sourceforge.net/" ); sink.text( "Checkstyle" ); sink.link_(); sink.text( "." ); if ( enableRSS ) { sink.nonBreakingSpace(); sink.link( "checkstyle.rss" ); sink.figure(); sink.figureCaption(); sink.text( "rss feed" ); sink.figureCaption_(); sink.figureGraphics( "images/rss.png" ); sink.figure_(); sink.link_(); } sink.paragraph_(); sink.section1_(); } /** * Get the value of the specified attribute from the Checkstyle configuration. * If parentConfigurations is non-null and non-empty, the parent * configurations are searched if the attribute cannot be found in the * current configuration. If the attribute is still not found, the * specified default value will be returned. * * @param config The current Checkstyle configuration * @param parentConfigurations The configurations for the parents of the current configuration * @param attributeName The name of the attribute * @param defaultValue The default value to use if the attribute cannot be found in any configuration * @return The value of the specified attribute */ private String getConfigAttribute( Configuration config, List<Configuration> parentConfigurations, String attributeName, String defaultValue ) { String ret; try { ret = config.getAttribute( attributeName ); } catch ( CheckstyleException e ) { // Try to find the attribute in a parent, if there are any if ( parentConfigurations != null && !parentConfigurations.isEmpty() ) { Configuration parentConfiguration = parentConfigurations.get( parentConfigurations.size() - 1 ); List<Configuration> newParentConfigurations = new ArrayList<Configuration>( parentConfigurations ); // Remove the last parent newParentConfigurations.remove( parentConfiguration ); ret = getConfigAttribute( parentConfiguration, newParentConfigurations, attributeName, defaultValue ); } else { ret = defaultValue; } } return ret; } /** * Create the rules summary section of the report. * * @param results The results to summarize */ private void doRulesSummary( CheckstyleResults results ) { if ( checkstyleConfig == null ) { return; } sink.section1(); sink.sectionTitle1(); sink.text( bundle.getString( "report.checkstyle.rules" ) ); sink.sectionTitle1_(); sink.table(); sink.tableRow(); sink.tableHeaderCell(); sink.text( bundle.getString( "report.checkstyle.column.severity" ) ); sink.tableHeaderCell_(); sink.tableHeaderCell(); sink.text( bundle.getString( "report.checkstyle.rule" ) ); sink.tableHeaderCell_(); sink.tableHeaderCell(); sink.text( bundle.getString( "report.checkstyle.violations" ) ); sink.tableHeaderCell_(); sink.tableRow_(); // Top level should be the checker. if ( "checker".equalsIgnoreCase( checkstyleConfig.getName() ) ) { doRuleChildren( checkstyleConfig, null, results ); } else { sink.tableRow(); sink.tableCell(); sink.text( bundle.getString( "report.checkstyle.norule" ) ); sink.tableCell_(); sink.tableRow_(); } sink.table_(); sink.section1_(); } /** * Create a summary for each Checkstyle rule. * * @param configuration The Checkstyle configuration * @param parentConfigurations A List of configurations for the chain of parents to the current configuration * @param results The results to summarize */ private void doRuleChildren( Configuration configuration, List<Configuration> parentConfigurations, CheckstyleResults results ) { // Remember the chain of parent configurations if ( parentConfigurations == null ) { parentConfigurations = new ArrayList<Configuration>(); } // The "oldest" parent will be first in the list parentConfigurations.add( configuration ); if ( getLog().isDebugEnabled() ) { // Log the parent configuration path StringBuilder parentPath = new StringBuilder(); for ( Iterator<Configuration> iterator = parentConfigurations.iterator(); iterator.hasNext(); ) { Configuration parentConfiguration = iterator.next(); parentPath.append( parentConfiguration.getName() ); if ( iterator.hasNext() ) { parentPath.append( " --> " ); } } if ( parentPath.length() > 0 ) { getLog().debug( "Parent Configuration Path: " + parentPath.toString() ); } } for ( Configuration configChild : configuration.getChildren() ) { String ruleName = configChild.getName(); if ( treeWalkerNames.contains( ruleName ) ) { // special sub-case: TreeWalker is the parent of multiple rules, not an effective rule doRuleChildren( configChild, parentConfigurations, results ); } else { doRuleRow( configChild, parentConfigurations, ruleName, results ); } } } /** * Create a summary for one Checkstyle rule. * * @param checkerConfig Configuration for the Checkstyle rule * @param parentConfigurations Configurations for the parents of this rule * @param ruleName The name of the rule, for example "JavadocMethod" * @param results The results to summarize */ private void doRuleRow( Configuration checkerConfig, List<Configuration> parentConfigurations, String ruleName, CheckstyleResults results ) { sink.tableRow(); // column 1: severity sink.tableCell(); // Grab the severity from the rule configuration, this time use error as default value // Also pass along all parent configurations, so that we can try to find the severity there String severity = getConfigAttribute( checkerConfig, parentConfigurations, "severity", "error" ); iconTool.iconSeverity( severity, IconTool.TEXT_SIMPLE ); sink.tableCell_(); // column 2: Rule name + configured attributes sink.tableCell(); sink.text( ruleName ); List<String> attribnames = new ArrayList<String>( Arrays.asList( checkerConfig.getAttributeNames() ) ); attribnames.remove( "severity" ); // special value (deserves unique column) if ( !attribnames.isEmpty() ) { sink.list(); for ( String name : attribnames ) { sink.listItem(); sink.bold(); sink.text( name ); sink.bold_(); String value = getConfigAttribute( checkerConfig, null, name, "" ); // special case, Header.header and RegexpHeader.header if ( "header".equals( name ) && ( "Header".equals( ruleName ) || "RegexpHeader".equals( ruleName ) ) ) { String[] lines = StringUtils.split( value, "\\n" ); int linenum = 1; for ( String line : lines ) { sink.lineBreak(); sink.rawText( "<span style=\"color: gray\">" ); sink.text( linenum + ":" ); sink.rawText( "</span>" ); sink.nonBreakingSpace(); sink.monospaced(); sink.text( line ); sink.monospaced_(); linenum++; } } else if ( "headerFile".equals( name ) && "RegexpHeader".equals( ruleName ) ) { sink.text( ": " ); sink.monospaced(); sink.text( "\"" ); if ( basedir != null ) { // Make the headerFile value relative to ${basedir} String path = siteTool.getRelativePath( value, basedir.getAbsolutePath() ); sink.text( path.replace( '\\', '/' ) ); } else { sink.text( value ); } sink.text( "\"" ); sink.monospaced_(); } else { sink.text( ": " ); sink.monospaced(); sink.text( "\"" ); sink.text( value ); sink.text( "\"" ); sink.monospaced_(); } sink.listItem_(); } sink.list_(); } sink.tableCell_(); // column 3: rule violation count sink.tableCell(); String fixedmessage = getConfigAttribute( checkerConfig, null, "message", null ); // Grab the severity from the rule configuration, use null as default value String configSeverity = getConfigAttribute( checkerConfig, null, "severity", null ); long violations = countRuleViolation( results.getFiles().values(), ruleName, fixedmessage, configSeverity ); sink.text( String.valueOf( violations ) ); if ( violations > 0 ) { sink.nonBreakingSpace(); iconTool.iconSeverity( severity ); } sink.tableCell_(); sink.tableRow_(); } /** * Get the rule name from a violation. * * @param event the violation * @return the rule name, which is the class name without package and removed eventual "Check" suffix */ public String getRuleName( AuditEvent event ) { String eventSrcName = event.getSourceName(); if ( eventSrcName == null ) { return null; } if ( eventSrcName.endsWith( "Check" ) ) { eventSrcName = eventSrcName.substring( 0, eventSrcName.length() - 5 ); } return eventSrcName.substring( eventSrcName.lastIndexOf( '.' ) + 1 ); } /** * Check if a violation matches a rule. * * @param event the violation to check * @param ruleName The name of the rule * @param expectedMessage A message that, if it's not null, will be matched to the message from the violation * @param expectedSeverity A severity that, if it's not null, will be matched to the severity from the violation * @return The number of rule violations */ public boolean matchRule( AuditEvent event, String ruleName, String expectedMessage, String expectedSeverity ) { if ( !ruleName.equals( getRuleName( event ) ) ) { return false; } // check message too, for those that have a specific one. // like GenericIllegalRegexp and Regexp if ( expectedMessage != null ) { // event.getMessage() uses java.text.MessageFormat in its implementation. // Read MessageFormat Javadoc about single quote: // http://java.sun.com/j2se/1.4.2/docs/api/java/text/MessageFormat.html String msgWithoutSingleQuote = StringUtils.replace( expectedMessage, "'", "" ); return expectedMessage.equals( event.getMessage() ) || msgWithoutSingleQuote.equals( event.getMessage() ); } // Check the severity. This helps to distinguish between // different configurations for the same rule, where each // configuration has a different severity, like JavadocMetod. // See also http://jira.codehaus.org/browse/MCHECKSTYLE-41 if ( expectedSeverity != null ) { return expectedSeverity.equals( event.getSeverityLevel().getName() ); } return true; } /** * Count the number of violations for the given rule. * * @param files A collection over the set of files that has violations * @param ruleName The name of the rule * @param expectedMessage A message that, if it's not null, will be matched to the message from the violation * @param expectedSeverity A severity that, if it's not null, will be matched to the severity from the violation * @return The number of rule violations */ public long countRuleViolation( Collection<List<AuditEvent>> files, String ruleName, String expectedMessage, String expectedSeverity ) { long count = 0; for ( List<AuditEvent> errors : files ) { for ( AuditEvent event : errors ) { if ( matchRule( event, ruleName, expectedMessage, expectedSeverity ) ) { count++; } } } return count; } private void doSeveritySummary( CheckstyleResults results ) { sink.section1(); sink.sectionTitle1(); sink.text( bundle.getString( "report.checkstyle.summary" ) ); sink.sectionTitle1_(); sink.table(); sink.tableRow(); sink.tableHeaderCell(); sink.text( bundle.getString( "report.checkstyle.files" ) ); sink.tableHeaderCell_(); sink.tableHeaderCell(); iconTool.iconInfo( IconTool.TEXT_TITLE ); sink.tableHeaderCell_(); sink.tableHeaderCell(); iconTool.iconWarning( IconTool.TEXT_TITLE ); sink.tableHeaderCell_(); sink.tableHeaderCell(); iconTool.iconError( IconTool.TEXT_TITLE ); sink.tableHeaderCell_(); sink.tableRow_(); sink.tableRow(); sink.tableCell(); sink.text( String.valueOf( results.getFileCount() ) ); sink.tableCell_(); sink.tableCell(); sink.text( String.valueOf( results.getSeverityCount( SeverityLevel.INFO ) ) ); sink.tableCell_(); sink.tableCell(); sink.text( String.valueOf( results.getSeverityCount( SeverityLevel.WARNING ) ) ); sink.tableCell_(); sink.tableCell(); sink.text( String.valueOf( results.getSeverityCount( SeverityLevel.ERROR ) ) ); sink.tableCell_(); sink.tableRow_(); sink.table_(); sink.section1_(); } private void doFilesSummary( CheckstyleResults results ) { sink.section1(); sink.sectionTitle1(); sink.text( bundle.getString( "report.checkstyle.files" ) ); sink.sectionTitle1_(); sink.table(); sink.tableRow(); sink.tableHeaderCell(); sink.text( bundle.getString( "report.checkstyle.file" ) ); sink.tableHeaderCell_(); sink.tableHeaderCell(); iconTool.iconInfo( IconTool.TEXT_ABBREV ); sink.tableHeaderCell_(); sink.tableHeaderCell(); iconTool.iconWarning( IconTool.TEXT_ABBREV ); sink.tableHeaderCell_(); sink.tableHeaderCell(); iconTool.iconError( IconTool.TEXT_ABBREV ); sink.tableHeaderCell_(); sink.tableRow_(); // Sort the files before writing them to the report List<String> fileList = new ArrayList<String>( results.getFiles().keySet() ); Collections.sort( fileList ); for ( String filename : fileList ) { List<AuditEvent> violations = results.getFileViolations( filename ); if ( violations.isEmpty() ) { // skip files without violations continue; } sink.tableRow(); sink.tableCell(); sink.link( "#" + filename.replace( '/', '.' ) ); sink.text( filename ); sink.link_(); sink.tableCell_(); sink.tableCell(); sink.text( String.valueOf( results.getSeverityCount( violations, SeverityLevel.INFO ) ) ); sink.tableCell_(); sink.tableCell(); sink.text( String.valueOf( results.getSeverityCount( violations, SeverityLevel.WARNING ) ) ); sink.tableCell_(); sink.tableCell(); sink.text( String.valueOf( results.getSeverityCount( violations, SeverityLevel.ERROR ) ) ); sink.tableCell_(); sink.tableRow_(); } sink.table_(); sink.section1_(); } private void doDetails( CheckstyleResults results ) { sink.section1(); sink.sectionTitle1(); sink.text( bundle.getString( "report.checkstyle.details" ) ); sink.sectionTitle1_(); // Sort the files before writing their details to the report List<String> fileList = new ArrayList<String>( results.getFiles().keySet() ); Collections.sort( fileList ); for ( String file : fileList ) { List<AuditEvent> violations = results.getFileViolations( file ); if ( violations.isEmpty() ) { // skip files without violations continue; } sink.section2(); SinkEventAttributes attrs = new SinkEventAttributeSet(); attrs.addAttribute( SinkEventAttributes.ID, file.replace( '/', '.' ) ); sink.sectionTitle( Sink.SECTION_LEVEL_2, attrs ); sink.text( file ); sink.sectionTitle_( Sink.SECTION_LEVEL_2 ); sink.table(); sink.tableRow(); sink.tableHeaderCell(); sink.text( bundle.getString( "report.checkstyle.column.severity" ) ); sink.tableHeaderCell_(); sink.tableHeaderCell(); sink.text( bundle.getString( "report.checkstyle.column.message" ) ); sink.tableHeaderCell_(); sink.tableHeaderCell(); sink.text( bundle.getString( "report.checkstyle.column.line" ) ); sink.tableHeaderCell_(); sink.tableRow_(); doFileEvents( violations, file ); sink.table_(); sink.section2_(); } sink.section1_(); } private void doFileEvents( List<AuditEvent> eventList, String filename ) { for ( AuditEvent event : eventList ) { SeverityLevel level = event.getSeverityLevel(); if ( ( getSeverityLevel() != null ) && !( getSeverityLevel() != level ) ) { continue; } sink.tableRow(); sink.tableCell(); iconTool.iconSeverity( level.getName(), IconTool.TEXT_SIMPLE ); sink.tableCell_(); sink.tableCell(); sink.text( event.getMessage() ); sink.tableCell_(); sink.tableCell(); if ( getXrefLocation() != null ) { sink.link( getXrefLocation() + "/" + filename.replaceAll( "\\.java$", ".html" ) + "#L" + event.getLine() ); sink.text( String.valueOf( event.getLine() ) ); sink.link_(); } else { sink.text( String.valueOf( event.getLine() ) ); } sink.tableCell_(); sink.tableRow_(); } } public SeverityLevel getSeverityLevel() { return severityLevel; } public void setSeverityLevel( SeverityLevel severityLevel ) { this.severityLevel = severityLevel; } public boolean isEnableRulesSummary() { return enableRulesSummary; } public void setEnableRulesSummary( boolean enableRulesSummary ) { this.enableRulesSummary = enableRulesSummary; } public boolean isEnableSeveritySummary() { return enableSeveritySummary; } public void setEnableSeveritySummary( boolean enableSeveritySummary ) { this.enableSeveritySummary = enableSeveritySummary; } public boolean isEnableFilesSummary() { return enableFilesSummary; } public void setEnableFilesSummary( boolean enableFilesSummary ) { this.enableFilesSummary = enableFilesSummary; } public boolean isEnableRSS() { return enableRSS; } public void setEnableRSS( boolean enableRSS ) { this.enableRSS = enableRSS; } public String getXrefLocation() { return xrefLocation; } public void setXrefLocation( String xrefLocation ) { this.xrefLocation = xrefLocation; } public Configuration getCheckstyleConfig() { return checkstyleConfig; } public void setCheckstyleConfig( Configuration config ) { this.checkstyleConfig = config; } public void setTreeWalkerNames( List<String> treeWalkerNames ) { this.treeWalkerNames = treeWalkerNames; } public List<String> getTreeWalkerNames() { return treeWalkerNames; } }
maven-checkstyle-plugin/src/main/java/org/apache/maven/plugin/checkstyle/CheckstyleReportGenerator.java
package org.apache.maven.plugin.checkstyle; /* * 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. */ import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.ResourceBundle; import org.apache.maven.doxia.sink.Sink; import org.apache.maven.doxia.sink.SinkEventAttributeSet; import org.apache.maven.doxia.sink.SinkEventAttributes; import org.apache.maven.doxia.tools.SiteTool; import org.apache.maven.plugin.checkstyle.exec.CheckstyleResults; import org.apache.maven.plugin.logging.Log; import org.apache.maven.plugin.logging.SystemStreamLog; import org.codehaus.plexus.util.StringUtils; import com.puppycrawl.tools.checkstyle.api.AuditEvent; import com.puppycrawl.tools.checkstyle.api.CheckstyleException; import com.puppycrawl.tools.checkstyle.api.Configuration; import com.puppycrawl.tools.checkstyle.api.SeverityLevel; /** * Generate a report based on CheckstyleResults. * * @version $Id$ */ public class CheckstyleReportGenerator { private Log log; private final File basedir; private final ResourceBundle bundle; private final Sink sink; private SeverityLevel severityLevel; private Configuration checkstyleConfig; private boolean enableRulesSummary; private boolean enableSeveritySummary; private boolean enableFilesSummary; private boolean enableRSS; private final SiteTool siteTool; private String xrefLocation; private List<String> treeWalkerNames = Collections.singletonList( "TreeWalker" ); private final IconTool iconTool; public CheckstyleReportGenerator( Sink sink, ResourceBundle bundle, File basedir, SiteTool siteTool ) { this.bundle = bundle; this.sink = sink; this.basedir = basedir; this.siteTool = siteTool; this.enableRulesSummary = true; this.enableSeveritySummary = true; this.enableFilesSummary = true; this.enableRSS = true; this.iconTool = new IconTool( sink, bundle ); } public Log getLog() { if ( this.log == null ) { this.log = new SystemStreamLog(); } return this.log; } public void setLog( Log log ) { this.log = log; } private String getTitle() { String title; if ( getSeverityLevel() == null ) { title = bundle.getString( "report.checkstyle.title" ); } else { title = bundle.getString( "report.checkstyle.severity_title" ) + severityLevel.getName(); } return title; } public void generateReport( CheckstyleResults results ) { doHeading(); if ( getSeverityLevel() == null ) { if ( enableSeveritySummary ) { doSeveritySummary( results ); } if ( enableFilesSummary ) { doFilesSummary( results ); } if ( enableRulesSummary ) { doRulesSummary( results ); } } doDetails( results ); sink.body_(); sink.flush(); sink.close(); } private void doHeading() { sink.head(); sink.title(); sink.text( getTitle() ); sink.title_(); sink.head_(); sink.body(); sink.section1(); sink.sectionTitle1(); sink.text( getTitle() ); sink.sectionTitle1_(); sink.paragraph(); sink.text( bundle.getString( "report.checkstyle.checkstylelink" ) + " " ); sink.link( "http://checkstyle.sourceforge.net/" ); sink.text( "Checkstyle" ); sink.link_(); sink.text( "." ); if ( enableRSS ) { sink.nonBreakingSpace(); sink.link( "checkstyle.rss" ); sink.figure(); sink.figureCaption(); sink.text( "rss feed" ); sink.figureCaption_(); sink.figureGraphics( "images/rss.png" ); sink.figure_(); sink.link_(); } sink.paragraph_(); sink.section1_(); } /** * Get the value of the specified attribute from the Checkstyle configuration. * If parentConfigurations is non-null and non-empty, the parent * configurations are searched if the attribute cannot be found in the * current configuration. If the attribute is still not found, the * specified default value will be returned. * * @param config The current Checkstyle configuration * @param parentConfigurations The configurations for the parents of the current configuration * @param attributeName The name of the attribute * @param defaultValue The default value to use if the attribute cannot be found in any configuration * @return The value of the specified attribute */ private String getConfigAttribute( Configuration config, List<Configuration> parentConfigurations, String attributeName, String defaultValue ) { String ret; try { ret = config.getAttribute( attributeName ); } catch ( CheckstyleException e ) { // Try to find the attribute in a parent, if there are any if ( parentConfigurations != null && !parentConfigurations.isEmpty() ) { Configuration parentConfiguration = parentConfigurations.get( parentConfigurations.size() - 1 ); List<Configuration> newParentConfigurations = new ArrayList<Configuration>( parentConfigurations ); // Remove the last parent newParentConfigurations.remove( parentConfiguration ); ret = getConfigAttribute( parentConfiguration, newParentConfigurations, attributeName, defaultValue ); } else { ret = defaultValue; } } return ret; } /** * Create the rules summary section of the report. * * @param results The results to summarize */ private void doRulesSummary( CheckstyleResults results ) { if ( checkstyleConfig == null ) { return; } sink.section1(); sink.sectionTitle1(); sink.text( bundle.getString( "report.checkstyle.rules" ) ); sink.sectionTitle1_(); sink.table(); sink.tableRow(); sink.tableHeaderCell(); sink.text( bundle.getString( "report.checkstyle.column.severity" ) ); sink.tableHeaderCell_(); sink.tableHeaderCell(); sink.text( bundle.getString( "report.checkstyle.rule" ) ); sink.tableHeaderCell_(); sink.tableHeaderCell(); sink.text( bundle.getString( "report.checkstyle.violations" ) ); sink.tableHeaderCell_(); sink.tableRow_(); // Top level should be the checker. if ( "checker".equalsIgnoreCase( checkstyleConfig.getName() ) ) { doRuleChildren( checkstyleConfig, null, results ); } else { sink.tableRow(); sink.tableCell(); sink.text( bundle.getString( "report.checkstyle.norule" ) ); sink.tableCell_(); sink.tableRow_(); } sink.table_(); sink.section1_(); } /** * Create a summary for each Checkstyle rule. * * @param configuration The Checkstyle configuration * @param parentConfigurations A List of configurations for the chain of parents to the current configuration * @param results The results to summarize */ private void doRuleChildren( Configuration configuration, List<Configuration> parentConfigurations, CheckstyleResults results ) { // Remember the chain of parent configurations if ( parentConfigurations == null ) { parentConfigurations = new ArrayList<Configuration>(); } // The "oldest" parent will be first in the list parentConfigurations.add( configuration ); if ( getLog().isDebugEnabled() ) { // Log the parent configuration path StringBuilder parentPath = new StringBuilder(); for ( Iterator<Configuration> iterator = parentConfigurations.iterator(); iterator.hasNext(); ) { Configuration parentConfiguration = iterator.next(); parentPath.append( parentConfiguration.getName() ); if ( iterator.hasNext() ) { parentPath.append( " --> " ); } } if ( parentPath.length() > 0 ) { getLog().debug( "Parent Configuration Path: " + parentPath.toString() ); } } for ( Configuration configChild : configuration.getChildren() ) { String ruleName = configChild.getName(); if ( treeWalkerNames.contains( ruleName ) ) { // special sub-case: TreeWalker is the parent of multiple rules, not an effective rule doRuleChildren( configChild, parentConfigurations, results ); } else { doRuleRow( configChild, parentConfigurations, ruleName, results ); } } } /** * Create a summary for one Checkstyle rule. * * @param checkerConfig Configuration for the Checkstyle rule * @param parentConfigurations Configurations for the parents of this rule * @param ruleName The name of the rule, for example "JavadocMethod" * @param results The results to summarize */ private void doRuleRow( Configuration checkerConfig, List<Configuration> parentConfigurations, String ruleName, CheckstyleResults results ) { sink.tableRow(); // column 1: severity sink.tableCell(); // Grab the severity from the rule configuration, this time use error as default value // Also pass along all parent configurations, so that we can try to find the severity there String severity = getConfigAttribute( checkerConfig, parentConfigurations, "severity", "error" ); iconTool.iconSeverity( severity, IconTool.TEXT_SIMPLE ); sink.tableCell_(); // column 2: Rule name + configured attributes sink.tableCell(); sink.text( ruleName ); List<String> attribnames = new ArrayList<String>( Arrays.asList( checkerConfig.getAttributeNames() ) ); attribnames.remove( "severity" ); // special value (deserves unique column) if ( !attribnames.isEmpty() ) { sink.list(); for ( String name : attribnames ) { sink.listItem(); sink.bold(); sink.text( name ); sink.bold_(); String value = getConfigAttribute( checkerConfig, null, name, "" ); // special case, Header.header and RegexpHeader.header if ( "header".equals( name ) && ( "Header".equals( ruleName ) || "RegexpHeader".equals( ruleName ) ) ) { String[] lines = StringUtils.split( value, "\\n" ); int linenum = 1; for ( String line : lines ) { sink.lineBreak(); sink.rawText( "<span style=\"color: gray\">" ); sink.text( linenum + ":" ); sink.rawText( "</span>" ); sink.nonBreakingSpace(); sink.monospaced(); sink.text( line ); sink.monospaced_(); linenum++; } } else if ( "headerFile".equals( name ) && "RegexpHeader".equals( ruleName ) ) { sink.text( ": " ); sink.monospaced(); sink.text( "\"" ); if ( basedir != null ) { // Make the headerFile value relative to ${basedir} String path = siteTool.getRelativePath( value, basedir.getAbsolutePath() ); sink.text( path.replace( '\\', '/' ) ); } else { sink.text( value ); } sink.text( "\"" ); sink.monospaced_(); } else { sink.text( ": " ); sink.monospaced(); sink.text( "\"" ); sink.text( value ); sink.text( "\"" ); sink.monospaced_(); } sink.listItem_(); } sink.list_(); } sink.tableCell_(); // column 3: rule violation count sink.tableCell(); String fixedmessage = getConfigAttribute( checkerConfig, null, "message", null ); // Grab the severity from the rule configuration, use null as default value String configSeverity = getConfigAttribute( checkerConfig, null, "severity", null ); long violations = countRuleViolation( results.getFiles().values(), ruleName, fixedmessage, configSeverity ); sink.text( String.valueOf( violations ) ); if ( violations > 0 ) { sink.nonBreakingSpace(); iconTool.iconSeverity( severity ); } sink.tableCell_(); sink.tableRow_(); } /** * Get the rule name from a violation. * * @param event the violation * @return the rule name, which is the class name without package and removed eventual "Check" suffix */ public String getRuleName( AuditEvent event ) { String eventSrcName = event.getSourceName(); if ( eventSrcName == null ) { return null; } if ( eventSrcName.endsWith( "Check" ) ) { eventSrcName = eventSrcName.substring( 0, eventSrcName.length() - 5 ); } return eventSrcName.substring( eventSrcName.lastIndexOf( '.' ) + 1 ); } /** * Check if a violation matches a rule. * * @param event the violation to check * @param ruleName The name of the rule * @param expectedMessage A message that, if it's not null, will be matched to the message from the violation * @param expectedSeverity A severity that, if it's not null, will be matched to the severity from the violation * @return The number of rule violations */ public boolean matchRule( AuditEvent event, String ruleName, String expectedMessage, String expectedSeverity ) { if ( !ruleName.equals( getRuleName( event ) ) ) { return false; } // check message too, for those that have a specific one. // like GenericIllegalRegexp and Regexp if ( expectedMessage != null ) { // event.getMessage() uses java.text.MessageFormat in its implementation. // Read MessageFormat Javadoc about single quote: // http://java.sun.com/j2se/1.4.2/docs/api/java/text/MessageFormat.html String msgWithoutSingleQuote = StringUtils.replace( expectedMessage, "'", "" ); return expectedMessage.equals( event.getMessage() ) || msgWithoutSingleQuote.equals( event.getMessage() ); } // Check the severity. This helps to distinguish between // different configurations for the same rule, where each // configuration has a different severity, like JavadocMetod. // See also http://jira.codehaus.org/browse/MCHECKSTYLE-41 if ( expectedSeverity != null ) { return expectedSeverity.equals( event.getSeverityLevel().getName() ); } return true; } /** * Count the number of violations for the given rule. * * @param files A collection over the set of files that has violations * @param ruleName The name of the rule * @param expectedMessage A message that, if it's not null, will be matched to the message from the violation * @param expectedSeverity A severity that, if it's not null, will be matched to the severity from the violation * @return The number of rule violations */ public long countRuleViolation( Collection<List<AuditEvent>> files, String ruleName, String expectedMessage, String expectedSeverity ) { long count = 0; for ( List<AuditEvent> errors : files ) { for ( AuditEvent event : errors ) { if ( matchRule( event, ruleName, expectedMessage, expectedSeverity ) ) { count++; } } } return count; } private void doSeveritySummary( CheckstyleResults results ) { sink.section1(); sink.sectionTitle1(); sink.text( bundle.getString( "report.checkstyle.summary" ) ); sink.sectionTitle1_(); sink.table(); sink.tableRow(); sink.tableHeaderCell(); sink.text( bundle.getString( "report.checkstyle.files" ) ); sink.tableHeaderCell_(); sink.tableHeaderCell(); iconTool.iconInfo( IconTool.TEXT_TITLE ); sink.tableHeaderCell_(); sink.tableHeaderCell(); iconTool.iconWarning( IconTool.TEXT_TITLE ); sink.tableHeaderCell_(); sink.tableHeaderCell(); iconTool.iconError( IconTool.TEXT_TITLE ); sink.tableHeaderCell_(); sink.tableRow_(); sink.tableRow(); sink.tableCell(); sink.text( String.valueOf( results.getFileCount() ) ); sink.tableCell_(); sink.tableCell(); sink.text( String.valueOf( results.getSeverityCount( SeverityLevel.INFO ) ) ); sink.tableCell_(); sink.tableCell(); sink.text( String.valueOf( results.getSeverityCount( SeverityLevel.WARNING ) ) ); sink.tableCell_(); sink.tableCell(); sink.text( String.valueOf( results.getSeverityCount( SeverityLevel.ERROR ) ) ); sink.tableCell_(); sink.tableRow_(); sink.table_(); sink.section1_(); } private void doFilesSummary( CheckstyleResults results ) { sink.section1(); sink.sectionTitle1(); sink.text( bundle.getString( "report.checkstyle.files" ) ); sink.sectionTitle1_(); sink.table(); sink.tableRow(); sink.tableHeaderCell(); sink.text( bundle.getString( "report.checkstyle.file" ) ); sink.tableHeaderCell_(); sink.tableHeaderCell(); iconTool.iconInfo( IconTool.TEXT_ABBREV ); sink.tableHeaderCell_(); sink.tableHeaderCell(); iconTool.iconWarning( IconTool.TEXT_ABBREV ); sink.tableHeaderCell_(); sink.tableHeaderCell(); iconTool.iconError( IconTool.TEXT_ABBREV ); sink.tableHeaderCell_(); sink.tableRow_(); // Sort the files before writing them to the report List<String> fileList = new ArrayList<String>( results.getFiles().keySet() ); Collections.sort( fileList ); for ( String filename : fileList ) { List<AuditEvent> violations = results.getFileViolations( filename ); if ( violations.isEmpty() ) { // skip files without violations continue; } sink.tableRow(); sink.tableCell(); sink.link( "#" + filename.replace( '/', '.' ) ); sink.text( filename ); sink.link_(); sink.tableCell_(); sink.tableCell(); sink.text( String.valueOf( results.getSeverityCount( violations, SeverityLevel.INFO ) ) ); sink.tableCell_(); sink.tableCell(); sink.text( String.valueOf( results.getSeverityCount( violations, SeverityLevel.WARNING ) ) ); sink.tableCell_(); sink.tableCell(); sink.text( String.valueOf( results.getSeverityCount( violations, SeverityLevel.ERROR ) ) ); sink.tableCell_(); sink.tableRow_(); } sink.table_(); sink.section1_(); } private void doDetails( CheckstyleResults results ) { sink.section1(); sink.sectionTitle1(); sink.text( bundle.getString( "report.checkstyle.details" ) ); sink.sectionTitle1_(); // Sort the files before writing their details to the report List<String> fileList = new ArrayList<String>( results.getFiles().keySet() ); Collections.sort( fileList ); for ( String file : fileList ) { List<AuditEvent> violations = results.getFileViolations( file ); if ( violations.isEmpty() ) { // skip files without violations continue; } sink.section2(); SinkEventAttributes attrs = new SinkEventAttributeSet(); attrs.addAttribute( SinkEventAttributes.ID, file.replace( '/', '.' ) ); sink.sectionTitle( Sink.SECTION_LEVEL_2, attrs ); sink.text( file ); sink.sectionTitle_( Sink.SECTION_LEVEL_2 ); sink.table(); sink.tableRow(); sink.tableHeaderCell(); sink.text( bundle.getString( "report.checkstyle.column.severity" ) ); sink.tableHeaderCell_(); sink.tableHeaderCell(); sink.text( bundle.getString( "report.checkstyle.column.message" ) ); sink.tableHeaderCell_(); sink.tableHeaderCell(); sink.text( bundle.getString( "report.checkstyle.column.line" ) ); sink.tableHeaderCell_(); sink.tableRow_(); doFileEvents( violations, file ); sink.table_(); sink.section2_(); } sink.section1_(); } private void doFileEvents( List<AuditEvent> eventList, String filename ) { for ( AuditEvent event : eventList ) { SeverityLevel level = event.getSeverityLevel(); if ( ( getSeverityLevel() != null ) && !( getSeverityLevel() != level ) ) { continue; } sink.tableRow(); sink.tableCell(); switch( level ) { case INFO: iconTool.iconInfo( IconTool.TEXT_SIMPLE ); break; case WARNING: iconTool.iconWarning( IconTool.TEXT_SIMPLE ); break; case ERROR: iconTool.iconError( IconTool.TEXT_SIMPLE ); break; default: break; } sink.tableCell_(); sink.tableCell(); sink.text( event.getMessage() ); sink.tableCell_(); sink.tableCell(); int line = event.getLine(); if ( getXrefLocation() != null ) { sink .link( getXrefLocation() + "/" + filename.replaceAll( "\\.java$", ".html" ) + "#L" + line ); } if ( line != 0 ) { sink.text( String.valueOf( event.getLine() ) ); } if ( getXrefLocation() != null ) { sink.link_(); } sink.tableCell_(); sink.tableRow_(); } } public SeverityLevel getSeverityLevel() { return severityLevel; } public void setSeverityLevel( SeverityLevel severityLevel ) { this.severityLevel = severityLevel; } public boolean isEnableRulesSummary() { return enableRulesSummary; } public void setEnableRulesSummary( boolean enableRulesSummary ) { this.enableRulesSummary = enableRulesSummary; } public boolean isEnableSeveritySummary() { return enableSeveritySummary; } public void setEnableSeveritySummary( boolean enableSeveritySummary ) { this.enableSeveritySummary = enableSeveritySummary; } public boolean isEnableFilesSummary() { return enableFilesSummary; } public void setEnableFilesSummary( boolean enableFilesSummary ) { this.enableFilesSummary = enableFilesSummary; } public boolean isEnableRSS() { return enableRSS; } public void setEnableRSS( boolean enableRSS ) { this.enableRSS = enableRSS; } public String getXrefLocation() { return xrefLocation; } public void setXrefLocation( String xrefLocation ) { this.xrefLocation = xrefLocation; } public Configuration getCheckstyleConfig() { return checkstyleConfig; } public void setCheckstyleConfig( Configuration config ) { this.checkstyleConfig = config; } public void setTreeWalkerNames( List<String> treeWalkerNames ) { this.treeWalkerNames = treeWalkerNames; } public List<String> getTreeWalkerNames() { return treeWalkerNames; } }
code simplification git-svn-id: 6038db50b076e48c7926ed71fd94f8e91be2fbc9@1608113 13f79535-47bb-0310-9956-ffa450edef68
maven-checkstyle-plugin/src/main/java/org/apache/maven/plugin/checkstyle/CheckstyleReportGenerator.java
code simplification
Java
apache-2.0
f592daad059a41f56305305943372c846eb8e2c9
0
gonmarques/commons-collections,MuShiiii/commons-collections,mohanaraosv/commons-collections,MuShiiii/commons-collections,apache/commons-collections,MuShiiii/commons-collections,apache/commons-collections,sandrineBeauche/commons-collections,sandrineBeauche/commons-collections,jankill/commons-collections,mohanaraosv/commons-collections,mohanaraosv/commons-collections,gonmarques/commons-collections,jankill/commons-collections,sandrineBeauche/commons-collections,jankill/commons-collections,apache/commons-collections
/* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//collections/src/test/org/apache/commons/collections/Attic/TestIterator.java,v 1.4 2002/02/25 23:37:38 morgand Exp $ * $Revision: 1.4 $ * $Date: 2002/02/25 23:37:38 $ * * ==================================================================== * * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2001 The Apache Software Foundation. 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. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Commons", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.commons.collections; import java.util.Iterator; import java.util.NoSuchElementException; /** * Base class for tetsing Iterator interface * * @author Morgan Delagrange */ public abstract class TestIterator extends TestObject { public TestIterator(String testName) { super(testName); } public abstract Iterator makeEmptyIterator(); public abstract Iterator makeFullIterator(); /** * Whether or not we are testing an iterator that can be * empty. Default is true. * * @return true if Iterators can be empty */ public boolean supportsEmptyIterator() { return true; } /** * Whether or not we are testing an iterator that can contain * elements. Default is true. * * @return true if Iterators can be empty */ public boolean supportsFullIterator() { return true; } /** * Should throw a NoSuchElementException. */ public void testEmptyIterator() { if (supportsEmptyIterator() == false) { return; } Iterator iter = makeEmptyIterator(); assertTrue("hasNext() should return false for empty iterators",iter.hasNext() == false); try { iter.next(); fail("NoSuchElementException must be thrown when Iterator is exhausted"); } catch (NoSuchElementException e) { } } /** * NoSuchElementException (or any other exception) * should not be thrown for the first element. * NoSuchElementException must be thrown when * hasNext() returns false */ public void testFullIterator() { if (supportsFullIterator() == false) { return; } Iterator iter = makeFullIterator(); assertTrue("hasNext() should return true for at least one element",iter.hasNext()); try { iter.next(); } catch (NoSuchElementException e) { fail("Full iterators must have at least one element"); } while (iter.hasNext()) { iter.next(); } try { iter.next(); fail("NoSuchElementException must be thrown when Iterator is exhausted"); } catch (NoSuchElementException e) { } } }
src/test/org/apache/commons/collections/TestIterator.java
/* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//collections/src/test/org/apache/commons/collections/Attic/TestIterator.java,v 1.3 2002/02/25 23:26:25 morgand Exp $ * $Revision: 1.3 $ * $Date: 2002/02/25 23:26:25 $ * * ==================================================================== * * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2001 The Apache Software Foundation. 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. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Commons", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.commons.collections; import java.util.Iterator; import java.util.NoSuchElementException; /** * Base class for tetsing Iterator interface * * @author Morgan Delagrange */ public abstract class TestIterator extends TestObject { public TestIterator(String testName) { super(testName); } public abstract Iterator makeEmptyIterator(); public abstract Iterator makeFullIterator(); /** * Should throw a NoSuchElementException. */ public void testEmptyIterator() { Iterator iter = makeEmptyIterator(); assertTrue("hasNext() should return false for empty iterators",iter.hasNext() == false); try { iter.next(); fail("NoSuchElementException must be thrown when Iterator is exhausted"); } catch (NoSuchElementException e) { } } /** * NoSuchElementException (or any other exception) * should not be thrown for the first element. * NoSuchElementException must be thrown when * hasNext() returns false */ public void testFullIterator() { Iterator iter = makeFullIterator(); assertTrue("hasNext() should return true for at least one element",iter.hasNext()); try { iter.next(); } catch (NoSuchElementException e) { fail("Full iterators must have at least one element"); } while (iter.hasNext()) { iter.next(); } try { iter.next(); fail("NoSuchElementException must be thrown when Iterator is exhausted"); } catch (NoSuchElementException e) { } } }
added methods to allow for iterators that can't be full, or that can't be empty git-svn-id: b713d2d75405ee089de821fbacfe0f8fc04e1abf@130579 13f79535-47bb-0310-9956-ffa450edef68
src/test/org/apache/commons/collections/TestIterator.java
added methods to allow for iterators that can't be full, or that can't be empty
Java
apache-2.0
561e2fa4737ece05b1c04212350b2fa44f2ac98e
0
bonigarcia/selenium-jupiter,bonigarcia/selenium-jupiter
/* * (C) Copyright 2017 Boni Garcia (http://bonigarcia.github.io/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package io.github.bonigarcia; import static com.google.common.collect.ImmutableList.copyOf; import static io.github.bonigarcia.SeleniumJupiter.config; import static java.lang.invoke.MethodHandles.lookup; import static java.nio.charset.Charset.defaultCharset; import static java.nio.file.Files.readAllBytes; import static java.nio.file.Paths.get; import static java.util.Arrays.asList; import static java.util.Arrays.stream; import static java.util.Collections.singletonList; import static java.util.Optional.empty; import static java.util.stream.Collectors.toList; import static org.slf4j.LoggerFactory.getLogger; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.net.URL; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.stream.Stream; import org.apache.commons.io.IOUtils; import org.junit.jupiter.api.TestTemplate; import org.junit.jupiter.api.extension.AfterEachCallback; import org.junit.jupiter.api.extension.Extension; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.ParameterContext; import org.junit.jupiter.api.extension.ParameterResolver; import org.junit.jupiter.api.extension.TestTemplateInvocationContext; import org.junit.jupiter.api.extension.TestTemplateInvocationContextProvider; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.edge.EdgeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.opera.OperaDriver; import org.openqa.selenium.phantomjs.PhantomJSDriver; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.safari.SafariDriver; import org.slf4j.Logger; import com.google.gson.Gson; import com.spotify.docker.client.exceptions.DockerCertificateException; import io.appium.java_client.AppiumDriver; import io.github.bonigarcia.BrowsersTemplate.Browser; import io.github.bonigarcia.handler.AppiumDriverHandler; import io.github.bonigarcia.handler.ChromeDriverHandler; import io.github.bonigarcia.handler.DriverHandler; import io.github.bonigarcia.handler.EdgeDriverHandler; import io.github.bonigarcia.handler.FirefoxDriverHandler; import io.github.bonigarcia.handler.ListDriverHandler; import io.github.bonigarcia.handler.OperaDriverHandler; import io.github.bonigarcia.handler.OtherDriverHandler; import io.github.bonigarcia.handler.RemoteDriverHandler; import io.github.bonigarcia.handler.SafariDriverHandler; import io.github.bonigarcia.wdm.WebDriverManager; /** * Selenium extension for Jupiter (JUnit 5) tests. * * @author Boni Garcia ([email protected]) * @since 1.0.0 */ public class SeleniumExtension implements ParameterResolver, AfterEachCallback, TestTemplateInvocationContextProvider { final Logger log = getLogger(lookup().lookupClass()); static final String CLASSPATH_PREFIX = "classpath:"; private List<Class<?>> typeList = new CopyOnWriteArrayList<>(); private Map<String, List<DriverHandler>> driverHandlerMap = new ConcurrentHashMap<>(); private Map<String, Class<?>> handlerMap = new ConcurrentHashMap<>(); private Map<String, Class<?>> templateHandlerMap = new ConcurrentHashMap<>(); private Map<String, Map<String, DockerContainer>> containersMap = new ConcurrentHashMap<>(); private DockerService dockerService; private Map<String, List<Browser>> browserListMap = new ConcurrentHashMap<>(); private List<List<Browser>> browserListList; public SeleniumExtension() { addEntry(handlerMap, "org.openqa.selenium.chrome.ChromeDriver", ChromeDriverHandler.class); addEntry(handlerMap, "org.openqa.selenium.firefox.FirefoxDriver", FirefoxDriverHandler.class); addEntry(handlerMap, "org.openqa.selenium.edge.EdgeDriver", EdgeDriverHandler.class); addEntry(handlerMap, "org.openqa.selenium.opera.OperaDriver", OperaDriverHandler.class); addEntry(handlerMap, "org.openqa.selenium.safari.SafariDriver", SafariDriverHandler.class); addEntry(handlerMap, "org.openqa.selenium.remote.RemoteWebDriver", RemoteDriverHandler.class); addEntry(handlerMap, "org.openqa.selenium.WebDriver", RemoteDriverHandler.class); addEntry(handlerMap, "io.appium.java_client.AppiumDriver", AppiumDriverHandler.class); addEntry(handlerMap, "java.util.List", ListDriverHandler.class); addEntry(handlerMap, "org.openqa.selenium.phantomjs.PhantomJSDriver", OtherDriverHandler.class); addEntry(templateHandlerMap, "chrome", ChromeDriver.class); addEntry(templateHandlerMap, "firefox", FirefoxDriver.class); addEntry(templateHandlerMap, "edge", EdgeDriver.class); addEntry(templateHandlerMap, "opera", OperaDriver.class); addEntry(templateHandlerMap, "safari", SafariDriver.class); addEntry(templateHandlerMap, "appium", AppiumDriver.class); addEntry(templateHandlerMap, "phantomjs", PhantomJSDriver.class); addEntry(templateHandlerMap, "iexplorer", InternetExplorerDriver.class); addEntry(templateHandlerMap, "chrome-in-docker", RemoteWebDriver.class); addEntry(templateHandlerMap, "firefox-in-docker", RemoteWebDriver.class); addEntry(templateHandlerMap, "opera-in-docker", RemoteWebDriver.class); addEntry(templateHandlerMap, "android", RemoteWebDriver.class); } @Override public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) { Class<?> type = parameterContext.getParameter().getType(); return (WebDriver.class.isAssignableFrom(type) || type.equals(List.class)) && !isTestTemplate(extensionContext); } @Override public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) { String contextId = extensionContext.getUniqueId(); Parameter parameter = parameterContext.getParameter(); Class<?> type = parameter.getType(); boolean isTemplate = isTestTemplate(extensionContext); boolean isGeneric = type.equals(RemoteWebDriver.class) || type.equals(WebDriver.class); String url = null; Browser browser = null; // Check template if (isGeneric && !browserListMap.isEmpty()) { browser = getBrowser(contextId, parameter, isTemplate); } if (browser != null) { type = templateHandlerMap.get(browser.getType()); url = browser.getUrl(); } // WebDriverManager if (!typeList.contains(type)) { WebDriverManager.getInstance(type).setup(); typeList.add(type); } // Handler DriverHandler driverHandler = null; Class<?> constructorClass = handlerMap.containsKey(type.getName()) ? handlerMap.get(type.getName()) : OtherDriverHandler.class; boolean isRemote = constructorClass.equals(RemoteDriverHandler.class); if (url != null && !url.isEmpty()) { constructorClass = RemoteDriverHandler.class; isRemote = true; } try { driverHandler = getDriverHandler(extensionContext, parameter, type, constructorClass, browser, isRemote); if (type.equals(RemoteWebDriver.class) || type.equals(WebDriver.class) || type.equals(List.class)) { initHandlerForDocker(contextId, driverHandler); } if (!isTemplate && isGeneric && isRemote) { ((RemoteDriverHandler) driverHandler).setParent(this); ((RemoteDriverHandler) driverHandler) .setParameterContext(parameterContext); } putDriverHandlerInMap(extensionContext.getUniqueId(), driverHandler); } catch (Exception e) { handleException(parameter, driverHandler, constructorClass, e); } return resolveHandler(parameter, driverHandler); } private void putDriverHandlerInMap(String contextId, DriverHandler driverHandler) { if (driverHandlerMap.containsKey(contextId)) { driverHandlerMap.get(contextId).add(driverHandler); } else { List<DriverHandler> driverHandlers = new ArrayList<>(); driverHandlers.add(driverHandler); driverHandlerMap.put(contextId, driverHandlers); } log.trace("Adding {} to handler map (id {})", driverHandler, contextId); } private Browser getBrowser(String contextId, Parameter parameter, boolean isTemplate) { Integer index = isTemplate ? Integer.valueOf(parameter.getName().replaceAll("arg", "")) : 0; Browser browser = null; List<Browser> browserList = getValueFromContextId(browserListMap, contextId); if (browserList == null) { log.warn("Browser list for context id {} not found", contextId); } else { browser = browserList.get(index); } return browser; } private Object resolveHandler(Parameter parameter, DriverHandler driverHandler) { if (driverHandler != null) { driverHandler.resolve(); return driverHandler.getObject(); } else if (config().isExceptionWhenNoDriver()) { throw new SeleniumJupiterException( "No valid handler for " + parameter + " was found"); } else { return null; } } private DriverHandler getDriverHandler(ExtensionContext extensionContext, Parameter parameter, Class<?> type, Class<?> constructorClass, Browser browser, boolean isRemote) throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { DriverHandler driverHandler = null; if (isRemote && browser != null) { driverHandler = (DriverHandler) constructorClass .getDeclaredConstructor(Parameter.class, ExtensionContext.class, Browser.class) .newInstance(parameter, extensionContext, browser); } else if (constructorClass.equals(OtherDriverHandler.class) && !browserListMap.isEmpty()) { driverHandler = (DriverHandler) constructorClass .getDeclaredConstructor(Parameter.class, ExtensionContext.class, Class.class) .newInstance(parameter, extensionContext, type); } else { driverHandler = (DriverHandler) constructorClass .getDeclaredConstructor(Parameter.class, ExtensionContext.class) .newInstance(parameter, extensionContext); } return driverHandler; } public void initHandlerForDocker(String contextId, DriverHandler driverHandler) throws DockerCertificateException { LinkedHashMap<String, DockerContainer> containerMap = new LinkedHashMap<>(); driverHandler.setContainerMap(containerMap); containersMap.put(contextId, containerMap); if (dockerService == null) { dockerService = new DockerService(); } driverHandler.setDockerService(dockerService); } private void handleException(Parameter parameter, DriverHandler driverHandler, Class<?> constructorClass, Exception e) { if (driverHandler != null && driverHandler.throwExceptionWhenNoDriver()) { log.error("Exception resolving {}", parameter, e); throw new SeleniumJupiterException(e); } else { log.warn("Exception creating {}", constructorClass, e); } } @Override public void afterEach(ExtensionContext extensionContext) { // Make screenshots if required and close browsers ScreenshotManager screenshotManager = new ScreenshotManager( extensionContext); String contextId = extensionContext.getUniqueId(); List<DriverHandler> driverHandlers = getValueFromContextId( driverHandlerMap, contextId); if (driverHandlers == null) { log.warn("Driver handler for context id {} not found", contextId); return; } for (DriverHandler driverHandler : copyOf(driverHandlers).reverse()) { // Quit WebDriver object Object object = driverHandler.getObject(); try { quitWebDriver(object, driverHandler, screenshotManager); } catch (Exception e) { log.warn("Exception closing webdriver object {}", object, e); } // Clean handler try { driverHandler.cleanup(); } catch (Exception e) { log.warn("Exception cleaning handler {}", driverHandler, e); } } // Clear handler map driverHandlerMap.remove(contextId); } @SuppressWarnings("unchecked") private void quitWebDriver(Object object, DriverHandler driverHandler, ScreenshotManager screenshotManager) { if (object != null) { if (List.class.isAssignableFrom(object.getClass())) { List<RemoteWebDriver> webDriverList = (List<RemoteWebDriver>) object; for (int i = 0; i < webDriverList.size(); i++) { screenshotManager.makeScreenshot(webDriverList.get(i), driverHandler.getName() + "_" + i); webDriverList.get(i).quit(); } } else { WebDriver webDriver = (WebDriver) object; if (driverHandler.getName() != null) { screenshotManager.makeScreenshot(webDriver, driverHandler.getName()); } webDriver.quit(); } } } private <T extends Object> T getValueFromContextId(Map<String, T> map, String contextId) { T output = map.get(contextId); if (output == null) { int i = contextId.lastIndexOf('/'); if (i != -1) { contextId = contextId.substring(0, i); output = map.get(contextId); } } return output; } @Override public boolean supportsTestTemplate(ExtensionContext context) { boolean allWebDriver = false; if (context.getTestMethod().isPresent()) { allWebDriver = !stream( context.getTestMethod().get().getParameterTypes()) .map(s -> s.equals(WebDriver.class) || s.equals(RemoteWebDriver.class)) .collect(toList()).contains(false); } return allWebDriver; } @Override public Stream<TestTemplateInvocationContext> provideTestTemplateInvocationContexts( ExtensionContext extensionContext) { String contextId = extensionContext.getUniqueId(); try { // 1. By JSON content String browserJsonContent = config() .getBrowserTemplateJsonContent(); if (browserJsonContent.isEmpty()) { // 2. By JSON file String browserJsonFile = config().getBrowserTemplateJsonFile(); if (browserJsonFile.startsWith(CLASSPATH_PREFIX)) { String browserJsonInClasspath = browserJsonFile .substring(CLASSPATH_PREFIX.length()); InputStream resourceAsStream = this.getClass() .getResourceAsStream("/" + browserJsonInClasspath); if (resourceAsStream != null) { browserJsonContent = IOUtils.toString(resourceAsStream, defaultCharset()); } } else { browserJsonContent = new String( readAllBytes(get(browserJsonFile))); } } if (!browserJsonContent.isEmpty()) { return new Gson() .fromJson(browserJsonContent, BrowsersTemplate.class) .getStream().map(b -> invocationContext(b, this)); } // 3. By setter if (browserListList != null) { return browserListList.stream() .map(b -> invocationContext(b, this)); } if (browserListMap != null) { return Stream.of( invocationContext(browserListMap.get(contextId), this)); } } catch (IOException e) { throw new SeleniumJupiterException(e); } throw new SeleniumJupiterException( "No browser scenario registered for test template"); } private synchronized TestTemplateInvocationContext invocationContext( List<Browser> template, SeleniumExtension parent) { return new TestTemplateInvocationContext() { @Override public String getDisplayName(int invocationIndex) { return template.toString(); } @Override public List<Extension> getAdditionalExtensions() { return singletonList(new ParameterResolver() { @Override public boolean supportsParameter( ParameterContext parameterContext, ExtensionContext extensionContext) { Class<?> type = parameterContext.getParameter() .getType(); return type.equals(WebDriver.class) || type.equals(RemoteWebDriver.class); } @Override public Object resolveParameter( ParameterContext parameterContext, ExtensionContext extensionContext) { String contextId = extensionContext.getUniqueId(); log.trace("Setting browser list {} for context id {}", template, contextId); parent.browserListMap.put(contextId, template); return parent.resolveParameter(parameterContext, extensionContext); } }); } }; } private void addEntry(Map<String, Class<?>> map, String key, Class<?> value) { try { map.put(key, value); } catch (Exception e) { log.warn("Exception adding {}={} to handler map ({})", key, value, e.getMessage()); } } private boolean isTestTemplate(ExtensionContext extensionContext) { Optional<Method> testMethod = extensionContext.getTestMethod(); return testMethod.isPresent() && testMethod.get().isAnnotationPresent(TestTemplate.class); } public void putBrowserList(String key, List<Browser> browserList) { this.browserListMap.put(key, browserList); } public void addBrowsers(Browser... browsers) { if (browserListList == null) { browserListList = new ArrayList<>(); } browserListList.add(asList(browsers)); } public Optional<String> getContainerId(WebDriver driver) { try { for (Map.Entry<String, Map<String, DockerContainer>> entry : containersMap .entrySet()) { DockerContainer selenoidContainer = containersMap .get(entry.getKey()).values().iterator().next(); URL selenoidUrl = new URL(selenoidContainer.getContainerUrl()); URL selenoidBaseUrl = new URL(selenoidUrl.getProtocol(), selenoidUrl.getHost(), selenoidUrl.getPort(), "/"); SelenoidService selenoidService = new SelenoidService( selenoidBaseUrl.toString()); Optional<String> containerId = selenoidService .getContainerId(driver); if (containerId.isPresent()) { return containerId; } } return empty(); } catch (Exception e) { throw new SeleniumJupiterException(e); } } public DockerService getDockerService() { return dockerService; } }
src/main/java/io/github/bonigarcia/SeleniumExtension.java
/* * (C) Copyright 2017 Boni Garcia (http://bonigarcia.github.io/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package io.github.bonigarcia; import static com.google.common.collect.ImmutableList.copyOf; import static io.github.bonigarcia.SeleniumJupiter.config; import static java.lang.invoke.MethodHandles.lookup; import static java.nio.charset.Charset.defaultCharset; import static java.nio.file.Files.readAllBytes; import static java.nio.file.Paths.get; import static java.util.Arrays.asList; import static java.util.Arrays.stream; import static java.util.Collections.singletonList; import static java.util.Optional.empty; import static java.util.stream.Collectors.toList; import static org.slf4j.LoggerFactory.getLogger; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.net.URL; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.stream.Stream; import org.apache.commons.io.IOUtils; import org.junit.jupiter.api.TestTemplate; import org.junit.jupiter.api.extension.AfterEachCallback; import org.junit.jupiter.api.extension.Extension; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.ParameterContext; import org.junit.jupiter.api.extension.ParameterResolver; import org.junit.jupiter.api.extension.TestTemplateInvocationContext; import org.junit.jupiter.api.extension.TestTemplateInvocationContextProvider; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.edge.EdgeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.opera.OperaDriver; import org.openqa.selenium.phantomjs.PhantomJSDriver; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.safari.SafariDriver; import org.slf4j.Logger; import com.google.gson.Gson; import com.spotify.docker.client.exceptions.DockerCertificateException; import io.appium.java_client.AppiumDriver; import io.github.bonigarcia.BrowsersTemplate.Browser; import io.github.bonigarcia.handler.AppiumDriverHandler; import io.github.bonigarcia.handler.ChromeDriverHandler; import io.github.bonigarcia.handler.DriverHandler; import io.github.bonigarcia.handler.EdgeDriverHandler; import io.github.bonigarcia.handler.FirefoxDriverHandler; import io.github.bonigarcia.handler.ListDriverHandler; import io.github.bonigarcia.handler.OperaDriverHandler; import io.github.bonigarcia.handler.OtherDriverHandler; import io.github.bonigarcia.handler.RemoteDriverHandler; import io.github.bonigarcia.handler.SafariDriverHandler; import io.github.bonigarcia.wdm.WebDriverManager; /** * Selenium extension for Jupiter (JUnit 5) tests. * * @author Boni Garcia ([email protected]) * @since 1.0.0 */ public class SeleniumExtension implements ParameterResolver, AfterEachCallback, TestTemplateInvocationContextProvider { final Logger log = getLogger(lookup().lookupClass()); static final String CLASSPATH_PREFIX = "classpath:"; private List<Class<?>> typeList = new CopyOnWriteArrayList<>(); private Map<String, List<DriverHandler>> driverHandlerMap = new ConcurrentHashMap<>(); private Map<String, Class<?>> handlerMap = new ConcurrentHashMap<>(); private Map<String, Class<?>> templateHandlerMap = new ConcurrentHashMap<>(); private Map<String, Map<String, DockerContainer>> containersMap = new ConcurrentHashMap<>(); private DockerService dockerService; private Map<String, List<Browser>> browserListMap = new ConcurrentHashMap<>(); private List<List<Browser>> browserListList; public SeleniumExtension() { addEntry(handlerMap, "org.openqa.selenium.chrome.ChromeDriver", ChromeDriverHandler.class); addEntry(handlerMap, "org.openqa.selenium.firefox.FirefoxDriver", FirefoxDriverHandler.class); addEntry(handlerMap, "org.openqa.selenium.edge.EdgeDriver", EdgeDriverHandler.class); addEntry(handlerMap, "org.openqa.selenium.opera.OperaDriver", OperaDriverHandler.class); addEntry(handlerMap, "org.openqa.selenium.safari.SafariDriver", SafariDriverHandler.class); addEntry(handlerMap, "org.openqa.selenium.remote.RemoteWebDriver", RemoteDriverHandler.class); addEntry(handlerMap, "org.openqa.selenium.WebDriver", RemoteDriverHandler.class); addEntry(handlerMap, "io.appium.java_client.AppiumDriver", AppiumDriverHandler.class); addEntry(handlerMap, "java.util.List", ListDriverHandler.class); addEntry(handlerMap, "org.openqa.selenium.phantomjs.PhantomJSDriver", OtherDriverHandler.class); addEntry(templateHandlerMap, "chrome", ChromeDriver.class); addEntry(templateHandlerMap, "firefox", FirefoxDriver.class); addEntry(templateHandlerMap, "edge", EdgeDriver.class); addEntry(templateHandlerMap, "opera", OperaDriver.class); addEntry(templateHandlerMap, "safari", SafariDriver.class); addEntry(templateHandlerMap, "appium", AppiumDriver.class); addEntry(templateHandlerMap, "phantomjs", PhantomJSDriver.class); addEntry(templateHandlerMap, "iexplorer", InternetExplorerDriver.class); addEntry(templateHandlerMap, "chrome-in-docker", RemoteWebDriver.class); addEntry(templateHandlerMap, "firefox-in-docker", RemoteWebDriver.class); addEntry(templateHandlerMap, "opera-in-docker", RemoteWebDriver.class); addEntry(templateHandlerMap, "android", RemoteWebDriver.class); } @Override public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) { Class<?> type = parameterContext.getParameter().getType(); return (WebDriver.class.isAssignableFrom(type) || type.equals(List.class)) && !isTestTemplate(extensionContext); } @Override public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) { String contextId = extensionContext.getUniqueId(); Parameter parameter = parameterContext.getParameter(); Class<?> type = parameter.getType(); boolean isTemplate = isTestTemplate(extensionContext); boolean isGeneric = type.equals(RemoteWebDriver.class) || type.equals(WebDriver.class); String url = null; Browser browser = null; // Check template if (isGeneric && !browserListMap.isEmpty()) { browser = getBrowser(contextId, parameter, isTemplate); } if (browser != null) { type = templateHandlerMap.get(browser.getType()); url = browser.getUrl(); } // WebDriverManager if (!typeList.contains(type)) { WebDriverManager.getInstance(type).setup(); typeList.add(type); } // Handler DriverHandler driverHandler = null; Class<?> constructorClass = handlerMap.containsKey(type.getName()) ? handlerMap.get(type.getName()) : OtherDriverHandler.class; boolean isRemote = constructorClass.equals(RemoteDriverHandler.class); if (url != null && !url.isEmpty()) { constructorClass = RemoteDriverHandler.class; isRemote = true; } try { driverHandler = getDriverHandler(extensionContext, parameter, type, constructorClass, browser, isRemote); if (type.equals(RemoteWebDriver.class) || type.equals(WebDriver.class) || type.equals(List.class)) { initHandlerForDocker(contextId, driverHandler); } if (!isTemplate && isGeneric && isRemote) { ((RemoteDriverHandler) driverHandler).setParent(this); ((RemoteDriverHandler) driverHandler) .setParameterContext(parameterContext); } putDriverHandlerInMap(extensionContext.getUniqueId(), driverHandler); } catch (Exception e) { handleException(parameter, driverHandler, constructorClass, e); } return resolveHandler(parameter, driverHandler); } private void putDriverHandlerInMap(String contextId, DriverHandler driverHandler) { if (driverHandlerMap.containsKey(contextId)) { driverHandlerMap.get(contextId).add(driverHandler); } else { List<DriverHandler> driverHandlers = new ArrayList<>(); driverHandlers.add(driverHandler); driverHandlerMap.put(contextId, driverHandlers); } log.trace("Adding {} to handler map (id {})", driverHandler, contextId); } private Browser getBrowser(String contextId, Parameter parameter, boolean isTemplate) { Integer index = isTemplate ? Integer.valueOf(parameter.getName().replaceAll("arg", "")) : 0; Browser browser = null; List<Browser> browserList = getValueFromContextId(browserListMap, contextId); if (browserList == null) { log.warn("Browser list for context id {} not found", contextId); } else { browser = browserList.get(index); } return browser; } private Object resolveHandler(Parameter parameter, DriverHandler driverHandler) { if (driverHandler != null) { driverHandler.resolve(); return driverHandler.getObject(); } else if (config().isExceptionWhenNoDriver()) { throw new SeleniumJupiterException( "No valid handler for " + parameter + " was found"); } else { return null; } } private DriverHandler getDriverHandler(ExtensionContext extensionContext, Parameter parameter, Class<?> type, Class<?> constructorClass, Browser browser, boolean isRemote) throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { DriverHandler driverHandler = null; if (isRemote && browser != null) { driverHandler = (DriverHandler) constructorClass .getDeclaredConstructor(Parameter.class, ExtensionContext.class, Browser.class) .newInstance(parameter, extensionContext, browser); } else if (constructorClass.equals(OtherDriverHandler.class) && !browserListMap.isEmpty()) { driverHandler = (DriverHandler) constructorClass .getDeclaredConstructor(Parameter.class, ExtensionContext.class, Class.class) .newInstance(parameter, extensionContext, type); } else { driverHandler = (DriverHandler) constructorClass .getDeclaredConstructor(Parameter.class, ExtensionContext.class) .newInstance(parameter, extensionContext); } return driverHandler; } public void initHandlerForDocker(String contextId, DriverHandler driverHandler) throws DockerCertificateException { LinkedHashMap<String, DockerContainer> containerMap = new LinkedHashMap<>(); driverHandler.setContainerMap(containerMap); containersMap.put(contextId, containerMap); if (dockerService == null) { dockerService = new DockerService(); } driverHandler.setDockerService(dockerService); } private void handleException(Parameter parameter, DriverHandler driverHandler, Class<?> constructorClass, Exception e) { if (driverHandler != null && driverHandler.throwExceptionWhenNoDriver()) { log.error("Exception resolving {}", parameter, e); throw new SeleniumJupiterException(e); } else { log.warn("Exception creating {}", constructorClass, e); } } @SuppressWarnings("unchecked") @Override public void afterEach(ExtensionContext extensionContext) { // Make screenshots if required and close browsers ScreenshotManager screenshotManager = new ScreenshotManager( extensionContext); String contextId = extensionContext.getUniqueId(); List<DriverHandler> driverHandlers = getValueFromContextId( driverHandlerMap, contextId); if (driverHandlers == null) { log.warn("Driver handler for context id {} not found", contextId); return; } for (DriverHandler driverHandler : copyOf(driverHandlers).reverse()) { try { Object object = driverHandler.getObject(); if (object != null) { if (List.class.isAssignableFrom(object.getClass())) { List<RemoteWebDriver> webDriverList = (List<RemoteWebDriver>) object; for (int i = 0; i < webDriverList.size(); i++) { screenshotManager.makeScreenshot( webDriverList.get(i), driverHandler.getName() + "_" + i); webDriverList.get(i).quit(); } } else { WebDriver webDriver = (WebDriver) object; if (driverHandler.getName() != null) { screenshotManager.makeScreenshot(webDriver, driverHandler.getName()); } webDriver.quit(); } } } catch (Exception e) { log.warn("Exception closing webdriver instance", e); } // Clean handler try { driverHandler.cleanup(); } catch (Exception e) { log.warn("Exception cleaning handler {}", driverHandler, e); } } // Clear handler map driverHandlerMap.remove(contextId); } private <T extends Object> T getValueFromContextId(Map<String, T> map, String contextId) { T output = map.get(contextId); if (output == null) { int i = contextId.lastIndexOf('/'); if (i != -1) { contextId = contextId.substring(0, i); output = map.get(contextId); } } return output; } @Override public boolean supportsTestTemplate(ExtensionContext context) { boolean allWebDriver = false; if (context.getTestMethod().isPresent()) { allWebDriver = !stream( context.getTestMethod().get().getParameterTypes()) .map(s -> s.equals(WebDriver.class) || s.equals(RemoteWebDriver.class)) .collect(toList()).contains(false); } return allWebDriver; } @Override public Stream<TestTemplateInvocationContext> provideTestTemplateInvocationContexts( ExtensionContext extensionContext) { String contextId = extensionContext.getUniqueId(); try { // 1. By JSON content String browserJsonContent = config() .getBrowserTemplateJsonContent(); if (browserJsonContent.isEmpty()) { // 2. By JSON file String browserJsonFile = config().getBrowserTemplateJsonFile(); if (browserJsonFile.startsWith(CLASSPATH_PREFIX)) { String browserJsonInClasspath = browserJsonFile .substring(CLASSPATH_PREFIX.length()); InputStream resourceAsStream = this.getClass() .getResourceAsStream("/" + browserJsonInClasspath); if (resourceAsStream != null) { browserJsonContent = IOUtils.toString(resourceAsStream, defaultCharset()); } } else { browserJsonContent = new String( readAllBytes(get(browserJsonFile))); } } if (!browserJsonContent.isEmpty()) { return new Gson() .fromJson(browserJsonContent, BrowsersTemplate.class) .getStream().map(b -> invocationContext(b, this)); } // 3. By setter if (browserListList != null) { return browserListList.stream() .map(b -> invocationContext(b, this)); } if (browserListMap != null) { return Stream.of( invocationContext(browserListMap.get(contextId), this)); } } catch (IOException e) { throw new SeleniumJupiterException(e); } throw new SeleniumJupiterException( "No browser scenario registered for test template"); } private synchronized TestTemplateInvocationContext invocationContext( List<Browser> template, SeleniumExtension parent) { return new TestTemplateInvocationContext() { @Override public String getDisplayName(int invocationIndex) { return template.toString(); } @Override public List<Extension> getAdditionalExtensions() { return singletonList(new ParameterResolver() { @Override public boolean supportsParameter( ParameterContext parameterContext, ExtensionContext extensionContext) { Class<?> type = parameterContext.getParameter() .getType(); return type.equals(WebDriver.class) || type.equals(RemoteWebDriver.class); } @Override public Object resolveParameter( ParameterContext parameterContext, ExtensionContext extensionContext) { String contextId = extensionContext.getUniqueId(); log.trace("Setting browser list {} for context id {}", template, contextId); parent.browserListMap.put(contextId, template); return parent.resolveParameter(parameterContext, extensionContext); } }); } }; } private void addEntry(Map<String, Class<?>> map, String key, Class<?> value) { try { map.put(key, value); } catch (Exception e) { log.warn("Exception adding {}={} to handler map ({})", key, value, e.getMessage()); } } private boolean isTestTemplate(ExtensionContext extensionContext) { Optional<Method> testMethod = extensionContext.getTestMethod(); return testMethod.isPresent() && testMethod.get().isAnnotationPresent(TestTemplate.class); } public void putBrowserList(String key, List<Browser> browserList) { this.browserListMap.put(key, browserList); } public void addBrowsers(Browser... browsers) { if (browserListList == null) { browserListList = new ArrayList<>(); } browserListList.add(asList(browsers)); } public Optional<String> getContainerId(WebDriver driver) { try { for (Map.Entry<String, Map<String, DockerContainer>> entry : containersMap .entrySet()) { DockerContainer selenoidContainer = containersMap .get(entry.getKey()).values().iterator().next(); URL selenoidUrl = new URL(selenoidContainer.getContainerUrl()); URL selenoidBaseUrl = new URL(selenoidUrl.getProtocol(), selenoidUrl.getHost(), selenoidUrl.getPort(), "/"); SelenoidService selenoidService = new SelenoidService( selenoidBaseUrl.toString()); Optional<String> containerId = selenoidService .getContainerId(driver); if (containerId.isPresent()) { return containerId; } } return empty(); } catch (Exception e) { throw new SeleniumJupiterException(e); } } public DockerService getDockerService() { return dockerService; } }
Refactor logic to quit WebDriver object in a separate method
src/main/java/io/github/bonigarcia/SeleniumExtension.java
Refactor logic to quit WebDriver object in a separate method
Java
apache-2.0
21499591c4c3c5c35e9bae0959cdc07775d968ea
0
marymiller/floodlight,CS-6617-Java/Floodlight,rizard/fast-failover-demo,TKTL-SDN/SoftOffload-Master,moisesber/floodlight,yeasy/floodlight-lc,teja-/floodlight,onebsv1/floodlightworkbench,rizard/geni-cinema,aprakash6/floodlight_video_cacher,TidyHuang/floodlight,Pengfei-Lu/floodlight,smartnetworks/floodlight,ZhangMenghao/Floodlight,thisthat/floodlight-controller,cbarrin/EAGERFloodlight,andi-bigswitch/floodlight-oss,woniu17/floodlight,SujithPandel/floodlight,kvm2116/floodlight,chinmaymhatre91/floodlight,yeasy/floodlight-lc,SujithPandel/floodlight,xuraylei/floodlight,rizard/SOSForFloodlight,andi-bigswitch/floodlight-oss,hgupta2/floodlight2,SujithPandel/floodlight,andiwundsam/floodlight-sync-proto,Linerd/sdn_optimization,pablotiburcio/AutoManIoT,aprakash6/floodlight_video_cacher,onebsv1/floodlightworkbench,fazevedo86/floodlight,CS-6617-Java/Floodlight,chinmaymhatre91/floodlight,duanjp8617/floodlight,fazevedo86/floodlight,swiatecki/DTUSDN,andiwundsam/floodlight-sync-proto,Pengfei-Lu/floodlight,Pengfei-Lu/floodlight,woniu17/floodlight,moisesber/floodlight,xph906/SDN-NW,hgupta2/floodlight2,rhoybeen/floodlightLB,Pengfei-Lu/floodlight,marcbaetica/Floodlight-OVS-OF-Network-Solution-,thisthat/floodlight-controller,rizard/fast-failover-demo,smartnetworks/floodlight,thisthat/floodlight-controller,AndreMantas/floodlight,andi-bigswitch/floodlight-oss,moisesber/floodlight,rizard/SOSForFloodlight,rizard/fast-failover-demo,rizard/floodlight,hgupta2/floodlight2,srcvirus/floodlight,marcbaetica/Floodlight-OVS-OF-Network-Solution-,jmiserez/floodlight,woniu17/floodlight,CS-6617-Java/Floodlight,baykovr/floodlight,jmiserez/floodlight,iluckydonkey/floodlight,alberthitanaya/floodlight-dnscollector,wallnerryan/FL_HAND,m1k3lin0/SDNProject,pixuan/floodlight,CS-6617-Java/Floodlight,marymiller/floodlight,rcchan/cs168-sdn-floodlight,xph906/SDN-NW,phisolani/floodlight,UdS-TelecommunicationsLab/floodlight,rsharo/floodlight,chinmaymhatre91/floodlight,ZhangMenghao/Floodlight,rsharo/floodlight,marcbaetica/Floodlight-OVS-OF-Network-Solution-,avbleverik/floodlight,wallnerryan/FL_HAND,fazevedo86/floodlight,jmiserez/floodlight,pablotiburcio/AutoManIoT,xph906/SDN-NW,JinWenQiang/FloodlightController,deepurple/floodlight,xph906/SDN,srcvirus/floodlight,cbarrin/EAGERFloodlight,rcchan/cs168-sdn-floodlight,kvm2116/floodlight,hgupta2/floodlight2,netgroup/floodlight,aprakash6/floodlight_video_cacher,swiatecki/DTUSDN,xph906/SDN-ec2,xph906/SDN,yeasy/floodlight-lc,netgroup/floodlight,geddings/floodlight,09zwcbupt/floodlight,rizard/fast-failover-demo,duanjp8617/floodlight,woniu17/floodlight,xph906/SDN-ec2,srcvirus/floodlight,rhoybeen/floodlightLB,daniel666/multicastSDN,alberthitanaya/floodlight-dnscollector,teja-/floodlight,niuqg/floodlight-test,pixuan/floodlight,cbarrin/EAGERFloodlight,iluckydonkey/floodlight,daniel666/multicastSDN,alexreimers/floodlight,09zwcbupt/floodlight,UdS-TelecommunicationsLab/floodlight,drinkwithwater/floodlightplus,avbleverik/floodlight,xuraylei/floodlight,deepurple/floodlight,netgroup/floodlight,m1k3lin0/SDNProject,chechoRP/floodlight,omkale/myfloodlight,JinWenQiang/FloodlightController,alberthitanaya/floodlight-dnscollector,TidyHuang/floodlight,onebsv1/floodlight,omkale/myfloodlight,rcchan/cs168-sdn-floodlight,teja-/floodlight,teja-/floodlight,aprakash6/floodlight_video_cacher,andiwundsam/floodlight-sync-proto,alsmadi/CSCI-6617,AndreMantas/floodlight,AndreMantas/floodlight,rizard/geni-cinema,alberthitanaya/floodlight-dnscollector,marcbaetica/Floodlight-OVS-OF-Network-Solution-,omkale/myfloodlight,ZhangMenghao/Floodlight,drinkwithwater/floodlightplus,duanjp8617/floodlight,Linerd/sdn_optimization,thisthat/floodlight-controller,pixuan/floodlight,rsharo/floodlight,chechoRP/floodlight,yeasy/floodlight-lc,phisolani/floodlight,phisolani/floodlight,niuqg/floodlight-test,dhruvkakadiya/FloodlightLoadBalancer,Pengfei-Lu/floodlight,xph906/SDN-ec2,daniel666/multicastSDN,xuraylei/floodlight,rhoybeen/floodlightLB,rizard/geni-cinema,ZhangMenghao/Floodlight,aprakash6/floodlight_video_cacher,avbleverik/floodlight,smartnetworks/floodlight,phisolani/floodlight,kvm2116/floodlight,deepurple/floodlight,drinkwithwater/floodlightplus,rizard/SOSForFloodlight,swiatecki/DTUSDN,09zwcbupt/floodlight,xph906/SDN-ec2,JinWenQiang/FloodlightController,rizard/floodlight,floodlight/floodlight,xph906/SDN-ec2,onebsv1/floodlight,deepurple/floodlight,TKTL-SDN/SoftOffload-Master,duanjp8617/floodlight,chinmaymhatre91/floodlight,rhoybeen/floodlightLB,09zwcbupt/floodlight,alexreimers/floodlight,xph906/SDN,swiatecki/DTUSDN,niuqg/floodlight-test,CS-6617-Java/Floodlight,jmiserez/floodlight,TidyHuang/floodlight,m1k3lin0/SDNProject,alberthitanaya/floodlight-dnscollector,andi-bigswitch/floodlight-oss,pixuan/floodlight,alsmadi/CSCI-6617,CS-6617-Java/Floodlight,UdS-TelecommunicationsLab/floodlight,xph906/SDN,alsmadi/CSCI-6617,floodlight/floodlight,TidyHuang/floodlight,woniu17/floodlight,chechoRP/floodlight,chinmaymhatre91/floodlight,dhruvkakadiya/FloodlightLoadBalancer,moisesber/floodlight,marymiller/floodlight,TKTL-SDN/SoftOffload-Master,xph906/SDN-NW,phisolani/floodlight,alexreimers/floodlight,alsmadi/CSCI-6617,floodlight/floodlight,swiatecki/DTUSDN,onebsv1/floodlightworkbench,rizard/geni-cinema,wallnerryan/FL_HAND,JinWenQiang/FloodlightController,rizard/geni-cinema,rizard/fast-failover-demo,smartnetworks/floodlight,TKTL-SDN/SoftOffload-Master,TidyHuang/floodlight,duanjp8617/floodlight,xph906/SDN,pablotiburcio/AutoManIoT,xph906/SDN-NW,rcchan/cs168-sdn-floodlight,baykovr/floodlight,geddings/floodlight,m1k3lin0/SDNProject,niuqg/floodlight-test,netgroup/floodlight,alexreimers/floodlight,thisthat/floodlight-controller,deepurple/floodlight,srcvirus/floodlight,smartnetworks/floodlight,pixuan/floodlight,JinWenQiang/FloodlightController,geddings/floodlight,moisesber/floodlight,m1k3lin0/SDNProject,dhruvkakadiya/FloodlightLoadBalancer,wallnerryan/FL_HAND,baykovr/floodlight,jmiserez/floodlight,netgroup/floodlight,daniel666/multicastSDN,TKTL-SDN/SoftOffload-Master,baykovr/floodlight,alsmadi/CSCI-6617,ZhangMenghao/Floodlight,fazevedo86/floodlight,UdS-TelecommunicationsLab/floodlight,fazevedo86/floodlight,Linerd/sdn_optimization,CS-6617-Java/Floodlight,rcchan/cs168-sdn-floodlight,UdS-TelecommunicationsLab/floodlight,baykovr/floodlight,chechoRP/floodlight,avbleverik/floodlight,andiwundsam/floodlight-sync-proto,chechoRP/floodlight,avbleverik/floodlight,iluckydonkey/floodlight,alexreimers/floodlight,rhoybeen/floodlightLB,dhruvkakadiya/FloodlightLoadBalancer,SujithPandel/floodlight,onebsv1/floodlight,drinkwithwater/floodlightplus,dhruvkakadiya/FloodlightLoadBalancer,iluckydonkey/floodlight,Linerd/sdn_optimization,iluckydonkey/floodlight,rizard/floodlight,marymiller/floodlight
package net.floodlightcontroller.firewall; import java.io.IOException; import java.util.Iterator; import java.util.List; import org.codehaus.jackson.JsonParseException; import org.codehaus.jackson.JsonParser; import org.codehaus.jackson.JsonToken; import org.codehaus.jackson.map.MappingJsonFactory; import org.openflow.util.HexString; import org.restlet.resource.Delete; import org.restlet.resource.Post; import org.restlet.resource.Get; import org.restlet.resource.ServerResource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.floodlightcontroller.packet.Ethernet; import net.floodlightcontroller.packet.IPv4; public class FirewallRulesResource extends ServerResource { protected static Logger log = LoggerFactory.getLogger(FirewallRulesResource.class); @Get("json") public Object handleRequest() { IFirewallService firewall = (IFirewallService)getContext().getAttributes(). get(IFirewallService.class.getCanonicalName()); return firewall.getRules(); } /** * Takes a Firewall Rule string in JSON format and parses it into * our firewall rule data structure, then adds it to the firewall. * @param fmJson The Firewall rule entry in JSON format. * @return A string status message */ @Post public String store(String fmJson) { IFirewallService firewall = (IFirewallService)getContext().getAttributes(). get(IFirewallService.class.getCanonicalName()); FirewallRule rule; try { rule = jsonToFirewallRule(fmJson); } catch (IOException e) { log.error("Error parsing firewall rule: " + fmJson, e); e.printStackTrace(); return "{\"status\" : \"Error! Could not parse firewall rule, see log for details.\"}"; } String status = null; if (checkRuleExists(rule, firewall.getRules())) { status = "Error! A similar firewall rule already exists."; log.error(status); } else { // add rule to firewall firewall.addRule(rule); status = "Rule added"; } return ("{\"status\" : \"" + status + "\"}"); } /** * Takes a Firewall Rule string in JSON format and parses it into * our firewall rule data structure, then deletes it from the firewall. * @param fmJson The Firewall rule entry in JSON format. * @return A string status message */ @Delete public String remove(String fmJson) { IFirewallService firewall = (IFirewallService)getContext().getAttributes(). get(IFirewallService.class.getCanonicalName()); FirewallRule rule; try { rule = jsonToFirewallRule(fmJson); } catch (IOException e) { log.error("Error parsing firewall rule: " + fmJson, e); e.printStackTrace(); return "{\"status\" : \"Error! Could not parse firewall rule, see log for details.\"}"; } String status = null; boolean exists = false; Iterator<FirewallRule> iter = firewall.getRules().iterator(); while (iter.hasNext()) { FirewallRule r = iter.next(); if (r.ruleid == rule.ruleid) { exists = true; break; } } if (!exists) { status = "Error! Can't delete, a rule with this ID doesn't exist."; log.error(status); } else { // delete rule from firewall firewall.deleteRule(rule.ruleid); status = "Rule deleted"; } return ("{\"status\" : \"" + status + "\"}"); } /** * Turns a JSON formatted Firewall Rule string into a FirewallRule instance * @param fmJson The JSON formatted static firewall rule * @return The FirewallRule instance * @throws IOException If there was an error parsing the JSON */ public static FirewallRule jsonToFirewallRule(String fmJson) throws IOException { FirewallRule rule = new FirewallRule(); MappingJsonFactory f = new MappingJsonFactory(); JsonParser jp; try { jp = f.createJsonParser(fmJson); } catch (JsonParseException e) { throw new IOException(e); } jp.nextToken(); if (jp.getCurrentToken() != JsonToken.START_OBJECT) { throw new IOException("Expected START_OBJECT"); } while (jp.nextToken() != JsonToken.END_OBJECT) { if (jp.getCurrentToken() != JsonToken.FIELD_NAME) { throw new IOException("Expected FIELD_NAME"); } String n = jp.getCurrentName(); jp.nextToken(); if (jp.getText().equals("")) continue; String tmp; // This is currently only applicable for remove(). In store(), ruleid takes a random number if (n == "ruleid") { rule.ruleid = Integer.parseInt((String)jp.getText()); } // This assumes user having dpid info for involved switches else if (n == "switchid") { tmp = jp.getText(); if (tmp.equalsIgnoreCase("-1") == false) { // user inputs hex format dpid rule.dpid = HexString.toLong(tmp); rule.wildcard_dpid = false; } } else if (n == "src-inport") { rule.in_port = Short.parseShort(jp.getText()); rule.wildcard_in_port = false; } else if (n == "src-mac") { tmp = jp.getText(); if (tmp.equalsIgnoreCase("ANY") == false) { rule.wildcard_dl_src = false; rule.dl_src = Ethernet.toLong(Ethernet.toMACAddress(tmp)); } } else if (n == "dst-mac") { tmp = jp.getText(); if (tmp.equalsIgnoreCase("ANY") == false) { rule.wildcard_dl_dst = false; rule.dl_dst = Ethernet.toLong(Ethernet.toMACAddress(tmp)); } } else if (n == "dl-type") { tmp = jp.getText(); if (tmp.equalsIgnoreCase("ARP")) { rule.wildcard_dl_type = false; rule.dl_type = Ethernet.TYPE_ARP; } if (tmp.equalsIgnoreCase("IPv4")) { rule.wildcard_dl_type = false; rule.dl_type = Ethernet.TYPE_IPv4; } } else if (n == "src-ip") { tmp = jp.getText(); if (tmp.equalsIgnoreCase("ANY") == false) { rule.wildcard_nw_src = false; rule.wildcard_dl_type = false; rule.dl_type = Ethernet.TYPE_IPv4; int[] cidr = IPCIDRToPrefixBits(tmp); rule.nw_src_prefix = cidr[0]; rule.nw_src_maskbits = cidr[1]; } } else if (n == "dst-ip") { tmp = jp.getText(); if (tmp.equalsIgnoreCase("ANY") == false) { rule.wildcard_nw_dst = false; rule.wildcard_dl_type = false; rule.dl_type = Ethernet.TYPE_IPv4; int[] cidr = IPCIDRToPrefixBits(tmp); rule.nw_dst_prefix = cidr[0]; rule.nw_dst_maskbits = cidr[1]; } } else if (n == "nw-proto") { tmp = jp.getText(); if (tmp.equalsIgnoreCase("TCP")) { rule.wildcard_nw_proto = false; rule.nw_proto = IPv4.PROTOCOL_TCP; rule.wildcard_dl_type = false; rule.dl_type = Ethernet.TYPE_IPv4; } else if (tmp.equalsIgnoreCase("UDP")) { rule.wildcard_nw_proto = false; rule.nw_proto = IPv4.PROTOCOL_UDP; rule.wildcard_dl_type = false; rule.dl_type = Ethernet.TYPE_IPv4; } else if (tmp.equalsIgnoreCase("ICMP")) { rule.wildcard_nw_proto = false; rule.nw_proto = IPv4.PROTOCOL_ICMP; rule.wildcard_dl_type = false; rule.dl_type = Ethernet.TYPE_IPv4; } } else if (n == "tp-src") { rule.wildcard_tp_src = false; rule.tp_src = Short.parseShort(jp.getText()); } else if (n == "tp-dst") { rule.wildcard_tp_dst = false; rule.tp_dst = Short.parseShort(jp.getText()); } else if (n == "priority") { rule.priority = Integer.parseInt(jp.getText()); } else if (n == "action") { if (jp.getText().equalsIgnoreCase("allow") == true) { rule.action = FirewallRule.FirewallAction.ALLOW; } else if (jp.getText().equalsIgnoreCase("deny") == true) { rule.action = FirewallRule.FirewallAction.DENY; } } } return rule; } public static int[] IPCIDRToPrefixBits(String cidr) { int ret[] = new int[2]; // as IP can also be a prefix rather than an absolute address // split it over "/" to get the bit range String[] parts = cidr.split("/"); String cidr_prefix = parts[0].trim(); int cidr_bits = 0; if (parts.length == 2) { try { cidr_bits = Integer.parseInt(parts[1].trim()); } catch (Exception exp) { cidr_bits = 32; } } ret[0] = IPv4.toIPv4Address(cidr_prefix); ret[1] = cidr_bits; return ret; } public static boolean checkRuleExists(FirewallRule rule, List<FirewallRule> rules) { Iterator<FirewallRule> iter = rules.iterator(); while (iter.hasNext()) { FirewallRule r = iter.next(); // check if we find a similar rule if (rule.isSameAs(r)) { return true; } } // no rule matched, so it doesn't exist in the rules return false; } }
src/main/java/net/floodlightcontroller/firewall/FirewallRulesResource.java
package net.floodlightcontroller.firewall; import java.io.IOException; import java.util.Iterator; import java.util.List; import org.codehaus.jackson.JsonParseException; import org.codehaus.jackson.JsonParser; import org.codehaus.jackson.JsonToken; import org.codehaus.jackson.map.MappingJsonFactory; import org.openflow.util.HexString; import org.restlet.resource.Delete; import org.restlet.resource.Post; import org.restlet.resource.Get; import org.restlet.resource.ServerResource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.floodlightcontroller.packet.Ethernet; import net.floodlightcontroller.packet.IPv4; public class FirewallRulesResource extends ServerResource { protected static Logger log = LoggerFactory.getLogger(FirewallRulesResource.class); @Get("json") public Object handleRequest() { IFirewallService firewall = (IFirewallService)getContext().getAttributes(). get(IFirewallService.class.getCanonicalName()); return firewall.getRules(); } /** * Takes a Firewall Rule string in JSON format and parses it into * our firewall rule data structure, then adds it to the firewall. * @param fmJson The Firewall rule entry in JSON format. * @return A string status message */ @Post public String store(String fmJson) { IFirewallService firewall = (IFirewallService)getContext().getAttributes(). get(IFirewallService.class.getCanonicalName()); FirewallRule rule; try { rule = jsonToFirewallRule(fmJson); } catch (IOException e) { log.error("Error parsing firewall rule: " + fmJson, e); e.printStackTrace(); return "{\"status\" : \"Error! Could not parse firewall rule, see log for details.\"}"; } String status = null; if (checkRuleExists(rule, firewall.getRules())) { status = "Error! A similar firewall rule already exists."; log.error(status); } else { // add rule to firewall firewall.addRule(rule); status = "Rule added"; } return ("{\"status\" : \"" + status + "\"}"); } /** * Takes a Firewall Rule string in JSON format and parses it into * our firewall rule data structure, then deletes it from the firewall. * @param fmJson The Firewall rule entry in JSON format. * @return A string status message */ @Delete public String remove(String fmJson) { IFirewallService firewall = (IFirewallService)getContext().getAttributes(). get(IFirewallService.class.getCanonicalName()); FirewallRule rule; try { rule = jsonToFirewallRule(fmJson); } catch (IOException e) { log.error("Error parsing firewall rule: " + fmJson, e); e.printStackTrace(); return "{\"status\" : \"Error! Could not parse firewall rule, see log for details.\"}"; } String status = null; boolean exists = false; Iterator<FirewallRule> iter = firewall.getRules().iterator(); while (iter.hasNext()) { FirewallRule r = iter.next(); if (r.ruleid == rule.ruleid) { exists = true; break; } } if (!exists) { status = "Error! Can't delete, a rule with this ID doesn't exist."; log.error(status); } else { // delete rule from firewall firewall.deleteRule(rule.ruleid); status = "Rule deleted"; } return ("{\"status\" : \"" + status + "\"}"); } /** * Turns a JSON formatted Firewall Rule string into a FirewallRule instance * @param fmJson The JSON formatted static firewall rule * @return The FirewallRule instance * @throws IOException If there was an error parsing the JSON */ public static FirewallRule jsonToFirewallRule(String fmJson) throws IOException { FirewallRule rule = new FirewallRule(); MappingJsonFactory f = new MappingJsonFactory(); JsonParser jp; try { jp = f.createJsonParser(fmJson); } catch (JsonParseException e) { throw new IOException(e); } jp.nextToken(); if (jp.getCurrentToken() != JsonToken.START_OBJECT) { throw new IOException("Expected START_OBJECT"); } while (jp.nextToken() != JsonToken.END_OBJECT) { if (jp.getCurrentToken() != JsonToken.FIELD_NAME) { throw new IOException("Expected FIELD_NAME"); } String n = jp.getCurrentName(); jp.nextToken(); if (jp.getText().equals("")) continue; String tmp; // This is currently only applicable for remove(). In store(), ruleid takes a random number if (n == "ruleid") { rule.ruleid = Integer.parseInt((String)jp.getText()); } // This assumes user having dpid info for involved switches else if (n == "switchid") { tmp = jp.getText(); if (tmp.equalsIgnoreCase("-1") == false) { // user inputs hex format dpid rule.dpid = HexString.toLong(tmp); rule.wildcard_dpid = false; } } else if (n == "src-inport") { rule.in_port = Short.parseShort(jp.getText()); rule.wildcard_in_port = false; } else if (n == "src-mac") { tmp = jp.getText(); if (tmp.equalsIgnoreCase("ANY") == false) { rule.wildcard_dl_src = false; rule.dl_src = Ethernet.toLong(Ethernet.toMACAddress(tmp)); } } else if (n == "dst-mac") { tmp = jp.getText(); if (tmp.equalsIgnoreCase("ANY") == false) { rule.wildcard_dl_dst = false; rule.dl_dst = Ethernet.toLong(Ethernet.toMACAddress(tmp)); } } else if (n == "dl-type") { tmp = jp.getText(); if (tmp.equalsIgnoreCase("ARP")) { rule.wildcard_dl_type = false; rule.dl_type = Ethernet.TYPE_ARP; } } else if (n == "src-ip") { tmp = jp.getText(); if (tmp.equalsIgnoreCase("ANY") == false) { rule.wildcard_nw_src = false; rule.wildcard_dl_type = false; rule.dl_type = Ethernet.TYPE_IPv4; int[] cidr = IPCIDRToPrefixBits(tmp); rule.nw_src_prefix = cidr[0]; rule.nw_src_maskbits = cidr[1]; } } else if (n == "dst-ip") { tmp = jp.getText(); if (tmp.equalsIgnoreCase("ANY") == false) { rule.wildcard_nw_dst = false; rule.wildcard_dl_type = false; rule.dl_type = Ethernet.TYPE_IPv4; int[] cidr = IPCIDRToPrefixBits(tmp); rule.nw_dst_prefix = cidr[0]; rule.nw_dst_maskbits = cidr[1]; } } else if (n == "nw-proto") { tmp = jp.getText(); if (tmp.equalsIgnoreCase("TCP")) { rule.wildcard_nw_proto = false; rule.nw_proto = IPv4.PROTOCOL_TCP; rule.wildcard_dl_type = false; rule.dl_type = Ethernet.TYPE_IPv4; } else if (tmp.equalsIgnoreCase("UDP")) { rule.wildcard_nw_proto = false; rule.nw_proto = IPv4.PROTOCOL_UDP; rule.wildcard_dl_type = false; rule.dl_type = Ethernet.TYPE_IPv4; } else if (tmp.equalsIgnoreCase("ICMP")) { rule.wildcard_nw_proto = false; rule.nw_proto = IPv4.PROTOCOL_ICMP; rule.wildcard_dl_type = false; rule.dl_type = Ethernet.TYPE_IPv4; } } else if (n == "tp-src") { rule.wildcard_tp_src = false; rule.tp_src = Short.parseShort(jp.getText()); } else if (n == "tp-dst") { rule.wildcard_tp_dst = false; rule.tp_dst = Short.parseShort(jp.getText()); } else if (n == "priority") { rule.priority = Integer.parseInt(jp.getText()); } else if (n == "action") { if (jp.getText().equalsIgnoreCase("allow") == true) { rule.action = FirewallRule.FirewallAction.ALLOW; } else if (jp.getText().equalsIgnoreCase("deny") == true) { rule.action = FirewallRule.FirewallAction.DENY; } } } return rule; } public static int[] IPCIDRToPrefixBits(String cidr) { int ret[] = new int[2]; // as IP can also be a prefix rather than an absolute address // split it over "/" to get the bit range String[] parts = cidr.split("/"); String cidr_prefix = parts[0].trim(); int cidr_bits = 0; if (parts.length == 2) { try { cidr_bits = Integer.parseInt(parts[1].trim()); } catch (Exception exp) { cidr_bits = 32; } } ret[0] = IPv4.toIPv4Address(cidr_prefix); ret[1] = cidr_bits; return ret; } public static boolean checkRuleExists(FirewallRule rule, List<FirewallRule> rules) { Iterator<FirewallRule> iter = rules.iterator(); while (iter.hasNext()) { FirewallRule r = iter.next(); // check if we find a similar rule if (rule.isSameAs(r)) { return true; } } // no rule matched, so it doesn't exist in the rules return false; } }
minor addition of IPv4 dl_type input handling to FirewallRulesResource
src/main/java/net/floodlightcontroller/firewall/FirewallRulesResource.java
minor addition of IPv4 dl_type input handling to FirewallRulesResource
Java
apache-2.0
8804571a4df83ec15000aabbf1333f6c0552fc28
0
wschaeferB/autopsy,narfindustries/autopsy,eXcomm/autopsy,esaunders/autopsy,wschaeferB/autopsy,esaunders/autopsy,mhmdfy/autopsy,wschaeferB/autopsy,esaunders/autopsy,maxrp/autopsy,mhmdfy/autopsy,millmanorama/autopsy,APriestman/autopsy,karlmortensen/autopsy,maxrp/autopsy,narfindustries/autopsy,APriestman/autopsy,esaunders/autopsy,APriestman/autopsy,esaunders/autopsy,APriestman/autopsy,dgrove727/autopsy,APriestman/autopsy,eXcomm/autopsy,wschaeferB/autopsy,maxrp/autopsy,karlmortensen/autopsy,karlmortensen/autopsy,rcordovano/autopsy,millmanorama/autopsy,sidheshenator/autopsy,sidheshenator/autopsy,narfindustries/autopsy,rcordovano/autopsy,APriestman/autopsy,rcordovano/autopsy,millmanorama/autopsy,rcordovano/autopsy,maxrp/autopsy,dgrove727/autopsy,karlmortensen/autopsy,sidheshenator/autopsy,mhmdfy/autopsy,mhmdfy/autopsy,APriestman/autopsy,wschaeferB/autopsy,eXcomm/autopsy,eXcomm/autopsy,dgrove727/autopsy,rcordovano/autopsy,rcordovano/autopsy,sidheshenator/autopsy,millmanorama/autopsy
/* * Autopsy Forensic Browser * * Copyright 2014 Basis Technology Corp. * Contact: carrier <at> sleuthkit <dot> 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.sleuthkit.autopsy.ingest; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.logging.Level; import org.openide.DialogDisplayer; import org.openide.NotifyDescriptor; import org.openide.util.Lookup; import org.openide.util.NbBundle; import org.sleuthkit.autopsy.coreutils.Logger; import org.sleuthkit.autopsy.examples.SampleExecutableIngestModuleFactory; import org.sleuthkit.autopsy.examples.SampleIngestModuleFactory; import org.sleuthkit.autopsy.modules.android.AndroidModuleFactory; import org.sleuthkit.autopsy.modules.e01verify.E01VerifierModuleFactory; import org.sleuthkit.autopsy.modules.exif.ExifParserModuleFactory; import org.sleuthkit.autopsy.modules.fileextmismatch.FileExtMismatchDetectorModuleFactory; import org.sleuthkit.autopsy.modules.filetypeid.FileTypeIdModuleFactory; import org.sleuthkit.autopsy.modules.hashdatabase.HashLookupModuleFactory; import org.sleuthkit.autopsy.modules.sevenzip.ArchiveFileExtractorModuleFactory; import org.sleuthkit.autopsy.python.JythonModuleLoader; /** * Discovers ingest module factories implemented in Java or Jython. */ final class IngestModuleFactoryLoader { private static final Logger logger = Logger.getLogger(IngestModuleFactoryLoader.class.getName()); private static final ArrayList<String> coreModuleOrdering = new ArrayList<String>() { { // The ordering of Core module factories is hard-coded. add("org.sleuthkit.autopsy.recentactivity.RecentActivityExtracterModuleFactory"); //NON-NLS add(HashLookupModuleFactory.class.getCanonicalName()); add(FileTypeIdModuleFactory.class.getCanonicalName()); add(ArchiveFileExtractorModuleFactory.class.getCanonicalName()); add(ExifParserModuleFactory.class.getCanonicalName()); add("org.sleuthkit.autopsy.keywordsearch.KeywordSearchModuleFactory"); //NON-NLS add("org.sleuthkit.autopsy.thunderbirdparser.EmailParserModuleFactory"); //NON-NLS add(FileExtMismatchDetectorModuleFactory.class.getCanonicalName()); add(E01VerifierModuleFactory.class.getCanonicalName()); add(AndroidModuleFactory.class.getCanonicalName()); } }; /** * Get the currently available set of ingest module factories. The factories * are not cached between calls since NetBeans modules with classes labeled * as IngestModuleFactory service providers and/or Python scripts defining * classes derived from IngestModuleFactory may be added or removed between * invocations. * * @return A list of objects that implement the IngestModuleFactory * interface. */ static List<IngestModuleFactory> getIngestModuleFactories() { // Discover the ingest module factories implemented using Java, making a // hash map of display names to discovered factories and a hash set of // display names. HashSet<String> moduleDisplayNames = new HashSet<>(); HashMap<String, IngestModuleFactory> javaFactoriesByClass = new HashMap<>(); for (IngestModuleFactory factory : Lookup.getDefault().lookupAll(IngestModuleFactory.class)) { if (!moduleDisplayNames.contains(factory.getModuleDisplayName())) { moduleDisplayNames.add(factory.getModuleDisplayName()); javaFactoriesByClass.put(factory.getClass().getCanonicalName(), factory); logger.log(Level.INFO, "Found ingest module factory: name = {0}, version = {1}", new Object[]{factory.getModuleDisplayName(), factory.getModuleVersionNumber()}); //NON-NLS } else { logger.log(Level.SEVERE, "Found duplicate ingest module display name (name = {0})", factory.getModuleDisplayName()); //NON-NLS DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message( NbBundle.getMessage(IngestModuleFactoryLoader.class, "IngestModuleFactoryLoader.errorMessages.duplicateDisplayName", factory.getModuleDisplayName()), NotifyDescriptor.ERROR_MESSAGE)); } } // Kick out the sample ingest module factories implemented in Java. javaFactoriesByClass.remove(SampleIngestModuleFactory.class.getCanonicalName()); javaFactoriesByClass.remove(SampleExecutableIngestModuleFactory.class.getCanonicalName()); // Add the core ingest module factories in the desired order, removing // the core factories from the map so that the map will only contain // non-core modules after this loop. List<IngestModuleFactory> factories = new ArrayList<>(); for (String className : coreModuleOrdering) { IngestModuleFactory coreFactory = javaFactoriesByClass.remove(className); if (coreFactory != null) { factories.add(coreFactory); } else { logger.log(Level.SEVERE, "Core factory {0} not loaded", coreFactory); } } // Add any remaining non-core factories discovered. Order is not // guaranteed! factories.addAll(javaFactoriesByClass.values()); // Add any ingest module factories implemented using Jython. Order is // not guaranteed! for (IngestModuleFactory factory : JythonModuleLoader.getIngestModuleFactories()) { if (!moduleDisplayNames.contains(factory.getModuleDisplayName())) { moduleDisplayNames.add(factory.getModuleDisplayName()); factories.add(factory); logger.log(Level.INFO, "Found ingest module factory: name = {0}, version = {1}", new Object[]{factory.getModuleDisplayName(), factory.getModuleVersionNumber()}); //NON-NLS } else { logger.log(Level.SEVERE, "Found duplicate ingest module display name (name = {0})", factory.getModuleDisplayName()); //NON-NLS DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message( NbBundle.getMessage(IngestModuleFactoryLoader.class, "IngestModuleFactoryLoader.errorMessages.duplicateDisplayName", factory.getModuleDisplayName()), NotifyDescriptor.ERROR_MESSAGE)); } } return factories; } }
Core/src/org/sleuthkit/autopsy/ingest/IngestModuleFactoryLoader.java
/* * Autopsy Forensic Browser * * Copyright 2014 Basis Technology Corp. * Contact: carrier <at> sleuthkit <dot> 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.sleuthkit.autopsy.ingest; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.logging.Level; import org.openide.DialogDisplayer; import org.openide.NotifyDescriptor; import org.openide.util.Lookup; import org.openide.util.NbBundle; import org.sleuthkit.autopsy.coreutils.Logger; import org.sleuthkit.autopsy.examples.SampleExecutableIngestModuleFactory; import org.sleuthkit.autopsy.examples.SampleIngestModuleFactory; import org.sleuthkit.autopsy.modules.android.AndroidModuleFactory; import org.sleuthkit.autopsy.modules.e01verify.E01VerifierModuleFactory; import org.sleuthkit.autopsy.modules.exif.ExifParserModuleFactory; import org.sleuthkit.autopsy.modules.fileextmismatch.FileExtMismatchDetectorModuleFactory; import org.sleuthkit.autopsy.modules.filetypeid.FileTypeIdModuleFactory; import org.sleuthkit.autopsy.modules.hashdatabase.HashLookupModuleFactory; import org.sleuthkit.autopsy.modules.sevenzip.ArchiveFileExtractorModuleFactory; import org.sleuthkit.autopsy.python.JythonModuleLoader; /** * Discovers ingest module factories implemented in Java or Jython. */ final class IngestModuleFactoryLoader { private static final Logger logger = Logger.getLogger(IngestModuleFactoryLoader.class.getName()); private static final ArrayList<String> coreModuleOrdering = new ArrayList<String>() { { // The ordering of Core module factories is hard-coded. add("org.sleuthkit.autopsy.recentactivity.RecentActivityExtracterModuleFactory"); //NON-NLS add(HashLookupModuleFactory.class.getCanonicalName()); add(FileTypeIdModuleFactory.class.getCanonicalName()); add(ArchiveFileExtractorModuleFactory.class.getCanonicalName()); add(ExifParserModuleFactory.class.getCanonicalName()); add("org.sleuthkit.autopsy.keywordsearch.KeywordSearchModuleFactory"); //NON-NLS add("org.sleuthkit.autopsy.thunderbirdparser.EmailParserModuleFactory"); //NON-NLS add(FileExtMismatchDetectorModuleFactory.class.getCanonicalName()); add(E01VerifierModuleFactory.class.getCanonicalName()); add(AndroidModuleFactory.class.getCanonicalName()); } }; /** * Get the currently available set of ingest module factories. The factories * are not cached between calls since NetBeans modules with classes labeled * as IngestModuleFactory service providers and/or Python scripts defining * classes derived from IngestModuleFactory may be added or removed between * invocations. * * @return A list of objects that implement the IngestModuleFactory * interface. */ static List<IngestModuleFactory> getIngestModuleFactories() { // Discover the ingest module factories implemented using Java, making a // hash map of display names to discovered factories and a hash set of // display names. HashSet<String> moduleDisplayNames = new HashSet<>(); HashMap<String, IngestModuleFactory> moduleFactoriesByClass = new HashMap<>(); Collection<? extends IngestModuleFactory> factories = Lookup.getDefault().lookupAll(IngestModuleFactory.class); for (IngestModuleFactory factory : factories) { if (!moduleDisplayNames.contains(factory.getModuleDisplayName())) { moduleDisplayNames.add(factory.getModuleDisplayName()); moduleFactoriesByClass.put(factory.getClass().getCanonicalName(), factory); logger.log(Level.INFO, "Found ingest module factory: name = {0}, version = {1}", new Object[]{factory.getModuleDisplayName(), factory.getModuleVersionNumber()}); //NON-NLS } else { logger.log(Level.SEVERE, "Found duplicate ingest module display name (name = {0})", factory.getModuleDisplayName()); //NON-NLS DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message( NbBundle.getMessage(IngestModuleFactoryLoader.class, "IngestModuleFactoryLoader.errorMessages.duplicateDisplayName", factory.getModuleDisplayName()), NotifyDescriptor.ERROR_MESSAGE)); } } // Kick out the sample ingest module factories implemented in Java. moduleFactoriesByClass.remove(SampleIngestModuleFactory.class.getCanonicalName()); moduleFactoriesByClass.remove(SampleExecutableIngestModuleFactory.class.getCanonicalName()); // Make the ordered list of core ingest module factories (remove the // core factories from the map). List<IngestModuleFactory> orderedModuleFactories = new ArrayList<>(); for (String className : coreModuleOrdering) { IngestModuleFactory coreFactory = moduleFactoriesByClass.remove(className); if (coreFactory != null) { orderedModuleFactories.add(coreFactory); } else { logger.log(Level.SEVERE, "Core factory {0} not loaded", coreFactory); } } // Add any remaining non-core factories discovered. Order is not // guaranteed! orderedModuleFactories.addAll(moduleFactoriesByClass.values()); // Add any ingest module factories implemented using Jython. Order is // not guaranteed! for (IngestModuleFactory factory : JythonModuleLoader.getIngestModuleFactories()) { if (!moduleDisplayNames.contains(factory.getModuleDisplayName())) { moduleDisplayNames.add(factory.getModuleDisplayName()); orderedModuleFactories.add(factory); logger.log(Level.INFO, "Found ingest module factory: name = {0}, version = {1}", new Object[]{factory.getModuleDisplayName(), factory.getModuleVersionNumber()}); //NON-NLS } else { logger.log(Level.SEVERE, "Found duplicate ingest module display name (name = {0})", factory.getModuleDisplayName()); //NON-NLS DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message( NbBundle.getMessage(IngestModuleFactoryLoader.class, "IngestModuleFactoryLoader.errorMessages.duplicateDisplayName", factory.getModuleDisplayName()), NotifyDescriptor.ERROR_MESSAGE)); } } return orderedModuleFactories; } }
Clarify code in IngestModuleFactoryLoader
Core/src/org/sleuthkit/autopsy/ingest/IngestModuleFactoryLoader.java
Clarify code in IngestModuleFactoryLoader
Java
apache-2.0
ef2bb61dd19eeb33207387685a1ebe921cd8ba9d
0
jboss-modules/jboss-modules
/* * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.modules; import java.lang.reflect.InvocationTargetException; import java.nio.ByteBuffer; import java.security.PermissionCollection; import java.security.ProtectionDomain; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.NoSuchElementException; import __redirected.__DatatypeFactory; import __redirected.__DocumentBuilderFactory; import __redirected.__SAXParserFactory; import __redirected.__SchemaFactory; import __redirected.__TransformerFactory; import __redirected.__XMLEventFactory; import __redirected.__XMLInputFactory; import __redirected.__XMLOutputFactory; import __redirected.__XMLReaderFactory; import __redirected.__XPathFactory; import org.jboss.modules.filter.PathFilter; import org.jboss.modules.filter.PathFilters; import org.jboss.modules.log.ModuleLogger; import org.jboss.modules.security.ModularProtectionDomain; import java.io.IOException; import java.io.InputStream; import java.lang.instrument.ClassFileTransformer; import java.net.URL; import java.security.CodeSource; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; import javax.xml.datatype.DatatypeFactory; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.SAXParserFactory; import javax.xml.stream.XMLEventFactory; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLOutputFactory; import javax.xml.transform.TransformerFactory; import javax.xml.validation.SchemaFactory; import javax.xml.xpath.XPathFactory; /** * A module classloader. Instances of this class implement the complete view of classes and resources available in a * module. Contrast with {@link Module}, which has API methods to access the exported view of classes and resources. * * @author <a href="mailto:[email protected]">John Bailey</a> * @author <a href="mailto:[email protected]">David M. Lloyd</a> * @author [email protected] * * @apiviz.landmark */ public class ModuleClassLoader extends ConcurrentClassLoader { private static final Map<String, Class<?>> jaxpClassesByName; static final Map<String, URLConnectionResource> jaxpImplResources; static { boolean parallelOk = true; try { parallelOk = ClassLoader.registerAsParallelCapable(); } catch (Throwable ignored) { } if (! parallelOk) { throw new Error("Failed to register " + ModuleClassLoader.class.getName() + " as parallel-capable"); } Map<String, Class<?>> jaxpMap = new HashMap<>(); jaxpMap.put(DatatypeFactory.class.getName(), __DatatypeFactory.class); jaxpMap.put(DocumentBuilderFactory.class.getName(), __DocumentBuilderFactory.class); jaxpMap.put(SAXParserFactory.class.getName(), __SAXParserFactory.class); jaxpMap.put(SchemaFactory.class.getName(), __SchemaFactory.class); jaxpMap.put(TransformerFactory.class.getName(), __TransformerFactory.class); jaxpMap.put(XMLEventFactory.class.getName(), __XMLEventFactory.class); jaxpMap.put(XMLInputFactory.class.getName(), __XMLInputFactory.class); jaxpMap.put(XMLOutputFactory.class.getName(), __XMLOutputFactory.class); jaxpMap.put(__XMLReaderFactory.SAX_DRIVER, __XMLReaderFactory.class); jaxpMap.put(XPathFactory.class.getName(), __XPathFactory.class); Map<String, Class<?>> classesByName = new HashMap<>(); Map<String, URLConnectionResource> resources = new HashMap<>(); for (Map.Entry<String, Class<?>> entry : jaxpMap.entrySet()) { final Class<?> clazz = entry.getValue(); final String clazzName = clazz.getName(); classesByName.put(clazzName, clazz); try { resources.put("META-INF/services/" + entry.getKey(), new URLConnectionResource(new URL(null, "data:text/plain;charset=utf-8," + clazzName, DataURLStreamHandler.getInstance()))); } catch (IOException e) { throw new IllegalStateException(e); } } jaxpClassesByName = classesByName; jaxpImplResources = resources; } private final Module module; private final ClassFileTransformer transformer; private final AtomicReference<Paths<ResourceLoader, ResourceLoaderSpec>> paths = new AtomicReference<>(Paths.<ResourceLoader, ResourceLoaderSpec>none()); private final LocalLoader localLoader = new IterableLocalLoader() { public Class<?> loadClassLocal(final String name, final boolean resolve) { try { return ModuleClassLoader.this.loadClassLocal(name, resolve); } catch (ClassNotFoundException e) { final Throwable cause = e.getCause(); if (cause instanceof Error) { throw (Error) cause; } else if (cause instanceof RuntimeException) { //unlikely throw (RuntimeException) cause; } return null; } } public Package loadPackageLocal(final String name) { return findLoadedPackage(name); } public List<Resource> loadResourceLocal(final String name) { return ModuleClassLoader.this.loadResourceLocal(name); } public Iterator<Resource> iterateResources(final String startPath, final boolean recursive) { return ModuleClassLoader.this.iterateResources(startPath, recursive); } public String toString() { return "local loader for " + ModuleClassLoader.this.toString(); } }; /** * Construct a new instance. * * @param configuration the module class loader configuration to use */ protected ModuleClassLoader(final Configuration configuration) { super(configuration.getModule().getModuleLoader().getModuleDescription(configuration.getModule())); module = configuration.getModule(); paths.lazySet(new Paths<>(configuration.getResourceLoaders(), Collections.<String, List<ResourceLoader>>emptyMap())); final AssertionSetting setting = configuration.getAssertionSetting(); if (setting != AssertionSetting.INHERIT) { setDefaultAssertionStatus(setting == AssertionSetting.ENABLED); } transformer = configuration.getTransformer(); } /** * Recalculate the path maps for this module class loader. * * @return {@code true} if the paths were recalculated, or {@code false} if another thread finished recalculating * before the calling thread */ boolean recalculate() { final Paths<ResourceLoader, ResourceLoaderSpec> paths = this.paths.get(); return setResourceLoaders(paths, paths.getSourceList(ResourceLoaderSpec.NO_RESOURCE_LOADERS)); } /** * Change the set of resource loaders for this module class loader, and recalculate the path maps. * * @param resourceLoaders the new resource loaders * @return {@code true} if the paths were recalculated, or {@code false} if another thread finished recalculating * before the calling thread */ boolean setResourceLoaders(final ResourceLoaderSpec[] resourceLoaders) { return setResourceLoaders(paths.get(), resourceLoaders); } private boolean setResourceLoaders(final Paths<ResourceLoader, ResourceLoaderSpec> paths, final ResourceLoaderSpec[] resourceLoaders) { final Map<String, List<ResourceLoader>> allPaths = new HashMap<String, List<ResourceLoader>>(); for (ResourceLoaderSpec loaderSpec : resourceLoaders) { final ResourceLoader loader = loaderSpec.getResourceLoader(); final PathFilter filter = loaderSpec.getPathFilter(); for (String path : loader.getPaths()) { if (filter.accept(path)) { final List<ResourceLoader> allLoaders = allPaths.get(path); if (allLoaders == null) { ArrayList<ResourceLoader> newList = new ArrayList<ResourceLoader>(16); newList.add(loader); allPaths.put(path, newList); } else { allLoaders.add(loader); } } } } return this.paths.compareAndSet(paths, new Paths<>(resourceLoaders, allPaths)); } /** * Get the local loader which refers to this module class loader. * * @return the local loader */ LocalLoader getLocalLoader() { return localLoader; } /** {@inheritDoc} */ @Override protected final Class<?> findClass(String className, boolean exportsOnly, final boolean resolve) throws ClassNotFoundException { // Check if we have already loaded it.. Class<?> loadedClass = findLoadedClass(className); if (loadedClass != null) { if (resolve) { resolveClass(loadedClass); } return loadedClass; } final ModuleLogger log = Module.log; loadedClass = jaxpClassesByName.get(className); if (loadedClass != null) { log.trace("Found jaxp class %s from %s", loadedClass, module); if (resolve) { resolveClass(loadedClass); } return loadedClass; } final Module module = this.module; log.trace("Finding class %s from %s", className, module); final Class<?> clazz = module.loadModuleClass(className, resolve); if (clazz != null) { return clazz; } log.trace("Class %s not found from %s", className, module); throw new ClassNotFoundException(getClassNotFoundExceptionMessage(className, module)); } /** * Returns an exception message used when producing instances of ClassNotFoundException. This can be overridden * by subclasses to customise the error message. * * @param className the name of the class which is missing * @param fromModule the module from which the class could not be found * @return an exception message used when producing instances of ClassNotFoundException */ protected String getClassNotFoundExceptionMessage(String className, Module fromModule){ return className + " from [" + fromModule + "]"; } /** * Load a class from this class loader. * * @param className the class name to load * @return the loaded class or {@code null} if it was not found * @throws ClassNotFoundException if an exception occurs while loading the class or its dependencies */ public Class<?> loadClassLocal(String className) throws ClassNotFoundException { return loadClassLocal(className, false); } /** * Load a local class from this class loader. * * @param className the class name * @param resolve {@code true} to resolve the loaded class * @return the loaded class or {@code null} if it was not found * @throws ClassNotFoundException if an error occurs while loading the class */ public Class<?> loadClassLocal(final String className, final boolean resolve) throws ClassNotFoundException { final ModuleLogger log = Module.log; final Module module = this.module; log.trace("Finding local class %s from %s", className, module); // Check if we have already loaded it.. Class<?> loadedClass = findLoadedClass(className); if (loadedClass != null) { log.trace("Found previously loaded %s from %s", loadedClass, module); if (resolve) { resolveClass(loadedClass); } return loadedClass; } loadedClass = jaxpClassesByName.get(className); if (loadedClass != null) { log.trace("Found jaxp class %s from %s", loadedClass, module); if (resolve) { resolveClass(loadedClass); } return loadedClass; } final Map<String, List<ResourceLoader>> paths = this.paths.get().getAllPaths(); log.trace("Loading class %s locally from %s", className, module); String pathOfClass = Module.pathOfClass(className); final List<ResourceLoader> loaders = paths.get(pathOfClass); if (loaders == null) { // no loaders for this path return null; } // Check to see if we can define it locally it ClassSpec classSpec; ResourceLoader resourceLoader; try { if (loaders.size() > 0) { String fileName = Module.fileNameOfClass(className); for (ResourceLoader loader : loaders) { classSpec = loader.getClassSpec(fileName); if (classSpec != null) { resourceLoader = loader; try { preDefine(classSpec, className); } catch (Throwable th) { throw new ClassNotFoundException("Failed to preDefine class: " + className, th); } final Class<?> clazz = defineClass(className, classSpec, resourceLoader); try { postDefine(classSpec, clazz); } catch (Throwable th) { throw new ClassNotFoundException("Failed to postDefine class: " + className, th); } if (resolve) { resolveClass(clazz); } return clazz; } } } } catch (IOException e) { throw new ClassNotFoundException(className, e); } catch (RuntimeException e) { log.trace(e, "Unexpected runtime exception in module loader"); throw new ClassNotFoundException(className, e); } catch (Error e) { log.trace(e, "Unexpected error in module loader"); throw e; } log.trace("No local specification found for class %s in %s", className, module); return null; } /** * Load a local resource from a specific root from this module class loader. * * @param root the root name * @param name the resource name * @return the resource, or {@code null} if it was not found */ Resource loadResourceLocal(final String root, final String name) { final Map<String, List<ResourceLoader>> paths = this.paths.get().getAllPaths(); final String path = Module.pathOf(name); final List<ResourceLoader> loaders = paths.get(path); if (loaders != null) { for (ResourceLoader loader : loaders) { if (root.equals(loader.getRootName())) { return loader.getResource(name); } } } // no loaders for this path if it's not in the JAXP map return jaxpImplResources.get(name); } /** * Load a local resource from this class loader. * * @param name the resource name * @return the list of resources */ public List<Resource> loadResourceLocal(final String name) { final Map<String, List<ResourceLoader>> paths = this.paths.get().getAllPaths(); final String path = Module.pathOf(name); final List<ResourceLoader> loaders = paths.get(path); final List<Resource> list = new ArrayList<Resource>(loaders == null ? 1 : loaders.size()); if (loaders != null) { for (ResourceLoader loader : loaders) { final Resource resource = loader.getResource(name); if (resource != null) { list.add(resource); } } } final URLConnectionResource resource = jaxpImplResources.get(name); if (resource != null) { list.add(resource); } return list.isEmpty() ? Collections.emptyList() : list; } private Class<?> doDefineOrLoadClass(final String className, final byte[] bytes, final ByteBuffer byteBuffer, ProtectionDomain protectionDomain) { try { final Class<?> definedClass = bytes != null ? defineClass(className, bytes, 0, bytes.length, protectionDomain) : defineClass(className, byteBuffer, protectionDomain); module.getModuleLoader().incClassCount(); return definedClass; } catch (LinkageError e) { final Class<?> loadedClass = findLoadedClass(className); if (loadedClass != null) { module.getModuleLoader().incRaceCount(); return loadedClass; } throw e; } } private final IdentityHashMap<CodeSource, ProtectionDomain> protectionDomains = new IdentityHashMap<CodeSource, ProtectionDomain>(); private ProtectionDomain getProtectionDomain(CodeSource codeSource) { final IdentityHashMap<CodeSource, ProtectionDomain> map = protectionDomains; synchronized (map) { ProtectionDomain protectionDomain = map.get(codeSource); if (protectionDomain == null) { final PermissionCollection permissions = module.getPermissionCollection(); protectionDomain = new ModularProtectionDomain(codeSource, permissions, this); map.put(codeSource, protectionDomain); } return protectionDomain; } } /** * Define a class from a class name and class spec. Also defines any enclosing {@link Package} instances, * and performs any sealed-package checks. * * @param name the class name * @param classSpec the class spec * @param resourceLoader the resource loader of the class spec * @return the new class */ private Class<?> defineClass(final String name, final ClassSpec classSpec, final ResourceLoader resourceLoader) { final ModuleLogger log = Module.log; final Module module = this.module; log.trace("Attempting to define class %s in %s", name, module); // Ensure that the package is loaded final int lastIdx = name.lastIndexOf('.'); if (lastIdx != -1) { // there's a package name; get the Package for it final String packageName = name.substring(0, lastIdx); synchronized (this) { Package pkg = findLoadedPackage(packageName); if (pkg == null) { try { pkg = definePackage(packageName, resourceLoader.getPackageSpec(packageName)); } catch (IOException e) { pkg = definePackage(packageName, null); } } // Check sealing if (pkg.isSealed() && ! pkg.isSealed(classSpec.getCodeSource().getLocation())) { log.trace("Detected a sealing violation (attempt to define class %s in sealed package %s in %s)", name, packageName, module); // use the same message as the JDK throw new SecurityException("sealing violation: package " + packageName + " is sealed"); } } } final Class<?> newClass; try { byte[] bytes = classSpec.getBytes(); ByteBuffer byteBuffer = classSpec.getByteBuffer(); try { final ProtectionDomain protectionDomain = getProtectionDomain(classSpec.getCodeSource()); if (transformer != null) { if (bytes == null) { final ByteBuffer dup = byteBuffer.duplicate(); byteBuffer = null; bytes = new byte[dup.remaining()]; dup.get(bytes); } try { bytes = transformer.transform(this, name.replace('.', '/'), null, protectionDomain, bytes); } catch (Exception e) { ClassFormatError error = new ClassFormatError(e.getMessage()); error.initCause(e); throw error; } } final long start = Metrics.getCurrentCPUTime(); newClass = doDefineOrLoadClass(name, bytes, byteBuffer, protectionDomain); module.getModuleLoader().addClassLoadTime(Metrics.getCurrentCPUTime() - start); log.classDefined(name, module); } catch (LinkageError e) { // Prepend the current class name, so that transitive class definition issues are clearly expressed Error ne; try { final String oldMsg = e.getMessage(); final String newMsg = "Failed to link " + name.replace('.', '/') + " (" + module + ")"; ne = e.getClass().getConstructor(String.class).newInstance(oldMsg == null || oldMsg.isEmpty() ? newMsg : newMsg + ": " + oldMsg); } catch (InstantiationException | NoSuchMethodException | InvocationTargetException | IllegalAccessException ignored) { // just throw the original throw e; } throw ne; } } catch (Error | RuntimeException e) { log.classDefineFailed(e, name, module); throw e; } final AssertionSetting setting = classSpec.getAssertionSetting(); if (setting != AssertionSetting.INHERIT) { setClassAssertionStatus(name, setting == AssertionSetting.ENABLED); } return newClass; } /** * A hook which is invoked before a class is defined. * * @param classSpec the class spec of the defined class * @param className the class to be defined */ @SuppressWarnings("unused") protected void preDefine(ClassSpec classSpec, String className) { } /** * A hook which is invoked after a class is defined. * * @param classSpec the class spec of the defined class * @param definedClass the class that was defined */ @SuppressWarnings("unused") protected void postDefine(ClassSpec classSpec, Class<?> definedClass) { } /** * Define a package from a package spec. * * @param name the package name * @param spec the package specification * @return the new package */ private Package definePackage(final String name, final PackageSpec spec) { final Module module = this.module; final ModuleLogger log = Module.log; log.trace("Attempting to define package %s in %s", name, module); final Package pkg; if (spec == null) { pkg = definePackage(name, null, null, null, null, null, null, null); } else { pkg = definePackage(name, spec.getSpecTitle(), spec.getSpecVersion(), spec.getSpecVendor(), spec.getImplTitle(), spec.getImplVersion(), spec.getImplVendor(), spec.getSealBase()); final AssertionSetting setting = spec.getAssertionSetting(); if (setting != AssertionSetting.INHERIT) { setPackageAssertionStatus(name, setting == AssertionSetting.ENABLED); } } log.trace("Defined package %s in %s", name, module); return pkg; } /** * Find a library from one of the resource loaders. * * @param libname the library name * @return the full absolute path to the library */ @Override protected final String findLibrary(final String libname) { final ModuleLogger log = Module.log; log.trace("Attempting to load native library %s from %s", libname, module); for (ResourceLoaderSpec loader : paths.get().getSourceList(ResourceLoaderSpec.NO_RESOURCE_LOADERS)) { final String library = loader.getResourceLoader().getLibrary(libname); if (library != null) { return library; } } return null; } /** {@inheritDoc} */ @Override public final URL findResource(final String name, final boolean exportsOnly) { return module.getResource(name); } /** {@inheritDoc} */ @Override public final Enumeration<URL> findResources(final String name, final boolean exportsOnly) { return module.getResources(name); } /** {@inheritDoc} */ @Override public final InputStream findResourceAsStream(final String name, boolean exportsOnly) { try { return module.getResourceAsStream(name); } catch (IOException e) { return null; } } /** * Get the module for this class loader. * * @return the module */ public final Module getModule() { return module; } /** * Get the name of this module. This method is used by Java 9 in debug output. * * @return the name of this module */ public final String getName() { return super.getName(); } /** * Get a string representation of this class loader. * * @return the string */ @Override public final String toString() { return getClass().getSimpleName() + " for " + module; } Set<String> getPaths() { return paths.get().getAllPaths().keySet(); } /** {@inheritDoc} */ @Override protected final Package definePackage(final String name, final String specTitle, final String specVersion, final String specVendor, final String implTitle, final String implVersion, final String implVendor, final URL sealBase) throws IllegalArgumentException { return super.definePackage(name, specTitle, specVersion, specVendor, implTitle, implVersion, implVendor, sealBase); } /** {@inheritDoc} */ @Override protected final Package getPackageByName(final String name) { Package loaded = findLoadedPackage(name); if (loaded != null) { return loaded; } return module.getPackage(name); } /** {@inheritDoc} */ @Override protected final Package[] getPackages() { return module.getPackages(); } /** {@inheritDoc} */ @Override public final void setDefaultAssertionStatus(final boolean enabled) { super.setDefaultAssertionStatus(enabled); } /** {@inheritDoc} */ @Override public final void setPackageAssertionStatus(final String packageName, final boolean enabled) { super.setPackageAssertionStatus(packageName, enabled); } /** {@inheritDoc} */ @Override public final void setClassAssertionStatus(final String className, final boolean enabled) { super.setClassAssertionStatus(className, enabled); } /** {@inheritDoc} */ @Override public final void clearAssertionStatus() { super.clearAssertionStatus(); } /** {@inheritDoc} */ @Override public final int hashCode() { return super.hashCode(); } /** {@inheritDoc} */ @Override public final boolean equals(final Object obj) { return super.equals(obj); } /** {@inheritDoc} */ @Override protected final Object clone() throws CloneNotSupportedException { return super.clone(); } /** {@inheritDoc} */ @Override protected final void finalize() throws Throwable { super.finalize(); } ResourceLoader[] getResourceLoaders() { final ResourceLoaderSpec[] specs = paths.get().getSourceList(ResourceLoaderSpec.NO_RESOURCE_LOADERS); final int length = specs.length; final ResourceLoader[] loaders = new ResourceLoader[length]; for (int i = 0; i < length; i++) { loaders[i] = specs[i].getResourceLoader(); } return loaders; } /** * Iterate the resources within this module class loader. Only resource roots which are inherently iterable will * be checked, thus the result of this method may only be a subset of the actual loadable resources. The returned * resources are not sorted or grouped in any particular way. * * @param startName the directory name to search * @param recurse {@code true} to recurse into subdirectories, {@code false} otherwise * @return the resource iterator */ public final Iterator<Resource> iterateResources(final String startName, final boolean recurse) { final String realStartName = PathUtils.canonicalize(PathUtils.relativize(startName)); final PathFilter filter; if (recurse) { if (realStartName.isEmpty()) { filter = PathFilters.acceptAll(); } else { filter = PathFilters.any(PathFilters.is(realStartName), PathFilters.isChildOf(realStartName)); } } else { filter = PathFilters.is(realStartName); } final Map<String, List<ResourceLoader>> paths = this.paths.get().getAllPaths(); final Iterator<Map.Entry<String, List<ResourceLoader>>> iterator = paths.entrySet().iterator(); return new Iterator<Resource>() { private String path; private Iterator<Resource> resourceIterator; private Iterator<ResourceLoader> loaderIterator; private Resource next; public boolean hasNext() { while (next == null) { if (resourceIterator != null) { assert path != null; if (resourceIterator.hasNext()) { next = resourceIterator.next(); return true; } resourceIterator = null; } if (loaderIterator != null) { assert path != null; if (loaderIterator.hasNext()) { final ResourceLoader loader = loaderIterator.next(); if (loader instanceof IterableResourceLoader) { resourceIterator = ((IterableResourceLoader)loader).iterateResources(path, false); continue; } } loaderIterator = null; } if (! iterator.hasNext()) { return false; } final Map.Entry<String, List<ResourceLoader>> entry = iterator.next(); path = entry.getKey(); if (filter.accept(path)) { loaderIterator = entry.getValue().iterator(); } } return true; } public Resource next() { if (! hasNext()) throw new NoSuchElementException(); try { return next; } finally { next = null; } } public void remove() { throw new UnsupportedOperationException(); } }; } /** * Get the (unmodifiable) set of paths which are locally available in this module class loader. The set will * include all paths defined by the module's resource loaders, minus any paths excluded by filters. The set will * generally always contain an empty entry (""). The set is unordered and unsorted, and is iterable in O(n) time * and accessible in O(1) time. * * @return the set of local paths */ public final Set<String> getLocalPaths() { return Collections.unmodifiableSet(paths.get().getAllPaths().keySet()); } /** * An opaque configuration used internally to create a module class loader. * * @apiviz.exclude */ public static final class Configuration { private final Module module; private final AssertionSetting assertionSetting; private final ResourceLoaderSpec[] resourceLoaders; private final ClassFileTransformer transformer; Configuration(final Module module, final AssertionSetting assertionSetting, final ResourceLoaderSpec[] resourceLoaders, final ClassFileTransformer transformer) { this.module = module; this.assertionSetting = assertionSetting; this.resourceLoaders = resourceLoaders; this.transformer = transformer; } Module getModule() { return module; } AssertionSetting getAssertionSetting() { return assertionSetting; } ResourceLoaderSpec[] getResourceLoaders() { return resourceLoaders; } ClassFileTransformer getTransformer() { return transformer; } } }
src/main/java/org/jboss/modules/ModuleClassLoader.java
/* * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.modules; import java.lang.reflect.InvocationTargetException; import java.nio.ByteBuffer; import java.security.PermissionCollection; import java.security.ProtectionDomain; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.NoSuchElementException; import __redirected.__DatatypeFactory; import __redirected.__DocumentBuilderFactory; import __redirected.__SAXParserFactory; import __redirected.__SchemaFactory; import __redirected.__TransformerFactory; import __redirected.__XMLEventFactory; import __redirected.__XMLInputFactory; import __redirected.__XMLOutputFactory; import __redirected.__XMLReaderFactory; import __redirected.__XPathFactory; import org.jboss.modules.filter.PathFilter; import org.jboss.modules.filter.PathFilters; import org.jboss.modules.log.ModuleLogger; import org.jboss.modules.security.ModularProtectionDomain; import java.io.IOException; import java.io.InputStream; import java.lang.instrument.ClassFileTransformer; import java.net.URL; import java.security.CodeSource; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; import javax.xml.datatype.DatatypeFactory; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.SAXParserFactory; import javax.xml.stream.XMLEventFactory; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLOutputFactory; import javax.xml.transform.TransformerFactory; import javax.xml.validation.SchemaFactory; import javax.xml.xpath.XPathFactory; /** * A module classloader. Instances of this class implement the complete view of classes and resources available in a * module. Contrast with {@link Module}, which has API methods to access the exported view of classes and resources. * * @author <a href="mailto:[email protected]">John Bailey</a> * @author <a href="mailto:[email protected]">David M. Lloyd</a> * @author [email protected] * * @apiviz.landmark */ public class ModuleClassLoader extends ConcurrentClassLoader { private static final Map<String, Class<?>> jaxpClassesByName; static final Map<String, URLConnectionResource> jaxpImplResources; static { boolean parallelOk = true; try { parallelOk = ClassLoader.registerAsParallelCapable(); } catch (Throwable ignored) { } if (! parallelOk) { throw new Error("Failed to register " + ModuleClassLoader.class.getName() + " as parallel-capable"); } Map<String, Class<?>> jaxpMap = new HashMap<>(); jaxpMap.put(DatatypeFactory.class.getName(), __DatatypeFactory.class); jaxpMap.put(DocumentBuilderFactory.class.getName(), __DocumentBuilderFactory.class); jaxpMap.put(SAXParserFactory.class.getName(), __SAXParserFactory.class); jaxpMap.put(SchemaFactory.class.getName(), __SchemaFactory.class); jaxpMap.put(TransformerFactory.class.getName(), __TransformerFactory.class); jaxpMap.put(XMLEventFactory.class.getName(), __XMLEventFactory.class); jaxpMap.put(XMLInputFactory.class.getName(), __XMLInputFactory.class); jaxpMap.put(XMLOutputFactory.class.getName(), __XMLOutputFactory.class); jaxpMap.put(__XMLReaderFactory.SAX_DRIVER, __XMLReaderFactory.class); jaxpMap.put(XPathFactory.class.getName(), __XPathFactory.class); Map<String, Class<?>> classesByName = new HashMap<>(); Map<String, URLConnectionResource> resources = new HashMap<>(); for (Map.Entry<String, Class<?>> entry : jaxpMap.entrySet()) { final Class<?> clazz = entry.getValue(); final String clazzName = clazz.getName(); classesByName.put(clazzName, clazz); try { resources.put("META-INF/services/" + entry.getKey(), new URLConnectionResource(new URL("data:text/plain;charset=utf-8," + clazzName))); } catch (IOException e) { throw new IllegalStateException(e); } } jaxpClassesByName = classesByName; jaxpImplResources = resources; } private final Module module; private final ClassFileTransformer transformer; private final AtomicReference<Paths<ResourceLoader, ResourceLoaderSpec>> paths = new AtomicReference<>(Paths.<ResourceLoader, ResourceLoaderSpec>none()); private final LocalLoader localLoader = new IterableLocalLoader() { public Class<?> loadClassLocal(final String name, final boolean resolve) { try { return ModuleClassLoader.this.loadClassLocal(name, resolve); } catch (ClassNotFoundException e) { final Throwable cause = e.getCause(); if (cause instanceof Error) { throw (Error) cause; } else if (cause instanceof RuntimeException) { //unlikely throw (RuntimeException) cause; } return null; } } public Package loadPackageLocal(final String name) { return findLoadedPackage(name); } public List<Resource> loadResourceLocal(final String name) { return ModuleClassLoader.this.loadResourceLocal(name); } public Iterator<Resource> iterateResources(final String startPath, final boolean recursive) { return ModuleClassLoader.this.iterateResources(startPath, recursive); } public String toString() { return "local loader for " + ModuleClassLoader.this.toString(); } }; /** * Construct a new instance. * * @param configuration the module class loader configuration to use */ protected ModuleClassLoader(final Configuration configuration) { super(configuration.getModule().getModuleLoader().getModuleDescription(configuration.getModule())); module = configuration.getModule(); paths.lazySet(new Paths<>(configuration.getResourceLoaders(), Collections.<String, List<ResourceLoader>>emptyMap())); final AssertionSetting setting = configuration.getAssertionSetting(); if (setting != AssertionSetting.INHERIT) { setDefaultAssertionStatus(setting == AssertionSetting.ENABLED); } transformer = configuration.getTransformer(); } /** * Recalculate the path maps for this module class loader. * * @return {@code true} if the paths were recalculated, or {@code false} if another thread finished recalculating * before the calling thread */ boolean recalculate() { final Paths<ResourceLoader, ResourceLoaderSpec> paths = this.paths.get(); return setResourceLoaders(paths, paths.getSourceList(ResourceLoaderSpec.NO_RESOURCE_LOADERS)); } /** * Change the set of resource loaders for this module class loader, and recalculate the path maps. * * @param resourceLoaders the new resource loaders * @return {@code true} if the paths were recalculated, or {@code false} if another thread finished recalculating * before the calling thread */ boolean setResourceLoaders(final ResourceLoaderSpec[] resourceLoaders) { return setResourceLoaders(paths.get(), resourceLoaders); } private boolean setResourceLoaders(final Paths<ResourceLoader, ResourceLoaderSpec> paths, final ResourceLoaderSpec[] resourceLoaders) { final Map<String, List<ResourceLoader>> allPaths = new HashMap<String, List<ResourceLoader>>(); for (ResourceLoaderSpec loaderSpec : resourceLoaders) { final ResourceLoader loader = loaderSpec.getResourceLoader(); final PathFilter filter = loaderSpec.getPathFilter(); for (String path : loader.getPaths()) { if (filter.accept(path)) { final List<ResourceLoader> allLoaders = allPaths.get(path); if (allLoaders == null) { ArrayList<ResourceLoader> newList = new ArrayList<ResourceLoader>(16); newList.add(loader); allPaths.put(path, newList); } else { allLoaders.add(loader); } } } } return this.paths.compareAndSet(paths, new Paths<>(resourceLoaders, allPaths)); } /** * Get the local loader which refers to this module class loader. * * @return the local loader */ LocalLoader getLocalLoader() { return localLoader; } /** {@inheritDoc} */ @Override protected final Class<?> findClass(String className, boolean exportsOnly, final boolean resolve) throws ClassNotFoundException { // Check if we have already loaded it.. Class<?> loadedClass = findLoadedClass(className); if (loadedClass != null) { if (resolve) { resolveClass(loadedClass); } return loadedClass; } final ModuleLogger log = Module.log; loadedClass = jaxpClassesByName.get(className); if (loadedClass != null) { log.trace("Found jaxp class %s from %s", loadedClass, module); if (resolve) { resolveClass(loadedClass); } return loadedClass; } final Module module = this.module; log.trace("Finding class %s from %s", className, module); final Class<?> clazz = module.loadModuleClass(className, resolve); if (clazz != null) { return clazz; } log.trace("Class %s not found from %s", className, module); throw new ClassNotFoundException(getClassNotFoundExceptionMessage(className, module)); } /** * Returns an exception message used when producing instances of ClassNotFoundException. This can be overridden * by subclasses to customise the error message. * * @param className the name of the class which is missing * @param fromModule the module from which the class could not be found * @return an exception message used when producing instances of ClassNotFoundException */ protected String getClassNotFoundExceptionMessage(String className, Module fromModule){ return className + " from [" + fromModule + "]"; } /** * Load a class from this class loader. * * @param className the class name to load * @return the loaded class or {@code null} if it was not found * @throws ClassNotFoundException if an exception occurs while loading the class or its dependencies */ public Class<?> loadClassLocal(String className) throws ClassNotFoundException { return loadClassLocal(className, false); } /** * Load a local class from this class loader. * * @param className the class name * @param resolve {@code true} to resolve the loaded class * @return the loaded class or {@code null} if it was not found * @throws ClassNotFoundException if an error occurs while loading the class */ public Class<?> loadClassLocal(final String className, final boolean resolve) throws ClassNotFoundException { final ModuleLogger log = Module.log; final Module module = this.module; log.trace("Finding local class %s from %s", className, module); // Check if we have already loaded it.. Class<?> loadedClass = findLoadedClass(className); if (loadedClass != null) { log.trace("Found previously loaded %s from %s", loadedClass, module); if (resolve) { resolveClass(loadedClass); } return loadedClass; } loadedClass = jaxpClassesByName.get(className); if (loadedClass != null) { log.trace("Found jaxp class %s from %s", loadedClass, module); if (resolve) { resolveClass(loadedClass); } return loadedClass; } final Map<String, List<ResourceLoader>> paths = this.paths.get().getAllPaths(); log.trace("Loading class %s locally from %s", className, module); String pathOfClass = Module.pathOfClass(className); final List<ResourceLoader> loaders = paths.get(pathOfClass); if (loaders == null) { // no loaders for this path return null; } // Check to see if we can define it locally it ClassSpec classSpec; ResourceLoader resourceLoader; try { if (loaders.size() > 0) { String fileName = Module.fileNameOfClass(className); for (ResourceLoader loader : loaders) { classSpec = loader.getClassSpec(fileName); if (classSpec != null) { resourceLoader = loader; try { preDefine(classSpec, className); } catch (Throwable th) { throw new ClassNotFoundException("Failed to preDefine class: " + className, th); } final Class<?> clazz = defineClass(className, classSpec, resourceLoader); try { postDefine(classSpec, clazz); } catch (Throwable th) { throw new ClassNotFoundException("Failed to postDefine class: " + className, th); } if (resolve) { resolveClass(clazz); } return clazz; } } } } catch (IOException e) { throw new ClassNotFoundException(className, e); } catch (RuntimeException e) { log.trace(e, "Unexpected runtime exception in module loader"); throw new ClassNotFoundException(className, e); } catch (Error e) { log.trace(e, "Unexpected error in module loader"); throw e; } log.trace("No local specification found for class %s in %s", className, module); return null; } /** * Load a local resource from a specific root from this module class loader. * * @param root the root name * @param name the resource name * @return the resource, or {@code null} if it was not found */ Resource loadResourceLocal(final String root, final String name) { final Map<String, List<ResourceLoader>> paths = this.paths.get().getAllPaths(); final String path = Module.pathOf(name); final List<ResourceLoader> loaders = paths.get(path); if (loaders != null) { for (ResourceLoader loader : loaders) { if (root.equals(loader.getRootName())) { return loader.getResource(name); } } } // no loaders for this path if it's not in the JAXP map return jaxpImplResources.get(name); } /** * Load a local resource from this class loader. * * @param name the resource name * @return the list of resources */ public List<Resource> loadResourceLocal(final String name) { final Map<String, List<ResourceLoader>> paths = this.paths.get().getAllPaths(); final String path = Module.pathOf(name); final List<ResourceLoader> loaders = paths.get(path); final List<Resource> list = new ArrayList<Resource>(loaders == null ? 1 : loaders.size()); if (loaders != null) { for (ResourceLoader loader : loaders) { final Resource resource = loader.getResource(name); if (resource != null) { list.add(resource); } } } final URLConnectionResource resource = jaxpImplResources.get(name); if (resource != null) { list.add(resource); } return list.isEmpty() ? Collections.emptyList() : list; } private Class<?> doDefineOrLoadClass(final String className, final byte[] bytes, final ByteBuffer byteBuffer, ProtectionDomain protectionDomain) { try { final Class<?> definedClass = bytes != null ? defineClass(className, bytes, 0, bytes.length, protectionDomain) : defineClass(className, byteBuffer, protectionDomain); module.getModuleLoader().incClassCount(); return definedClass; } catch (LinkageError e) { final Class<?> loadedClass = findLoadedClass(className); if (loadedClass != null) { module.getModuleLoader().incRaceCount(); return loadedClass; } throw e; } } private final IdentityHashMap<CodeSource, ProtectionDomain> protectionDomains = new IdentityHashMap<CodeSource, ProtectionDomain>(); private ProtectionDomain getProtectionDomain(CodeSource codeSource) { final IdentityHashMap<CodeSource, ProtectionDomain> map = protectionDomains; synchronized (map) { ProtectionDomain protectionDomain = map.get(codeSource); if (protectionDomain == null) { final PermissionCollection permissions = module.getPermissionCollection(); protectionDomain = new ModularProtectionDomain(codeSource, permissions, this); map.put(codeSource, protectionDomain); } return protectionDomain; } } /** * Define a class from a class name and class spec. Also defines any enclosing {@link Package} instances, * and performs any sealed-package checks. * * @param name the class name * @param classSpec the class spec * @param resourceLoader the resource loader of the class spec * @return the new class */ private Class<?> defineClass(final String name, final ClassSpec classSpec, final ResourceLoader resourceLoader) { final ModuleLogger log = Module.log; final Module module = this.module; log.trace("Attempting to define class %s in %s", name, module); // Ensure that the package is loaded final int lastIdx = name.lastIndexOf('.'); if (lastIdx != -1) { // there's a package name; get the Package for it final String packageName = name.substring(0, lastIdx); synchronized (this) { Package pkg = findLoadedPackage(packageName); if (pkg == null) { try { pkg = definePackage(packageName, resourceLoader.getPackageSpec(packageName)); } catch (IOException e) { pkg = definePackage(packageName, null); } } // Check sealing if (pkg.isSealed() && ! pkg.isSealed(classSpec.getCodeSource().getLocation())) { log.trace("Detected a sealing violation (attempt to define class %s in sealed package %s in %s)", name, packageName, module); // use the same message as the JDK throw new SecurityException("sealing violation: package " + packageName + " is sealed"); } } } final Class<?> newClass; try { byte[] bytes = classSpec.getBytes(); ByteBuffer byteBuffer = classSpec.getByteBuffer(); try { final ProtectionDomain protectionDomain = getProtectionDomain(classSpec.getCodeSource()); if (transformer != null) { if (bytes == null) { final ByteBuffer dup = byteBuffer.duplicate(); byteBuffer = null; bytes = new byte[dup.remaining()]; dup.get(bytes); } try { bytes = transformer.transform(this, name.replace('.', '/'), null, protectionDomain, bytes); } catch (Exception e) { ClassFormatError error = new ClassFormatError(e.getMessage()); error.initCause(e); throw error; } } final long start = Metrics.getCurrentCPUTime(); newClass = doDefineOrLoadClass(name, bytes, byteBuffer, protectionDomain); module.getModuleLoader().addClassLoadTime(Metrics.getCurrentCPUTime() - start); log.classDefined(name, module); } catch (LinkageError e) { // Prepend the current class name, so that transitive class definition issues are clearly expressed Error ne; try { final String oldMsg = e.getMessage(); final String newMsg = "Failed to link " + name.replace('.', '/') + " (" + module + ")"; ne = e.getClass().getConstructor(String.class).newInstance(oldMsg == null || oldMsg.isEmpty() ? newMsg : newMsg + ": " + oldMsg); } catch (InstantiationException | NoSuchMethodException | InvocationTargetException | IllegalAccessException ignored) { // just throw the original throw e; } throw ne; } } catch (Error | RuntimeException e) { log.classDefineFailed(e, name, module); throw e; } final AssertionSetting setting = classSpec.getAssertionSetting(); if (setting != AssertionSetting.INHERIT) { setClassAssertionStatus(name, setting == AssertionSetting.ENABLED); } return newClass; } /** * A hook which is invoked before a class is defined. * * @param classSpec the class spec of the defined class * @param className the class to be defined */ @SuppressWarnings("unused") protected void preDefine(ClassSpec classSpec, String className) { } /** * A hook which is invoked after a class is defined. * * @param classSpec the class spec of the defined class * @param definedClass the class that was defined */ @SuppressWarnings("unused") protected void postDefine(ClassSpec classSpec, Class<?> definedClass) { } /** * Define a package from a package spec. * * @param name the package name * @param spec the package specification * @return the new package */ private Package definePackage(final String name, final PackageSpec spec) { final Module module = this.module; final ModuleLogger log = Module.log; log.trace("Attempting to define package %s in %s", name, module); final Package pkg; if (spec == null) { pkg = definePackage(name, null, null, null, null, null, null, null); } else { pkg = definePackage(name, spec.getSpecTitle(), spec.getSpecVersion(), spec.getSpecVendor(), spec.getImplTitle(), spec.getImplVersion(), spec.getImplVendor(), spec.getSealBase()); final AssertionSetting setting = spec.getAssertionSetting(); if (setting != AssertionSetting.INHERIT) { setPackageAssertionStatus(name, setting == AssertionSetting.ENABLED); } } log.trace("Defined package %s in %s", name, module); return pkg; } /** * Find a library from one of the resource loaders. * * @param libname the library name * @return the full absolute path to the library */ @Override protected final String findLibrary(final String libname) { final ModuleLogger log = Module.log; log.trace("Attempting to load native library %s from %s", libname, module); for (ResourceLoaderSpec loader : paths.get().getSourceList(ResourceLoaderSpec.NO_RESOURCE_LOADERS)) { final String library = loader.getResourceLoader().getLibrary(libname); if (library != null) { return library; } } return null; } /** {@inheritDoc} */ @Override public final URL findResource(final String name, final boolean exportsOnly) { return module.getResource(name); } /** {@inheritDoc} */ @Override public final Enumeration<URL> findResources(final String name, final boolean exportsOnly) { return module.getResources(name); } /** {@inheritDoc} */ @Override public final InputStream findResourceAsStream(final String name, boolean exportsOnly) { try { return module.getResourceAsStream(name); } catch (IOException e) { return null; } } /** * Get the module for this class loader. * * @return the module */ public final Module getModule() { return module; } /** * Get the name of this module. This method is used by Java 9 in debug output. * * @return the name of this module */ public final String getName() { return super.getName(); } /** * Get a string representation of this class loader. * * @return the string */ @Override public final String toString() { return getClass().getSimpleName() + " for " + module; } Set<String> getPaths() { return paths.get().getAllPaths().keySet(); } /** {@inheritDoc} */ @Override protected final Package definePackage(final String name, final String specTitle, final String specVersion, final String specVendor, final String implTitle, final String implVersion, final String implVendor, final URL sealBase) throws IllegalArgumentException { return super.definePackage(name, specTitle, specVersion, specVendor, implTitle, implVersion, implVendor, sealBase); } /** {@inheritDoc} */ @Override protected final Package getPackageByName(final String name) { Package loaded = findLoadedPackage(name); if (loaded != null) { return loaded; } return module.getPackage(name); } /** {@inheritDoc} */ @Override protected final Package[] getPackages() { return module.getPackages(); } /** {@inheritDoc} */ @Override public final void setDefaultAssertionStatus(final boolean enabled) { super.setDefaultAssertionStatus(enabled); } /** {@inheritDoc} */ @Override public final void setPackageAssertionStatus(final String packageName, final boolean enabled) { super.setPackageAssertionStatus(packageName, enabled); } /** {@inheritDoc} */ @Override public final void setClassAssertionStatus(final String className, final boolean enabled) { super.setClassAssertionStatus(className, enabled); } /** {@inheritDoc} */ @Override public final void clearAssertionStatus() { super.clearAssertionStatus(); } /** {@inheritDoc} */ @Override public final int hashCode() { return super.hashCode(); } /** {@inheritDoc} */ @Override public final boolean equals(final Object obj) { return super.equals(obj); } /** {@inheritDoc} */ @Override protected final Object clone() throws CloneNotSupportedException { return super.clone(); } /** {@inheritDoc} */ @Override protected final void finalize() throws Throwable { super.finalize(); } ResourceLoader[] getResourceLoaders() { final ResourceLoaderSpec[] specs = paths.get().getSourceList(ResourceLoaderSpec.NO_RESOURCE_LOADERS); final int length = specs.length; final ResourceLoader[] loaders = new ResourceLoader[length]; for (int i = 0; i < length; i++) { loaders[i] = specs[i].getResourceLoader(); } return loaders; } /** * Iterate the resources within this module class loader. Only resource roots which are inherently iterable will * be checked, thus the result of this method may only be a subset of the actual loadable resources. The returned * resources are not sorted or grouped in any particular way. * * @param startName the directory name to search * @param recurse {@code true} to recurse into subdirectories, {@code false} otherwise * @return the resource iterator */ public final Iterator<Resource> iterateResources(final String startName, final boolean recurse) { final String realStartName = PathUtils.canonicalize(PathUtils.relativize(startName)); final PathFilter filter; if (recurse) { if (realStartName.isEmpty()) { filter = PathFilters.acceptAll(); } else { filter = PathFilters.any(PathFilters.is(realStartName), PathFilters.isChildOf(realStartName)); } } else { filter = PathFilters.is(realStartName); } final Map<String, List<ResourceLoader>> paths = this.paths.get().getAllPaths(); final Iterator<Map.Entry<String, List<ResourceLoader>>> iterator = paths.entrySet().iterator(); return new Iterator<Resource>() { private String path; private Iterator<Resource> resourceIterator; private Iterator<ResourceLoader> loaderIterator; private Resource next; public boolean hasNext() { while (next == null) { if (resourceIterator != null) { assert path != null; if (resourceIterator.hasNext()) { next = resourceIterator.next(); return true; } resourceIterator = null; } if (loaderIterator != null) { assert path != null; if (loaderIterator.hasNext()) { final ResourceLoader loader = loaderIterator.next(); if (loader instanceof IterableResourceLoader) { resourceIterator = ((IterableResourceLoader)loader).iterateResources(path, false); continue; } } loaderIterator = null; } if (! iterator.hasNext()) { return false; } final Map.Entry<String, List<ResourceLoader>> entry = iterator.next(); path = entry.getKey(); if (filter.accept(path)) { loaderIterator = entry.getValue().iterator(); } } return true; } public Resource next() { if (! hasNext()) throw new NoSuchElementException(); try { return next; } finally { next = null; } } public void remove() { throw new UnsupportedOperationException(); } }; } /** * Get the (unmodifiable) set of paths which are locally available in this module class loader. The set will * include all paths defined by the module's resource loaders, minus any paths excluded by filters. The set will * generally always contain an empty entry (""). The set is unordered and unsorted, and is iterable in O(n) time * and accessible in O(1) time. * * @return the set of local paths */ public final Set<String> getLocalPaths() { return Collections.unmodifiableSet(paths.get().getAllPaths().keySet()); } /** * An opaque configuration used internally to create a module class loader. * * @apiviz.exclude */ public static final class Configuration { private final Module module; private final AssertionSetting assertionSetting; private final ResourceLoaderSpec[] resourceLoaders; private final ClassFileTransformer transformer; Configuration(final Module module, final AssertionSetting assertionSetting, final ResourceLoaderSpec[] resourceLoaders, final ClassFileTransformer transformer) { this.module = module; this.assertionSetting = assertionSetting; this.resourceLoaders = resourceLoaders; this.transformer = transformer; } Module getModule() { return module; } AssertionSetting getAssertionSetting() { return assertionSetting; } ResourceLoaderSpec[] getResourceLoaders() { return resourceLoaders; } ClassFileTransformer getTransformer() { return transformer; } } }
[MODULES-365] Using URLStreamHandler explicitly in the URL constructor
src/main/java/org/jboss/modules/ModuleClassLoader.java
[MODULES-365] Using URLStreamHandler explicitly in the URL constructor
Java
apache-2.0
65bcc4494da45e85d93f76872eafd3e260194fb8
0
rsahlin/graphics-by-opengl,rsahlin/graphics-by-opengl,rsahlin/graphics-by-opengl
package com.nucleus.geometry; import java.nio.ByteBuffer; import com.nucleus.geometry.ElementBuffer.Mode; import com.nucleus.geometry.ElementBuffer.Type; import com.nucleus.geometry.Mesh.BufferIndex; import com.nucleus.opengl.GLESWrapper.GLES20; import com.nucleus.shader.ShaderProgram; /** * Utility class to help build different type of Meshes. * * @author Richard Sahlin * */ public class MeshBuilder { /** * Number of vertices for an indexed quad */ public final static int INDEXED_QUAD_VERTICES = 4; /** * Number of components for X,Y,Z */ public final static int XYZ_COMPONENTS = 3; /** * Number of indexes for a quad drawn using drawElements (3 * 2) */ public final static int QUAD_INDICES = 6; /** * Sets 3 component position in the destination array. * This method is not speed efficient, only use when very few positions shall be set. * * @param x * @param y * @param z * @param dest position will be set here, must contain at least pos + 3 values. * @param pos The index where data is written. */ public static void setPosition(float x, float y, float z, float[] dest, int pos) { dest[pos++] = x; dest[pos++] = y; dest[pos++] = z; } /** * Sets 3 component position in the destination buffer. * This method is not speed efficient, only use when very few positions shall be set. * * @param x * @param y * @param z * @param buffer */ public static void setPosition(float x, float y, float z, ByteBuffer buffer) { buffer.putFloat(x); buffer.putFloat(y); buffer.putFloat(z); } /** * Builds a buffer containing the 4 vertices for XYZ components, to be indexed when drawing, ie drawn using * drawElements(). * The vertices will be centered using anchorX and anchorY, a value of 0 will be left/top aligned. * A value of 1/width will be centered horizontally. * * @param width * @param height * @param z The Z position * @param anchorX X axis anchor offet, 0 will be left centered (assuming x axis is increasing to the right) * @param anchorY Y axis anchor offet, 0 will be top centered, (assuming y axis is increasing downwards) * @param vertexStride, number of floats to add from one vertex to the next. Usually 3 to allow XYZ storage, * increase if padding (eg for UV) is needed. * @return array containing 4 vertices for a quad with the specified size, the size of the array will be * vertexStride * 4 */ public static float[] buildQuadPositionsIndexed(float width, float height, float z, float anchorX, float anchorY, int vertexStride) { float[] quadPositions = new float[vertexStride * 4]; com.nucleus.geometry.MeshBuilder.setPosition(-anchorX, -anchorY, z, quadPositions, 0); com.nucleus.geometry.MeshBuilder.setPosition(width - anchorX, -anchorY, z, quadPositions, vertexStride); com.nucleus.geometry.MeshBuilder.setPosition(width - anchorX, height - anchorY, z, quadPositions, vertexStride * 2); com.nucleus.geometry.MeshBuilder.setPosition(-anchorX, height - anchorY, z, quadPositions, vertexStride * 3); return quadPositions; } /** * Builds a mesh with a specified number of indexed quads of GL_FLOAT type, the mesh will have an elementbuffer to * index the vertices. * Vertex buffer will have storage for XYZ + UV. * * @param mesh The mesh to build the buffers in, this is the mesh that can be rendered. * @param The program to use when rendering the mesh * @param spriteCount Number of sprites to build, this is NOT the vertex count. * @param quadPositions Array with x,y,z - this is set for each tile. Must contain data for 4 vertices. * @param attribute2Size Size per vertex for attribute buffer 2, this may be 0 * * @throws IllegalArgumentException if type is not GLES20.GL_FLOAT */ public static void buildQuadMeshIndexed(Mesh mesh, ShaderProgram program, int quadCount, float[] quadPositions, int attribute2Size) { int attributeBuffers = 1; if (attribute2Size > 0) { attributeBuffers = 2; } VertexBuffer[] attributes = new VertexBuffer[attributeBuffers]; attributes[BufferIndex.VERTICES.index] = new VertexBuffer(quadCount * INDEXED_QUAD_VERTICES, XYZ_COMPONENTS, XYZ_COMPONENTS, GLES20.GL_FLOAT); if (attributeBuffers > 1) { attributes[1] = new VertexBuffer(quadCount * INDEXED_QUAD_VERTICES, 4, attribute2Size, GLES20.GL_FLOAT); } ElementBuffer indices = new ElementBuffer(Mode.TRIANGLES, QUAD_INDICES * quadCount, Type.SHORT); ElementBuilder.buildQuadBuffer(indices, indices.getCount() / QUAD_INDICES, 0); float[] vertices = new float[quadCount * INDEXED_QUAD_VERTICES * XYZ_COMPONENTS]; int destPos = 0; for (int i = 0; i < quadCount; i++) { System.arraycopy(quadPositions, 0, vertices, destPos, quadPositions.length); destPos += quadPositions.length; } attributes[BufferIndex.VERTICES.index].setPosition(vertices, 0, 0, quadCount * INDEXED_QUAD_VERTICES); Material material = new Material(program); mesh.setupIndexed(indices, attributes, material, null); } /** * Used by tiled objects to set the UV position to 1 or 0 so it can be multiplied by a fraction size to get * correct UV for a specific frame. * This method is chosen to move as much processing as possible to the GPU - the UV of each sprite could be * calculated at runtime but that would give a higher CPU impact when a large number of sprites are animated. * * @param attributeData Array with attribute data where UV is stored. * @param offset Offset into attribute array * @param uIndex Index to U in attribute data * @param vIndex Index to V in attribute data * @param stride Added to get to next vertex. */ public static void prepareTiledUV(float[] attributeData, int offset, int uIndex, int vIndex, int stride) { int index = offset; attributeData[index + uIndex] = 0; attributeData[index + vIndex] = 0; index += stride; attributeData[index + uIndex] = 1; attributeData[index + vIndex] = 0; index += stride; attributeData[index + uIndex] = 1; attributeData[index + vIndex] = 1; index += stride; attributeData[index + uIndex] = 0; attributeData[index + vIndex] = 1; } }
graphics-by-opengl-j2se/src/main/java/com/nucleus/geometry/MeshBuilder.java
package com.nucleus.geometry; import java.nio.ByteBuffer; import com.nucleus.geometry.ElementBuffer.Mode; import com.nucleus.geometry.ElementBuffer.Type; import com.nucleus.opengl.GLESWrapper.GLES20; import com.nucleus.shader.ShaderProgram; /** * Utility class to help build different type of Meshes. * * @author Richard Sahlin * */ public class MeshBuilder { /** * Number of vertices for an indexed quad */ public final static int INDEXED_QUAD_VERTICES = 4; /** * Number of components for X,Y,Z */ public final static int XYZ_COMPONENTS = 3; /** * Number of indexes for a quad drawn using drawElements (3 * 2) */ public final static int QUAD_INDICES = 6; /** * Sets 3 component position in the destination array. * This method is not speed efficient, only use when very few positions shall be set. * * @param x * @param y * @param z * @param dest position will be set here, must contain at least pos + 3 values. * @param pos The index where data is written. */ public static void setPosition(float x, float y, float z, float[] dest, int pos) { dest[pos++] = x; dest[pos++] = y; dest[pos++] = z; } /** * Sets 3 component position in the destination buffer. * This method is not speed efficient, only use when very few positions shall be set. * * @param x * @param y * @param z * @param buffer */ public static void setPosition(float x, float y, float z, ByteBuffer buffer) { buffer.putFloat(x); buffer.putFloat(y); buffer.putFloat(z); } /** * Builds a buffer containing the 4 vertices for XYZ components, to be indexed when drawing, ie drawn using * drawElements(). * The vertices will be centered using anchorX and anchorY, a value of 0 will be left/top aligned. * A value of 1/width will be centered horizontally. * * @param width * @param height * @param z The Z position * @param anchorX X axis anchor offet, 0 will be left centered (assuming x axis is increasing to the right) * @param anchorY Y axis anchor offet, 0 will be top centered, (assuming y axis is increasing downwards) * @param vertexStride, number of floats to add from one vertex to the next. Usually 3 to allow XYZ storage, * increase if padding (eg for UV) is needed. * @return array containing 4 vertices for a quad with the specified size, the size of the array will be * vertexStride * 4 */ public static float[] buildQuadPositionsIndexed(float width, float height, float z, float anchorX, float anchorY, int vertexStride) { float[] quadPositions = new float[vertexStride * 4]; com.nucleus.geometry.MeshBuilder.setPosition(-anchorX, -anchorY, z, quadPositions, 0); com.nucleus.geometry.MeshBuilder.setPosition(width - anchorX, -anchorY, z, quadPositions, vertexStride); com.nucleus.geometry.MeshBuilder.setPosition(width - anchorX, height - anchorY, z, quadPositions, vertexStride * 2); com.nucleus.geometry.MeshBuilder.setPosition(-anchorX, height - anchorY, z, quadPositions, vertexStride * 3); return quadPositions; } /** * Builds a mesh with a specified number of indexed quads of GL_FLOAT type, the mesh will have an elementbuffer to * index the vertices. * Vertex buffer will have storage for XYZ + UV. * * @param mesh The mesh to build the buffers in, this is the mesh that can be rendered. * @param The program to use when rendering the mesh * @param spriteCount Number of sprites to build, this is NOT the vertex count. * @param quadPositions Array with x,y,z - this is set for each tile. Must contain data for 4 vertices. * @param attribute2Size Size per vertex for attribute buffer 2, this may be 0 * * @throws IllegalArgumentException if type is not GLES20.GL_FLOAT */ public static void buildQuadMeshIndexed(Mesh mesh, ShaderProgram program, int quadCount, float[] quadPositions, int attribute2Size) { int attributeBuffers = 1; if (attribute2Size > 0) { attributeBuffers = 2; } VertexBuffer[] attributes = new VertexBuffer[attributeBuffers]; attributes[0] = new VertexBuffer(quadCount * INDEXED_QUAD_VERTICES, XYZ_COMPONENTS, XYZ_COMPONENTS, GLES20.GL_FLOAT); if (attributeBuffers > 1) { attributes[1] = new VertexBuffer(quadCount * INDEXED_QUAD_VERTICES, 4, attribute2Size, GLES20.GL_FLOAT); } ElementBuffer indices = new ElementBuffer(Mode.TRIANGLES, QUAD_INDICES * quadCount, Type.SHORT); ElementBuilder.buildQuadBuffer(indices, indices.getCount() / QUAD_INDICES, 0); float[] vertices = new float[quadCount * INDEXED_QUAD_VERTICES * XYZ_COMPONENTS]; int destPos = 0; for (int i = 0; i < quadCount; i++) { System.arraycopy(quadPositions, 0, vertices, destPos, quadPositions.length); destPos += quadPositions.length; } attributes[0].setPosition(vertices, 0, 0, quadCount * INDEXED_QUAD_VERTICES); Material material = new Material(program); mesh.setupIndexed(indices, attributes, material, null); } /** * Used by tiled objects to set the UV position to 1 or 0 so it can be multiplied by a fraction size to get * correct UV for a specific frame. * This method is chosen to move as much processing as possible to the GPU - the UV of each sprite could be * calculated at runtime but that would give a higher CPU impact when a large number of sprites are animated. * * @param attributeData Array with attribute data where UV is stored. * @param offset Offset into attribute array * @param uIndex Index to U in attribute data * @param vIndex Index to V in attribute data * @param stride Added to get to next vertex. */ public static void prepareTiledUV(float[] attributeData, int offset, int uIndex, int vIndex, int stride) { int index = offset; attributeData[index + uIndex] = 0; attributeData[index + vIndex] = 0; index += stride; attributeData[index + uIndex] = 1; attributeData[index + vIndex] = 0; index += stride; attributeData[index + uIndex] = 1; attributeData[index + vIndex] = 1; index += stride; attributeData[index + uIndex] = 0; attributeData[index + vIndex] = 1; } }
Use enum to index vertice/attribute array
graphics-by-opengl-j2se/src/main/java/com/nucleus/geometry/MeshBuilder.java
Use enum to index vertice/attribute array
Java
apache-2.0
97127c3cb05ce4f2f69fee337b4561d7902c1bed
0
emre-aydin/hazelcast,emre-aydin/hazelcast,dsukhoroslov/hazelcast,mdogan/hazelcast,mesutcelik/hazelcast,tkountis/hazelcast,tufangorel/hazelcast,dsukhoroslov/hazelcast,mdogan/hazelcast,tufangorel/hazelcast,emre-aydin/hazelcast,mesutcelik/hazelcast,tkountis/hazelcast,tufangorel/hazelcast,Donnerbart/hazelcast,Donnerbart/hazelcast,tkountis/hazelcast,mesutcelik/hazelcast,mdogan/hazelcast,Donnerbart/hazelcast
/* * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.map.impl.eviction; import com.hazelcast.config.MapConfig; import com.hazelcast.config.MaxSizeConfig; import com.hazelcast.internal.nearcache.NearCache; import com.hazelcast.logging.ILogger; import com.hazelcast.map.impl.MapContainer; import com.hazelcast.map.impl.MapServiceContext; import com.hazelcast.map.impl.PartitionContainer; import com.hazelcast.map.impl.nearcache.MapNearCacheManager; import com.hazelcast.map.impl.recordstore.RecordStore; import com.hazelcast.monitor.NearCacheStats; import com.hazelcast.nio.Address; import com.hazelcast.spi.NodeEngine; import com.hazelcast.spi.partition.IPartition; import com.hazelcast.spi.partition.IPartitionService; import com.hazelcast.util.MemoryInfoAccessor; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import static com.hazelcast.cluster.memberselector.MemberSelectors.DATA_MEMBER_SELECTOR; import static com.hazelcast.memory.MemorySize.toPrettyString; import static com.hazelcast.memory.MemoryUnit.MEGABYTES; import static com.hazelcast.util.Preconditions.checkNotNull; import static java.lang.String.format; /** * Checks whether a specific threshold is exceeded or not * according to configured {@link com.hazelcast.config.MaxSizeConfig.MaxSizePolicy} * to start eviction process. * * @see EvictorImpl#evictionChecker */ public class EvictionChecker { private static final int MIN_SANE_PER_PARTITION_SIZE = 2; protected static final double ONE_HUNDRED_PERCENT = 100D; protected final ILogger logger; protected final MapServiceContext mapServiceContext; protected final MemoryInfoAccessor memoryInfoAccessor; protected final AtomicBoolean misconfiguredPerNodeMaxSizeWarningLogged; public EvictionChecker(MemoryInfoAccessor givenMemoryInfoAccessor, MapServiceContext mapServiceContext) { checkNotNull(givenMemoryInfoAccessor, "givenMemoryInfoAccessor cannot be null"); checkNotNull(mapServiceContext, "mapServiceContext cannot be null"); this.logger = mapServiceContext.getNodeEngine().getLogger(getClass()); this.mapServiceContext = mapServiceContext; this.memoryInfoAccessor = givenMemoryInfoAccessor; if (logger.isFinestEnabled()) { logger.finest("Used memoryInfoAccessor=" + this.memoryInfoAccessor.getClass().getCanonicalName()); } this.misconfiguredPerNodeMaxSizeWarningLogged = new AtomicBoolean(); } public boolean checkEvictable(RecordStore recordStore) { if (recordStore.size() == 0) { return false; } String mapName = recordStore.getName(); MapContainer mapContainer = recordStore.getMapContainer(); MaxSizeConfig maxSizeConfig = mapContainer.getMapConfig().getMaxSizeConfig(); MaxSizeConfig.MaxSizePolicy maxSizePolicy = maxSizeConfig.getMaxSizePolicy(); switch (maxSizePolicy) { case PER_NODE: return checkPerNodeEviction(recordStore); case PER_PARTITION: int partitionId = recordStore.getPartitionId(); return checkPerPartitionEviction(mapName, maxSizeConfig, partitionId); case USED_HEAP_PERCENTAGE: return checkHeapPercentageEviction(mapName, maxSizeConfig); case USED_HEAP_SIZE: return checkHeapSizeEviction(mapName, maxSizeConfig); case FREE_HEAP_PERCENTAGE: return checkFreeHeapPercentageEviction(maxSizeConfig); case FREE_HEAP_SIZE: return checkFreeHeapSizeEviction(maxSizeConfig); default: throw new IllegalArgumentException("Not an appropriate max size policy [" + maxSizePolicy + ']'); } } protected boolean checkPerNodeEviction(RecordStore recordStore) { double maxExpectedRecordStoreSize = calculatePerNodeMaxRecordStoreSize(recordStore); return recordStore.size() > maxExpectedRecordStoreSize; } /** * Calculates and returns the expected maximum size of an evicted record-store * when {@link com.hazelcast.config.MaxSizeConfig.MaxSizePolicy#PER_NODE PER_NODE} max-size-policy is used. */ public double calculatePerNodeMaxRecordStoreSize(RecordStore recordStore) { MapConfig mapConfig = recordStore.getMapContainer().getMapConfig(); MaxSizeConfig maxSizeConfig = mapConfig.getMaxSizeConfig(); NodeEngine nodeEngine = mapServiceContext.getNodeEngine(); int configuredMaxSize = maxSizeConfig.getSize(); int memberCount = nodeEngine.getClusterService().getSize(DATA_MEMBER_SELECTOR); int partitionCount = nodeEngine.getPartitionService().getPartitionCount(); double perNodeMaxRecordStoreSize = (1D * configuredMaxSize * memberCount / partitionCount); if(perNodeMaxRecordStoreSize < 1) { perNodeMaxRecordStoreSize = MIN_SANE_PER_PARTITION_SIZE; if(misconfiguredPerNodeMaxSizeWarningLogged.compareAndSet(false, true)) { int minMaxSize = (int) Math.ceil((1D * partitionCount / memberCount)); int newSize = MIN_SANE_PER_PARTITION_SIZE * partitionCount / memberCount; logger.warning(format("The max size configuration for map \"%s\" does not allow any data in the map. " + "Given the current cluster size of %d members with %d partitions, max size should be at " + "least %d. Map size is forced set to %d for backward compatibility", mapConfig.getName(), memberCount, partitionCount, minMaxSize, newSize)); } } return perNodeMaxRecordStoreSize; } protected boolean checkPerPartitionEviction(String mapName, MaxSizeConfig maxSizeConfig, int partitionId) { final double maxSize = maxSizeConfig.getSize(); final PartitionContainer container = mapServiceContext.getPartitionContainer(partitionId); if (container == null) { return false; } final int size = getRecordStoreSize(mapName, container); return size > maxSize; } protected boolean checkHeapSizeEviction(String mapName, MaxSizeConfig maxSizeConfig) { long usedHeapBytes = getUsedHeapInBytes(mapName); if (usedHeapBytes == -1L) { return false; } int maxUsableHeapMegaBytes = maxSizeConfig.getSize(); return MEGABYTES.toBytes(maxUsableHeapMegaBytes) < usedHeapBytes; } protected boolean checkFreeHeapSizeEviction(MaxSizeConfig maxSizeConfig) { long currentFreeHeapBytes = getAvailableMemory(); int minFreeHeapMegaBytes = maxSizeConfig.getSize(); return MEGABYTES.toBytes(minFreeHeapMegaBytes) > currentFreeHeapBytes; } protected boolean checkHeapPercentageEviction(String mapName, MaxSizeConfig maxSizeConfig) { long usedHeapBytes = getUsedHeapInBytes(mapName); if (usedHeapBytes == -1L) { return false; } double maxOccupiedHeapPercentage = maxSizeConfig.getSize(); long maxMemory = getMaxMemory(); if (maxMemory <= 0) { return true; } return maxOccupiedHeapPercentage < (ONE_HUNDRED_PERCENT * usedHeapBytes / maxMemory); } protected boolean checkFreeHeapPercentageEviction(MaxSizeConfig maxSizeConfig) { long totalMemory = getTotalMemory(); long freeMemory = getFreeMemory(); long maxMemory = getMaxMemory(); long availableMemory = freeMemory + (maxMemory - totalMemory); boolean evictable; double actualFreePercentage = 0; double configuredFreePercentage = 0; if (totalMemory <= 0 || freeMemory <= 0 || maxMemory <= 0 || availableMemory <= 0) { evictable = true; } else { actualFreePercentage = ONE_HUNDRED_PERCENT * availableMemory / maxMemory; configuredFreePercentage = maxSizeConfig.getSize(); evictable = configuredFreePercentage > actualFreePercentage; } if (evictable && logger.isFinestEnabled()) { logger.finest(format("runtime.max=%s, runtime.used=%s, configuredFree%%=%.2f, actualFree%%=%.2f", toPrettyString(maxMemory), toPrettyString(totalMemory - freeMemory), configuredFreePercentage, actualFreePercentage)); } return evictable; } protected long getTotalMemory() { return memoryInfoAccessor.getTotalMemory(); } protected long getFreeMemory() { return memoryInfoAccessor.getFreeMemory(); } protected long getMaxMemory() { return memoryInfoAccessor.getMaxMemory(); } protected long getAvailableMemory() { final long totalMemory = getTotalMemory(); final long freeMemory = getFreeMemory(); final long maxMemory = getMaxMemory(); return freeMemory + (maxMemory - totalMemory); } protected long getUsedHeapInBytes(String mapName) { long heapCost = 0L; final List<Integer> partitionIds = findPartitionIds(); for (int partitionId : partitionIds) { final PartitionContainer container = mapServiceContext.getPartitionContainer(partitionId); if (container == null) { continue; } heapCost += getRecordStoreHeapCost(mapName, container); } MapContainer mapContainer = mapServiceContext.getMapContainer(mapName); if (!mapContainer.getMapConfig().isNearCacheEnabled()) { return heapCost; } MapNearCacheManager mapNearCacheManager = mapServiceContext.getMapNearCacheManager(); NearCache nearCache = mapNearCacheManager.getNearCache(mapName); NearCacheStats nearCacheStats = nearCache.getNearCacheStats(); heapCost += nearCacheStats.getOwnedEntryMemoryCost(); return heapCost; } protected int getRecordStoreSize(String mapName, PartitionContainer partitionContainer) { final RecordStore existingRecordStore = partitionContainer.getExistingRecordStore(mapName); if (existingRecordStore == null) { return 0; } return existingRecordStore.size(); } protected long getRecordStoreHeapCost(String mapName, PartitionContainer partitionContainer) { final RecordStore existingRecordStore = partitionContainer.getExistingRecordStore(mapName); if (existingRecordStore == null) { return 0L; } return existingRecordStore.getOwnedEntryCost(); } protected List<Integer> findPartitionIds() { final NodeEngine nodeEngine = mapServiceContext.getNodeEngine(); final IPartitionService partitionService = nodeEngine.getPartitionService(); final int partitionCount = partitionService.getPartitionCount(); List<Integer> partitionIds = null; for (int partitionId = 0; partitionId < partitionCount; partitionId++) { if (isOwnerOrBackup(partitionId)) { if (partitionIds == null) { partitionIds = new ArrayList<Integer>(); } partitionIds.add(partitionId); } } return partitionIds == null ? Collections.<Integer>emptyList() : partitionIds; } protected boolean isOwnerOrBackup(int partitionId) { final NodeEngine nodeEngine = mapServiceContext.getNodeEngine(); final IPartitionService partitionService = nodeEngine.getPartitionService(); final IPartition partition = partitionService.getPartition(partitionId, false); final Address thisAddress = nodeEngine.getThisAddress(); return partition.isOwnerOrBackup(thisAddress); } }
hazelcast/src/main/java/com/hazelcast/map/impl/eviction/EvictionChecker.java
/* * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.map.impl.eviction; import com.hazelcast.config.MapConfig; import com.hazelcast.config.MaxSizeConfig; import com.hazelcast.internal.nearcache.NearCache; import com.hazelcast.logging.ILogger; import com.hazelcast.map.impl.MapContainer; import com.hazelcast.map.impl.MapServiceContext; import com.hazelcast.map.impl.PartitionContainer; import com.hazelcast.map.impl.nearcache.MapNearCacheManager; import com.hazelcast.map.impl.recordstore.RecordStore; import com.hazelcast.monitor.NearCacheStats; import com.hazelcast.nio.Address; import com.hazelcast.spi.NodeEngine; import com.hazelcast.spi.partition.IPartition; import com.hazelcast.spi.partition.IPartitionService; import com.hazelcast.util.MemoryInfoAccessor; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import static com.hazelcast.cluster.memberselector.MemberSelectors.DATA_MEMBER_SELECTOR; import static com.hazelcast.memory.MemorySize.toPrettyString; import static com.hazelcast.memory.MemoryUnit.MEGABYTES; import static com.hazelcast.util.Preconditions.checkNotNull; import static java.lang.String.format; /** * Checks whether a specific threshold is exceeded or not * according to configured {@link com.hazelcast.config.MaxSizeConfig.MaxSizePolicy} * to start eviction process. * * @see EvictorImpl#evictionChecker */ public class EvictionChecker { protected static final double ONE_HUNDRED_PERCENT = 100D; protected final ILogger logger; protected final MapServiceContext mapServiceContext; protected final MemoryInfoAccessor memoryInfoAccessor; protected final AtomicBoolean misconfiguredPerNodeMaxSizeWarningLogged; public EvictionChecker(MemoryInfoAccessor givenMemoryInfoAccessor, MapServiceContext mapServiceContext) { checkNotNull(givenMemoryInfoAccessor, "givenMemoryInfoAccessor cannot be null"); checkNotNull(mapServiceContext, "mapServiceContext cannot be null"); this.logger = mapServiceContext.getNodeEngine().getLogger(getClass()); this.mapServiceContext = mapServiceContext; this.memoryInfoAccessor = givenMemoryInfoAccessor; if (logger.isFinestEnabled()) { logger.finest("Used memoryInfoAccessor=" + this.memoryInfoAccessor.getClass().getCanonicalName()); } this.misconfiguredPerNodeMaxSizeWarningLogged = new AtomicBoolean(); } public boolean checkEvictable(RecordStore recordStore) { if (recordStore.size() == 0) { return false; } String mapName = recordStore.getName(); MapContainer mapContainer = recordStore.getMapContainer(); MaxSizeConfig maxSizeConfig = mapContainer.getMapConfig().getMaxSizeConfig(); MaxSizeConfig.MaxSizePolicy maxSizePolicy = maxSizeConfig.getMaxSizePolicy(); switch (maxSizePolicy) { case PER_NODE: return checkPerNodeEviction(recordStore); case PER_PARTITION: int partitionId = recordStore.getPartitionId(); return checkPerPartitionEviction(mapName, maxSizeConfig, partitionId); case USED_HEAP_PERCENTAGE: return checkHeapPercentageEviction(mapName, maxSizeConfig); case USED_HEAP_SIZE: return checkHeapSizeEviction(mapName, maxSizeConfig); case FREE_HEAP_PERCENTAGE: return checkFreeHeapPercentageEviction(maxSizeConfig); case FREE_HEAP_SIZE: return checkFreeHeapSizeEviction(maxSizeConfig); default: throw new IllegalArgumentException("Not an appropriate max size policy [" + maxSizePolicy + ']'); } } protected boolean checkPerNodeEviction(RecordStore recordStore) { double maxExpectedRecordStoreSize = calculatePerNodeMaxRecordStoreSize(recordStore); return recordStore.size() > maxExpectedRecordStoreSize; } /** * Calculates and returns the expected maximum size of an evicted record-store * when {@link com.hazelcast.config.MaxSizeConfig.MaxSizePolicy#PER_NODE PER_NODE} max-size-policy is used. */ public double calculatePerNodeMaxRecordStoreSize(RecordStore recordStore) { MapConfig mapConfig = recordStore.getMapContainer().getMapConfig(); MaxSizeConfig maxSizeConfig = mapConfig.getMaxSizeConfig(); NodeEngine nodeEngine = mapServiceContext.getNodeEngine(); int configuredMaxSize = maxSizeConfig.getSize(); int memberCount = nodeEngine.getClusterService().getSize(DATA_MEMBER_SELECTOR); int partitionCount = nodeEngine.getPartitionService().getPartitionCount(); final double perNodeMaxRecordStoreSize = (1D * configuredMaxSize * memberCount / partitionCount); if (perNodeMaxRecordStoreSize < 1 && misconfiguredPerNodeMaxSizeWarningLogged.compareAndSet(false, true)) { int minMaxSize = (int) Math.ceil((1D * partitionCount / memberCount)); logger.warning(format("The max size configuration for map \"%s\" does not allow any data in the map. " + "Given the current cluster size of %d members with %d partitions, max size should be at " + "least %d.", mapConfig.getName(), memberCount, partitionCount, minMaxSize)); } return perNodeMaxRecordStoreSize; } protected boolean checkPerPartitionEviction(String mapName, MaxSizeConfig maxSizeConfig, int partitionId) { final double maxSize = maxSizeConfig.getSize(); final PartitionContainer container = mapServiceContext.getPartitionContainer(partitionId); if (container == null) { return false; } final int size = getRecordStoreSize(mapName, container); return size > maxSize; } protected boolean checkHeapSizeEviction(String mapName, MaxSizeConfig maxSizeConfig) { long usedHeapBytes = getUsedHeapInBytes(mapName); if (usedHeapBytes == -1L) { return false; } int maxUsableHeapMegaBytes = maxSizeConfig.getSize(); return MEGABYTES.toBytes(maxUsableHeapMegaBytes) < usedHeapBytes; } protected boolean checkFreeHeapSizeEviction(MaxSizeConfig maxSizeConfig) { long currentFreeHeapBytes = getAvailableMemory(); int minFreeHeapMegaBytes = maxSizeConfig.getSize(); return MEGABYTES.toBytes(minFreeHeapMegaBytes) > currentFreeHeapBytes; } protected boolean checkHeapPercentageEviction(String mapName, MaxSizeConfig maxSizeConfig) { long usedHeapBytes = getUsedHeapInBytes(mapName); if (usedHeapBytes == -1L) { return false; } double maxOccupiedHeapPercentage = maxSizeConfig.getSize(); long maxMemory = getMaxMemory(); if (maxMemory <= 0) { return true; } return maxOccupiedHeapPercentage < (ONE_HUNDRED_PERCENT * usedHeapBytes / maxMemory); } protected boolean checkFreeHeapPercentageEviction(MaxSizeConfig maxSizeConfig) { long totalMemory = getTotalMemory(); long freeMemory = getFreeMemory(); long maxMemory = getMaxMemory(); long availableMemory = freeMemory + (maxMemory - totalMemory); boolean evictable; double actualFreePercentage = 0; double configuredFreePercentage = 0; if (totalMemory <= 0 || freeMemory <= 0 || maxMemory <= 0 || availableMemory <= 0) { evictable = true; } else { actualFreePercentage = ONE_HUNDRED_PERCENT * availableMemory / maxMemory; configuredFreePercentage = maxSizeConfig.getSize(); evictable = configuredFreePercentage > actualFreePercentage; } if (evictable && logger.isFinestEnabled()) { logger.finest(format("runtime.max=%s, runtime.used=%s, configuredFree%%=%.2f, actualFree%%=%.2f", toPrettyString(maxMemory), toPrettyString(totalMemory - freeMemory), configuredFreePercentage, actualFreePercentage)); } return evictable; } protected long getTotalMemory() { return memoryInfoAccessor.getTotalMemory(); } protected long getFreeMemory() { return memoryInfoAccessor.getFreeMemory(); } protected long getMaxMemory() { return memoryInfoAccessor.getMaxMemory(); } protected long getAvailableMemory() { final long totalMemory = getTotalMemory(); final long freeMemory = getFreeMemory(); final long maxMemory = getMaxMemory(); return freeMemory + (maxMemory - totalMemory); } protected long getUsedHeapInBytes(String mapName) { long heapCost = 0L; final List<Integer> partitionIds = findPartitionIds(); for (int partitionId : partitionIds) { final PartitionContainer container = mapServiceContext.getPartitionContainer(partitionId); if (container == null) { continue; } heapCost += getRecordStoreHeapCost(mapName, container); } MapContainer mapContainer = mapServiceContext.getMapContainer(mapName); if (!mapContainer.getMapConfig().isNearCacheEnabled()) { return heapCost; } MapNearCacheManager mapNearCacheManager = mapServiceContext.getMapNearCacheManager(); NearCache nearCache = mapNearCacheManager.getNearCache(mapName); NearCacheStats nearCacheStats = nearCache.getNearCacheStats(); heapCost += nearCacheStats.getOwnedEntryMemoryCost(); return heapCost; } protected int getRecordStoreSize(String mapName, PartitionContainer partitionContainer) { final RecordStore existingRecordStore = partitionContainer.getExistingRecordStore(mapName); if (existingRecordStore == null) { return 0; } return existingRecordStore.size(); } protected long getRecordStoreHeapCost(String mapName, PartitionContainer partitionContainer) { final RecordStore existingRecordStore = partitionContainer.getExistingRecordStore(mapName); if (existingRecordStore == null) { return 0L; } return existingRecordStore.getOwnedEntryCost(); } protected List<Integer> findPartitionIds() { final NodeEngine nodeEngine = mapServiceContext.getNodeEngine(); final IPartitionService partitionService = nodeEngine.getPartitionService(); final int partitionCount = partitionService.getPartitionCount(); List<Integer> partitionIds = null; for (int partitionId = 0; partitionId < partitionCount; partitionId++) { if (isOwnerOrBackup(partitionId)) { if (partitionIds == null) { partitionIds = new ArrayList<Integer>(); } partitionIds.add(partitionId); } } return partitionIds == null ? Collections.<Integer>emptyList() : partitionIds; } protected boolean isOwnerOrBackup(int partitionId) { final NodeEngine nodeEngine = mapServiceContext.getNodeEngine(); final IPartitionService partitionService = nodeEngine.getPartitionService(); final IPartition partition = partitionService.getPartition(partitionId, false); final Address thisAddress = nodeEngine.getThisAddress(); return partition.isOwnerOrBackup(thisAddress); } }
Fixed backward compatibility issue for PER_NODE capacity calculation algorithm
hazelcast/src/main/java/com/hazelcast/map/impl/eviction/EvictionChecker.java
Fixed backward compatibility issue for PER_NODE capacity calculation algorithm
Java
apache-2.0
52ac158c7888f0462778d73e52a353d258b5ed91
0
Frostman/webjavin,Frostman/webjavin,Frostman/webjavin
/****************************************************************************** * WebJavin - Java Web Framework. * * * * Copyright (c) 2011 - Sergey "Frosman" Lukjanov, [email protected] * * * * 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 ru.frostman.web.dispatch; import com.google.common.collect.Lists; import org.apache.commons.io.IOUtils; import ru.frostman.web.Javin; import ru.frostman.web.config.JavinConfig; import ru.frostman.web.config.StaticResource; import ru.frostman.web.controller.Controllers; import ru.frostman.web.thr.JavinRuntimeException; import ru.frostman.web.thr.NotFoundException; import ru.frostman.web.util.HttpMethod; import javax.activation.MimetypesFileTypeMap; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.List; import java.util.Map; /** * @author slukjanov aka Frostman */ public class Dispatcher { private static final MimetypesFileTypeMap MIME_MAP = new MimetypesFileTypeMap(); static { MIME_MAP.addMimeTypes("application/javascript js"); MIME_MAP.addMimeTypes("text/css css"); MIME_MAP.addMimeTypes("image/png png"); } private final List<ActionDefinition> actions; public Dispatcher(List<ActionDefinition> actions) { this.actions = Lists.newLinkedList(actions); } public void dispatch(String requestUrl, HttpMethod requestMethod, HttpServletRequest request , HttpServletResponse response) { if (JavinConfig.get().getContext().equals(requestUrl)) { requestUrl += "/"; } if (dispatchStatic(requestUrl, requestMethod, request, response)) { return; } ActionInvoker invoker = null; if (invoker == null) { for (ActionDefinition definition : actions) { if (definition.matches(requestUrl, requestMethod)) { invoker = definition.initInvoker(request, response); break; } } } if (invoker == null) { sendNotFound(request, response); } else { try { invoker.invoke(); } catch (NotFoundException e) { sendNotFound(request, response); } } } private boolean dispatchStatic(String url, HttpMethod requestMethod, HttpServletRequest request, HttpServletResponse response) { //todo think about this if (url.contains("..")) { return false; } if (requestMethod.equals(HttpMethod.GET)) //todo impl caching, think about regexp in statics //todo compile expressions on AppClasses#update for (Map.Entry<String, StaticResource> entry : JavinConfig.get().getStatics().entrySet()) { String fullUrl = Controllers.url(entry.getKey()); if (url.startsWith(fullUrl)) { String resource = Javin.getApplicationPath() + entry.getValue().getTarget() + "/" + url.substring(fullUrl.length() - 1); try { File resourceFile = new File(resource); FileInputStream resourceStream = new FileInputStream(resourceFile); String contentType = MIME_MAP.getContentType(resourceFile); response.setContentType(contentType); response.setCharacterEncoding(null); //todo think about setting encoding for text IOUtils.copy(resourceStream, response.getOutputStream()); } catch (IOException e) { //todo think about this // no operations continue; } return true; } } return false; } private void sendNotFound(HttpServletRequest request, HttpServletResponse response) { try { response.sendError(HttpServletResponse.SC_NOT_FOUND, request.getRequestURI()); } catch (IOException e) { throw new JavinRuntimeException("Exception while sending 404:Not found", e); } } }
webjavin-core/src/main/java/ru/frostman/web/dispatch/Dispatcher.java
/****************************************************************************** * WebJavin - Java Web Framework. * * * * Copyright (c) 2011 - Sergey "Frosman" Lukjanov, [email protected] * * * * 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 ru.frostman.web.dispatch; import com.google.common.collect.Lists; import org.apache.commons.io.IOUtils; import ru.frostman.web.Javin; import ru.frostman.web.config.JavinConfig; import ru.frostman.web.config.StaticResource; import ru.frostman.web.controller.Controllers; import ru.frostman.web.thr.JavinRuntimeException; import ru.frostman.web.thr.NotFoundException; import ru.frostman.web.util.HttpMethod; import javax.activation.MimetypesFileTypeMap; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.List; import java.util.Map; /** * @author slukjanov aka Frostman */ public class Dispatcher { private static final MimetypesFileTypeMap MIME_MAP = new MimetypesFileTypeMap(); static { MIME_MAP.addMimeTypes("application/javascript js"); MIME_MAP.addMimeTypes("text/css css"); MIME_MAP.addMimeTypes("image/png png"); } private final List<ActionDefinition> actions; public Dispatcher(List<ActionDefinition> actions) { this.actions = Lists.newLinkedList(actions); } public void dispatch(String requestUrl, HttpMethod requestMethod, HttpServletRequest request , HttpServletResponse response) { if (JavinConfig.get().getContext().equals(requestUrl)) { requestUrl += "/"; } if (dispatchStatic(requestUrl, requestMethod, request, response)) { return; } ActionInvoker invoker = null; if (invoker == null) { for (ActionDefinition definition : actions) { if (definition.matches(requestUrl, requestMethod)) { invoker = definition.initInvoker(request, response); break; } } } if (invoker == null) { sendNotFound(request, response); } else { try { invoker.invoke(); } catch (NotFoundException e) { sendNotFound(request, response); } } } private boolean dispatchStatic(String url, HttpMethod requestMethod, HttpServletRequest request, HttpServletResponse response) { //todo think about this if (url.contains("..")) { return false; } if (requestMethod.equals(HttpMethod.GET)) //todo impl caching, think about regexp in statics //todo compile expressions on AppClasses#update for (Map.Entry<String, StaticResource> entry : JavinConfig.get().getStatics().entrySet()) { String fullUrl = Controllers.url(entry.getKey()); if (url.startsWith(fullUrl)) { String resource = Javin.getApplicationPath() + entry.getValue().getTarget() + "/" + url.substring(fullUrl.length() - 1); try { File resourceFile = new File(resource); FileInputStream resourceStream = new FileInputStream(resourceFile); String contentType = MIME_MAP.getContentType(resourceFile); response.setContentType(contentType); IOUtils.copy(resourceStream, response.getWriter()); } catch (IOException e) { throw new JavinRuntimeException("Exception while streaming resource: " + resource, e); } return true; } } return false; } private void sendNotFound(HttpServletRequest request, HttpServletResponse response) { try { response.sendError(HttpServletResponse.SC_NOT_FOUND, request.getRequestURI()); } catch (IOException e) { throw new JavinRuntimeException("Exception while sending 404:Not found", e); } } }
Static files serving updated.
webjavin-core/src/main/java/ru/frostman/web/dispatch/Dispatcher.java
Static files serving updated.
Java
apache-2.0
6aefe7399b57969cb7685972dbd774656cb1f4a0
0
HaStr/kieker,HaStr/kieker,HaStr/kieker,kieker-monitoring/kieker,HaStr/kieker,leadwire-apm/leadwire-javaagent,kieker-monitoring/kieker,kieker-monitoring/kieker,kieker-monitoring/kieker,leadwire-apm/leadwire-javaagent,kieker-monitoring/kieker,HaStr/kieker
/*************************************************************************** * Copyright 2014 Kieker Project (http://kieker-monitoring.net) * * 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 kieker.monitoring.writer.explorviz; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; import java.util.concurrent.BlockingQueue; import kieker.common.configuration.Configuration; import kieker.common.logging.Log; import kieker.common.logging.LogFactory; import kieker.common.record.IMonitoringRecord; import kieker.common.record.flow.IObjectRecord; import kieker.common.record.flow.trace.operation.AfterOperationEvent; import kieker.common.record.flow.trace.operation.AfterOperationFailedEvent; import kieker.common.record.flow.trace.operation.BeforeOperationEvent; import kieker.common.record.misc.RegistryRecord; import kieker.monitoring.core.controller.IMonitoringController; import kieker.monitoring.writer.AbstractAsyncThread; import kieker.monitoring.writer.AbstractAsyncWriter; /** * * @author Florian Fittkau, Jan Waller * * @since 1.9 */ public class ExplorVizExportWriter extends AbstractAsyncWriter { private static final String PREFIX = ExplorVizExportWriter.class.getName() + "."; public static final String CONFIG_HOSTNAME = PREFIX + "hostname"; // NOCS (afterPREFIX) public static final String CONFIG_PORT = PREFIX + "port"; // NOCS (afterPREFIX) public static final String CONFIG_BUFFERSIZE = PREFIX + "bufferSize"; // NOCS (afterPREFIX) public static final String CONFIG_FLUSH = PREFIX + "flush"; // NOCS (afterPREFIX) private final String hostname; private final int port; private final int bufferSize; private final boolean flush; public ExplorVizExportWriter(final Configuration configuration) { super(configuration); this.hostname = configuration.getStringProperty(CONFIG_HOSTNAME); this.port = configuration.getIntProperty(CONFIG_PORT); // should be check for buffers too small for a single record? this.bufferSize = configuration.getIntProperty(CONFIG_BUFFERSIZE); this.flush = configuration.getBooleanProperty(CONFIG_FLUSH); } @Override protected void init() throws Exception { this.addWorker(new ExplorVizExportWriterThread(this.monitoringController, this.blockingQueue, this.hostname, this.port, this.bufferSize, this.flush)); } } /** * * @author Florian Fittkau, Jan Waller * * @since 1.9 */ final class ExplorVizExportWriterThread extends AbstractAsyncThread { private static final Log LOG = LogFactory.getLog(ExplorVizExportWriterThread.class); private static final byte HOST_APPLICATION_META_DATA_CLAZZ_ID = 0; private static final byte BEFORE_OPERATION_CLAZZ_ID = 1; private static final byte AFTER_FAILED_OPERATION_CLAZZ_ID = 2; private static final byte AFTER_OPERATION_CLAZZ_ID = 3; private static final byte STRING_REGISTRY_CLAZZ_ID = 4; private final SocketChannel socketChannel; private final ByteBuffer byteBuffer; private final boolean flush; public ExplorVizExportWriterThread(final IMonitoringController monitoringController, final BlockingQueue<IMonitoringRecord> writeQueue, final String hostname, final int port, final int bufferSize, final boolean flush) throws IOException { super(monitoringController, writeQueue); this.byteBuffer = ByteBuffer.allocateDirect(bufferSize); this.socketChannel = SocketChannel.open(new InetSocketAddress(hostname, port)); this.flush = flush; this.byteBuffer.put(HOST_APPLICATION_META_DATA_CLAZZ_ID); final String systemName = "Default System"; final int systemId = this.monitoringController.getUniqueIdForString(systemName); this.byteBuffer.putInt(systemId); final String ip = InetAddress.getLocalHost().getHostAddress(); final int ipId = this.monitoringController.getUniqueIdForString(ip); this.byteBuffer.putInt(ipId); final String localHostname = monitoringController.getHostname(); // is called to early in the initialization, so no record is created final int localHostnameId = this.monitoringController.getUniqueIdForString(localHostname); this.byteBuffer.putInt(localHostnameId); final String applicatioName = monitoringController.getName(); // is called to early in the initialization, so no record is created final int applicationId = this.monitoringController.getUniqueIdForString(applicatioName); this.byteBuffer.putInt(applicationId); this.putRegistryRecordIntoBuffer(new RegistryRecord(systemId, systemName)); this.putRegistryRecordIntoBuffer(new RegistryRecord(ipId, ip)); this.putRegistryRecordIntoBuffer(new RegistryRecord(localHostnameId, localHostname)); this.putRegistryRecordIntoBuffer(new RegistryRecord(applicationId, applicatioName)); this.send(); } @Override protected void consume(final IMonitoringRecord monitoringRecord) throws Exception { // sizes from ExplorViz not Kieker! int recordSize = 0; if (monitoringRecord instanceof BeforeOperationEvent) { recordSize = 37; } else if (monitoringRecord instanceof AfterOperationFailedEvent) { recordSize = 25; } else if (monitoringRecord instanceof AfterOperationEvent) { recordSize = 21; } else if (monitoringRecord instanceof RegistryRecord) { final RegistryRecord registryRecord = (RegistryRecord) monitoringRecord; recordSize = 9 + registryRecord.getStrBytes().length; } final ByteBuffer buffer = this.byteBuffer; if (recordSize > buffer.remaining()) { this.send(); } this.convertKiekerToExplorViz(buffer, monitoringRecord); if (this.flush) { this.send(); } } private void convertKiekerToExplorViz(final ByteBuffer buffer, final IMonitoringRecord kiekerRecord) { if (kiekerRecord instanceof BeforeOperationEvent) { final BeforeOperationEvent kiekerBefore = (BeforeOperationEvent) kiekerRecord; buffer.put(BEFORE_OPERATION_CLAZZ_ID); buffer.putLong(kiekerBefore.getTimestamp()); buffer.putLong(kiekerBefore.getTraceId()); buffer.putInt(kiekerBefore.getOrderIndex()); if (kiekerRecord instanceof IObjectRecord) { final IObjectRecord iObjectRecord = (IObjectRecord) kiekerRecord; buffer.putInt(iObjectRecord.getObjectId()); } else { buffer.putInt(0); } buffer.putInt(this.monitoringController.getUniqueIdForString(kiekerBefore.getOperationSignature())); buffer.putInt(this.monitoringController.getUniqueIdForString(kiekerBefore.getClassSignature())); // if (kiekerRecord instanceof IInterfaceRecord) { // final IInterfaceRecord iInterfaceRecord = (IInterfaceRecord) kiekerRecord; // buffer.putInt(this.monitoringController.getUniqueIdForString(iInterfaceRecord.getInterface())); // } else { buffer.putInt(this.monitoringController.getUniqueIdForString("")); // } } else if (kiekerRecord instanceof AfterOperationFailedEvent) { final AfterOperationFailedEvent kiekerAfterFailed = (AfterOperationFailedEvent) kiekerRecord; buffer.put(AFTER_FAILED_OPERATION_CLAZZ_ID); buffer.putLong(kiekerAfterFailed.getTimestamp()); buffer.putLong(kiekerAfterFailed.getTraceId()); buffer.putInt(kiekerAfterFailed.getOrderIndex()); buffer.putInt(this.monitoringController.getUniqueIdForString(kiekerAfterFailed.getCause())); } else if (kiekerRecord instanceof AfterOperationEvent) { final AfterOperationEvent kiekerAfter = (AfterOperationEvent) kiekerRecord; buffer.put(AFTER_OPERATION_CLAZZ_ID); buffer.putLong(kiekerAfter.getTimestamp()); buffer.putLong(kiekerAfter.getTraceId()); buffer.putInt(kiekerAfter.getOrderIndex()); } else if (kiekerRecord instanceof RegistryRecord) { final RegistryRecord registryRecord = (RegistryRecord) kiekerRecord; this.putRegistryRecordIntoBuffer(registryRecord); } } private void putRegistryRecordIntoBuffer(final RegistryRecord registryRecord) { final byte[] valueAsBytes = registryRecord.getStrBytes(); this.byteBuffer.put(STRING_REGISTRY_CLAZZ_ID); this.byteBuffer.putInt(registryRecord.getId()); this.byteBuffer.putInt(valueAsBytes.length); this.byteBuffer.put(valueAsBytes); } private void send() throws IOException { this.byteBuffer.flip(); while (this.byteBuffer.hasRemaining()) { this.socketChannel.write(this.byteBuffer); } this.byteBuffer.clear(); } @Override protected void cleanup() { try { this.send(); this.socketChannel.close(); } catch (final IOException ex) { LOG.error("Error closing connection", ex); } } }
src/monitoring/kieker/monitoring/writer/explorviz/ExplorVizExportWriter.java
/*************************************************************************** * Copyright 2014 Kieker Project (http://kieker-monitoring.net) * * 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 kieker.monitoring.writer.explorviz; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; import java.util.concurrent.BlockingQueue; import kieker.common.configuration.Configuration; import kieker.common.logging.Log; import kieker.common.logging.LogFactory; import kieker.common.record.IMonitoringRecord; import kieker.common.record.flow.IObjectRecord; import kieker.common.record.flow.trace.operation.AfterOperationEvent; import kieker.common.record.flow.trace.operation.AfterOperationFailedEvent; import kieker.common.record.flow.trace.operation.BeforeOperationEvent; import kieker.common.record.misc.RegistryRecord; import kieker.monitoring.core.controller.IMonitoringController; import kieker.monitoring.writer.AbstractAsyncThread; import kieker.monitoring.writer.AbstractAsyncWriter; /** * * @author Florian Fittkau, Jan Waller * * @since 1.9 */ public class ExplorVizExportWriter extends AbstractAsyncWriter { private static final String PREFIX = ExplorVizExportWriter.class.getName() + "."; public static final String CONFIG_HOSTNAME = PREFIX + "hostname"; // NOCS (afterPREFIX) public static final String CONFIG_PORT = PREFIX + "port"; // NOCS (afterPREFIX) public static final String CONFIG_BUFFERSIZE = PREFIX + "bufferSize"; // NOCS (afterPREFIX) public static final String CONFIG_FLUSH = PREFIX + "flush"; // NOCS (afterPREFIX) private final String hostname; private final int port; private final int bufferSize; private final boolean flush; public ExplorVizExportWriter(final Configuration configuration) { super(configuration); this.hostname = configuration.getStringProperty(CONFIG_HOSTNAME); this.port = configuration.getIntProperty(CONFIG_PORT); // should be check for buffers too small for a single record? this.bufferSize = configuration.getIntProperty(CONFIG_BUFFERSIZE); this.flush = configuration.getBooleanProperty(CONFIG_FLUSH); } @Override protected void init() throws Exception { this.addWorker(new ExplorVizExportWriterThread(this.monitoringController, this.blockingQueue, this.hostname, this.port, this.bufferSize, this.flush)); } } /** * * @author Florian Fittkau, Jan Waller * * @since 1.9 */ final class ExplorVizExportWriterThread extends AbstractAsyncThread { private static final Log LOG = LogFactory.getLog(ExplorVizExportWriterThread.class); private static final byte HOST_APPLICATION_META_DATA_CLAZZ_ID = 0; private static final byte BEFORE_OPERATION_CLAZZ_ID = 1; private static final byte AFTER_FAILED_OPERATION_CLAZZ_ID = 2; private static final byte AFTER_OPERATION_CLAZZ_ID = 3; private static final byte STRING_REGISTRY_CLAZZ_ID = 4; private final SocketChannel socketChannel; private final ByteBuffer byteBuffer; private final boolean flush; public ExplorVizExportWriterThread(final IMonitoringController monitoringController, final BlockingQueue<IMonitoringRecord> writeQueue, final String hostname, final int port, final int bufferSize, final boolean flush) throws IOException { super(monitoringController, writeQueue); this.byteBuffer = ByteBuffer.allocateDirect(bufferSize); this.socketChannel = SocketChannel.open(new InetSocketAddress(hostname, port)); this.flush = flush; this.byteBuffer.put(HOST_APPLICATION_META_DATA_CLAZZ_ID); final String systemName = "Default System"; final int systemId = this.monitoringController.getUniqueIdForString(systemName); this.byteBuffer.putInt(systemId); final String ip = InetAddress.getLocalHost().getHostAddress(); final int ipId = this.monitoringController.getUniqueIdForString(ip); this.byteBuffer.putInt(ipId); final String localHostname = monitoringController.getHostname(); // is called to early in the initialization, so no record is created final int localHostnameId = this.monitoringController.getUniqueIdForString(localHostname); this.byteBuffer.putInt(localHostnameId); final String applicatioName = monitoringController.getName(); // is called to early in the initialization, so no record is created final int applicationId = this.monitoringController.getUniqueIdForString(applicatioName); this.byteBuffer.putInt(applicationId); this.putRegistryRecordIntoBuffer(new RegistryRecord(systemId, systemName)); this.putRegistryRecordIntoBuffer(new RegistryRecord(ipId, ip)); this.putRegistryRecordIntoBuffer(new RegistryRecord(localHostnameId, localHostname)); this.putRegistryRecordIntoBuffer(new RegistryRecord(applicationId, applicatioName)); this.send(); } @Override protected void consume(final IMonitoringRecord monitoringRecord) throws Exception { // sizes from ExplorViz not Kieker! int recordSize = 0; if (monitoringRecord instanceof BeforeOperationEvent) { recordSize = 29; } else if (monitoringRecord instanceof AfterOperationFailedEvent) { recordSize = 25; } else if (monitoringRecord instanceof AfterOperationEvent) { recordSize = 21; } else if (monitoringRecord instanceof RegistryRecord) { final RegistryRecord registryRecord = (RegistryRecord) monitoringRecord; recordSize = 9 + registryRecord.getStrBytes().length; } final ByteBuffer buffer = this.byteBuffer; if (recordSize > buffer.remaining()) { this.send(); } this.convertKiekerToExplorViz(buffer, monitoringRecord); if (this.flush) { this.send(); } } private void convertKiekerToExplorViz(final ByteBuffer buffer, final IMonitoringRecord kiekerRecord) { if (kiekerRecord instanceof BeforeOperationEvent) { final BeforeOperationEvent kiekerBefore = (BeforeOperationEvent) kiekerRecord; buffer.put(BEFORE_OPERATION_CLAZZ_ID); buffer.putLong(kiekerBefore.getTimestamp()); buffer.putLong(kiekerBefore.getTraceId()); buffer.putInt(kiekerBefore.getOrderIndex()); if (kiekerRecord instanceof IObjectRecord) { final IObjectRecord iObjectRecord = (IObjectRecord) kiekerRecord; buffer.putInt(iObjectRecord.getObjectId()); } else { buffer.putInt(0); } buffer.putInt(this.monitoringController.getUniqueIdForString(kiekerBefore.getOperationSignature())); } else if (kiekerRecord instanceof AfterOperationFailedEvent) { final AfterOperationFailedEvent kiekerAfterFailed = (AfterOperationFailedEvent) kiekerRecord; buffer.put(AFTER_FAILED_OPERATION_CLAZZ_ID); buffer.putLong(kiekerAfterFailed.getTimestamp()); buffer.putLong(kiekerAfterFailed.getTraceId()); buffer.putInt(kiekerAfterFailed.getOrderIndex()); buffer.putInt(this.monitoringController.getUniqueIdForString(kiekerAfterFailed.getCause())); } else if (kiekerRecord instanceof AfterOperationEvent) { final AfterOperationEvent kiekerAfter = (AfterOperationEvent) kiekerRecord; buffer.put(AFTER_OPERATION_CLAZZ_ID); buffer.putLong(kiekerAfter.getTimestamp()); buffer.putLong(kiekerAfter.getTraceId()); buffer.putInt(kiekerAfter.getOrderIndex()); } else if (kiekerRecord instanceof RegistryRecord) { final RegistryRecord registryRecord = (RegistryRecord) kiekerRecord; this.putRegistryRecordIntoBuffer(registryRecord); } } private void putRegistryRecordIntoBuffer(final RegistryRecord registryRecord) { final byte[] valueAsBytes = registryRecord.getStrBytes(); this.byteBuffer.put(STRING_REGISTRY_CLAZZ_ID); this.byteBuffer.putInt(registryRecord.getId()); this.byteBuffer.putInt(valueAsBytes.length); this.byteBuffer.put(valueAsBytes); } private void send() throws IOException { this.byteBuffer.flip(); while (this.byteBuffer.hasRemaining()) { this.socketChannel.write(this.byteBuffer); } this.byteBuffer.clear(); } @Override protected void cleanup() { try { this.send(); this.socketChannel.close(); } catch (final IOException ex) { LOG.error("Error closing connection", ex); } } }
Fixed ExplorViz Writer
src/monitoring/kieker/monitoring/writer/explorviz/ExplorVizExportWriter.java
Fixed ExplorViz Writer