diff --git a/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/common/ASTProcessor.java b/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/common/ASTProcessor.java index 67c34774ff1..088c734ceea 100644 --- a/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/common/ASTProcessor.java +++ b/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/common/ASTProcessor.java @@ -13,8 +13,10 @@ *******************************************************************************/ package org.eclipse.jdt.internal.common; +import java.util.AbstractMap; import java.util.LinkedHashMap; import java.util.LinkedList; +import java.util.Map; import java.util.Set; import java.util.function.BiPredicate; import java.util.function.Function; @@ -1197,7 +1199,9 @@ public ASTProcessor callMethodInvocationVisitor( */ public ASTProcessor callMethodInvocationVisitor(String methodname, BiPredicate bs) { - nodetypelist.put(VisitorEnum.MethodInvocation, new NodeHolder(bs, null, methodname)); + nodetypelist.put(VisitorEnum.MethodInvocation, new NodeHolder(bs, null, Map.ofEntries( + new AbstractMap.SimpleEntry<>(HelperVisitor.METHODNAME, methodname) + ))); return this; } @@ -1209,7 +1213,9 @@ public ASTProcessor callMethodInvocationVisitor(String methodname, */ public ASTProcessor callMethodInvocationVisitor(String methodname, BiPredicate bs, Function navigate) { - nodetypelist.put(VisitorEnum.MethodInvocation, new NodeHolder(bs, navigate, methodname)); + nodetypelist.put(VisitorEnum.MethodInvocation, new NodeHolder(bs, navigate, Map.ofEntries( + new AbstractMap.SimpleEntry<>(HelperVisitor.METHODNAME, methodname) + ))); return this; } diff --git a/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/common/HelperVisitor.java b/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/common/HelperVisitor.java index b854f5fdb4f..71812422892 100644 --- a/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/common/HelperVisitor.java +++ b/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/common/HelperVisitor.java @@ -13,6 +13,7 @@ *******************************************************************************/ package org.eclipse.jdt.internal.common; +import java.util.AbstractMap; import java.util.EnumSet; import java.util.HashMap; import java.util.LinkedHashMap; @@ -34,6 +35,9 @@ */ public class HelperVisitor,V,T> { + public static final String TYPEOF = "typeof"; //$NON-NLS-1$ + public static final String METHODNAME = "methodname"; //$NON-NLS-1$ + public static final String PARAMTYPENAMES = "paramtypenames"; //$NON-NLS-1$ ASTVisitor astvisitor; public E dataholder; @@ -370,6 +374,20 @@ public BiPredicate addClassInstanceCreation(BiPredicate addClassInstanceCreation(Class typeof, BiPredicate bs) { + Map map = Map.ofEntries( + new AbstractMap.SimpleEntry<>(TYPEOF, typeof) + ); + predicatedata.put(VisitorEnum.ClassInstanceCreation, map); + return predicatemap.put(VisitorEnum.ClassInstanceCreation, bs); + } + /** * Add BiPredicate to use for CompilationUnit visit * @@ -719,7 +737,27 @@ public BiPredicate addMethodInvocation(BiPredicate addMethodInvocation(String methodname, BiPredicate bs) { - this.predicatedata.put(VisitorEnum.MethodInvocation, methodname); + this.predicatedata.put(VisitorEnum.MethodInvocation, Map.ofEntries( + new AbstractMap.SimpleEntry<>(METHODNAME, methodname) + )); + return predicatemap.put(VisitorEnum.MethodInvocation, bs); + } + + /** + * Add BiPredicate to use for MethodInvocation visit where class and method name is specified + * + * @param typeof class whose method is called + * @param methodname name of the method that is called + * @param bs BiPredicate that can be assigned a lambda expression + * @return previous BiPredicate registered + */ + public BiPredicate addMethodInvocation(Class typeof, String methodname, + BiPredicate bs) { + Map map = Map.ofEntries( + new AbstractMap.SimpleEntry<>(METHODNAME, methodname), + new AbstractMap.SimpleEntry<>(TYPEOF, typeof) + ); + predicatedata.put(VisitorEnum.MethodInvocation, map); return predicatemap.put(VisitorEnum.MethodInvocation, bs); } @@ -1484,7 +1522,9 @@ public BiConsumer addMethodInvocation(BiConsumer addMethodInvocation(String methodname, BiConsumer bc) { - this.consumerdata.put(VisitorEnum.MethodInvocation, methodname); + this.consumerdata.put(VisitorEnum.MethodInvocation, Map.ofEntries( + new AbstractMap.SimpleEntry<>(METHODNAME, methodname) + )); return consumermap.put(VisitorEnum.MethodInvocation, bc); } @@ -2180,24 +2220,51 @@ public void addMethodDeclaration(BiPredicate bs, BiConsume /** * - * @param bs - BiPredicate that can be assigned a lambda expression + * @param methodname Only visit MethodInvocation with this name + * @param bs - BiPredicate that is visited when a MethodInvocation is found + * @param bc - BiConsumer that is visited at the end after a MethodInvocation has been found */ public void addMethodInvocation(String methodname, BiPredicate bs, BiConsumer bc) { - this.predicatedata.put(VisitorEnum.MethodInvocation, methodname); + predicatedata.put(VisitorEnum.MethodInvocation, Map.ofEntries( + new AbstractMap.SimpleEntry<>(METHODNAME, methodname) + )); + predicatemap.put(VisitorEnum.MethodInvocation, bs); + consumerdata.put(VisitorEnum.MethodInvocation, Map.ofEntries( + new AbstractMap.SimpleEntry<>(METHODNAME, methodname) + )); + consumermap.put(VisitorEnum.MethodInvocation, bc); + } + + /** + * @param typeof Only visit MethodInvocation calling a method of this class + * @param methodname Only visit MethodInvocation with this name + * @param bs - BiPredicate that is visited when a MethodInvocation is found + * @param bc - BiConsumer that is visited at the end after a MethodInvocation has been found + */ + public void addMethodInvocation(Class typeof, String methodname, BiPredicate bs, + BiConsumer bc) { + Map map = Map.ofEntries( + new AbstractMap.SimpleEntry<>(METHODNAME, methodname), + new AbstractMap.SimpleEntry<>(TYPEOF, typeof) + ); + predicatedata.put(VisitorEnum.MethodInvocation, map); predicatemap.put(VisitorEnum.MethodInvocation, bs); + consumerdata.put(VisitorEnum.MethodInvocation, map); consumermap.put(VisitorEnum.MethodInvocation, bc); } /** * * @param bs - BiPredicate that can be assigned a lambda expression + * @param bc - BiConsumer that is visited at the end after a MethodInvocation has been found */ public void addMethodInvocation(BiPredicate bs, BiConsumer bc) { predicatemap.put(VisitorEnum.MethodInvocation, bs); consumermap.put(VisitorEnum.MethodInvocation, bc); } + /** * * @param bs - BiPredicate that can be assigned a lambda expression @@ -3428,6 +3495,13 @@ public static void callMethodInvocationVisitor(String methodname, ASTNode hv.build(node); } + public static void callMethodInvocationVisitor(Class methodof, String methodname, ASTNode node, ReferenceHolder dataholder, Set nodesprocessed, + BiPredicate> bs) { + + HelperVisitor,V,T> hv= new HelperVisitor<>(nodesprocessed, dataholder); + hv.addMethodInvocation(methodof, methodname, bs); + hv.build(node); + } /** * * @param nodesprocessed - set of nodes processed @@ -5627,6 +5701,13 @@ public static void callClassInstanceCreationVisitor(ASTNode node, Referen hv.build(node); } + public static void callClassInstanceCreationVisitor(Class class1, ASTNode node, ReferenceHolder dataholder, Set nodesprocessed, + BiPredicate> bs) { + + HelperVisitor,V,T> hv= new HelperVisitor<>(nodesprocessed, dataholder); + hv.addClassInstanceCreation(class1, bs); + hv.build(node); + } /** * * @param nodesprocessed - set of nodes processed diff --git a/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/common/LambdaASTVisitor.java b/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/common/LambdaASTVisitor.java index 40b61b29179..9d6a8ba2862 100644 --- a/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/common/LambdaASTVisitor.java +++ b/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/common/LambdaASTVisitor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2021, 2022 Carsten Hammer. + * Copyright (c) 2021 Carsten Hammer. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -9,15 +9,18 @@ * SPDX-License-Identifier: EPL-2.0 * * Contributors: - * Carsten Hammer - initial API and implementation + * Carsten Hammer *******************************************************************************/ package org.eclipse.jdt.internal.common; +import java.util.Map; import java.util.function.BiConsumer; import java.util.function.BiPredicate; import org.eclipse.jdt.core.dom.*; +import org.eclipse.jdt.internal.corext.dom.ASTNodes; + /** * * @author chammer @@ -25,9 +28,13 @@ * @param - type that extends HelpVisitorProvider that provides {@code HelperVisitor} * @param - type that HelperVisitor uses as map key type * @param - type that HelperVisitor uses as map value type + * @since 1.15 */ -@SuppressWarnings("unchecked") +@SuppressWarnings({ "unchecked" }) public class LambdaASTVisitor, V, T> extends ASTVisitor { + /** + * + */ private final HelperVisitor helperVisitor; /** @@ -190,6 +197,16 @@ public boolean visit(CharacterLiteral node) { @Override public boolean visit(ClassInstanceCreation node) { if (this.helperVisitor.predicatemap.containsKey(VisitorEnum.ClassInstanceCreation)) { + Map map=(Map) this.helperVisitor.getSupplierData().get(VisitorEnum.ClassInstanceCreation); + if(map != null) { + Class typeof=(Class) map.get(HelperVisitor.TYPEOF); + if(typeof!=null) { + ITypeBinding binding= node.resolveTypeBinding(); + if (!typeof.getSimpleName().equals(binding.getName())) { + return true; + } + } + } return ((BiPredicate) (this.helperVisitor.predicatemap .get(VisitorEnum.ClassInstanceCreation))).test(node, this.helperVisitor.dataholder); } @@ -496,9 +513,25 @@ public boolean visit(MethodDeclaration node) { @Override public boolean visit(MethodInvocation node) { if (this.helperVisitor.predicatemap.containsKey(VisitorEnum.MethodInvocation)) { - String data=(String) this.helperVisitor.getSupplierData().get(VisitorEnum.MethodInvocation); - if (data!= null && !node.getName().getIdentifier().equals(data)) { - return true; + Map map=(Map) this.helperVisitor.getSupplierData().get(VisitorEnum.MethodInvocation); + if(map != null) { + String data=(String) map.get(HelperVisitor.METHODNAME); + if ((data!= null) && !node.getName().getIdentifier().equals(data)) { + return true; + } + Class typeof=(Class) map.get(HelperVisitor.TYPEOF); + String[] parameterTypesQualifiedNames=(String[]) map.get(HelperVisitor.PARAMTYPENAMES); + + if(typeof!=null) { + if(parameterTypesQualifiedNames==null) { + if (ASTNodes.usesGivenSignature(node, typeof.getCanonicalName(), data)) { + return ((BiPredicate) (this.helperVisitor.predicatemap.get(VisitorEnum.MethodInvocation))).test(node, this.helperVisitor.dataholder); + } + } else + if (ASTNodes.usesGivenSignature(node, typeof.getCanonicalName(), data, parameterTypesQualifiedNames)) { + return ((BiPredicate) (this.helperVisitor.predicatemap.get(VisitorEnum.MethodInvocation))).test(node, this.helperVisitor.dataholder); + } + } } return ((BiPredicate) (this.helperVisitor.predicatemap.get(VisitorEnum.MethodInvocation))).test(node, this.helperVisitor.dataholder); } @@ -949,14 +982,17 @@ public boolean visit(VariableDeclarationExpression node) { @Override public boolean visit(VariableDeclarationStatement node) { if (this.helperVisitor.predicatemap.containsKey(VisitorEnum.VariableDeclarationStatement)) { - Class data=(Class) this.helperVisitor.getSupplierData().get(VisitorEnum.VariableDeclarationStatement); - if (data!= null) { - VariableDeclarationFragment bli = (VariableDeclarationFragment) node.fragments().get(0); - IVariableBinding resolveBinding = bli.resolveBinding(); - if(resolveBinding!=null) { - String qualifiedName = resolveBinding.getType().getErasure().getQualifiedName(); - if (!data.getCanonicalName().equals(qualifiedName)) { - return true; + Map map=(Map)this.helperVisitor.getConsumerData().get(VisitorEnum.VariableDeclarationStatement); + if(map != null) { + Class data=(Class) map.get(HelperVisitor.TYPEOF); + if (data!= null) { + VariableDeclarationFragment bli = (VariableDeclarationFragment) node.fragments().get(0); + IVariableBinding resolveBinding = bli.resolveBinding(); + if(resolveBinding!=null) { + String qualifiedName = resolveBinding.getType().getErasure().getQualifiedName(); + if (!data.getCanonicalName().equals(qualifiedName)) { + return true; + } } } } @@ -1388,9 +1424,18 @@ public void endVisit(MethodDeclaration node) { @Override public void endVisit(MethodInvocation node) { if (this.helperVisitor.consumermap.containsKey(VisitorEnum.MethodInvocation)) { - String data=(String) this.helperVisitor.getConsumerData().get(VisitorEnum.MethodInvocation); - if (data!= null && !node.getName().getIdentifier().equals(data)) { - return; + Map map=(Map) this.helperVisitor.getConsumerData().get(VisitorEnum.MethodInvocation); + if(map != null) { + String data=(String) map.get(HelperVisitor.METHODNAME); + if ((data!= null) && !node.getName().getIdentifier().equals(data)) { + return; + } + Class typeof=(Class) map.get(HelperVisitor.TYPEOF); + if(typeof!=null) { + if (!ASTNodes.usesGivenSignature(node, typeof.getCanonicalName(), data)) { + return; + } + } } ((BiConsumer) (this.helperVisitor.consumermap.get(VisitorEnum.MethodInvocation))).accept(node, this.helperVisitor.dataholder); @@ -1774,14 +1819,17 @@ public void endVisit(VariableDeclarationExpression node) { @Override public void endVisit(VariableDeclarationStatement node) { if (this.helperVisitor.consumermap.containsKey(VisitorEnum.VariableDeclarationStatement)) { - Class data=(Class) this.helperVisitor.getConsumerData().get(VisitorEnum.VariableDeclarationStatement); - if (data!= null) { - VariableDeclarationFragment bli = (VariableDeclarationFragment) node.fragments().get(0); - IVariableBinding resolveBinding = bli.resolveBinding(); - if(resolveBinding!=null) { - String qualifiedName = resolveBinding.getType().getErasure().getQualifiedName(); - if (!data.getCanonicalName().equals(qualifiedName)) { - return; + Map map=(Map)this.helperVisitor.getConsumerData().get(VisitorEnum.VariableDeclarationStatement); + if(map != null) { + Class data=(Class) map.get(HelperVisitor.TYPEOF); + if (data!= null) { + VariableDeclarationFragment bli = (VariableDeclarationFragment) node.fragments().get(0); + IVariableBinding resolveBinding = bli.resolveBinding(); + if(resolveBinding!=null) { + String qualifiedName = resolveBinding.getType().getErasure().getQualifiedName(); + if (!data.getCanonicalName().equals(qualifiedName)) { + return; + } } } } diff --git a/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/fix/MultiFixMessages.java b/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/fix/MultiFixMessages.java index b105bded44a..e2b45e13ad3 100644 --- a/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/fix/MultiFixMessages.java +++ b/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/fix/MultiFixMessages.java @@ -209,6 +209,8 @@ private MultiFixMessages() { public static String StringConcatToTextBlockCleanUp_description; public static String StringConcatToTextBlockStringBuffer_description; public static String StringBuilderForLocalVarsOnlyCleanUp_description; + public static String ExplicitEncodingCleanUp_description; + public static String ExplicitEncodingCleanUpFix_refactor; static { // initialize resource bundle diff --git a/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/fix/MultiFixMessages.properties b/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/fix/MultiFixMessages.properties index 0342b02609d..a0afb8e83bf 100644 --- a/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/fix/MultiFixMessages.properties +++ b/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/fix/MultiFixMessages.properties @@ -191,3 +191,5 @@ StringBufferToStringBuilderCleanUp_description=Convert StringBuffer to StringBui StringConcatToTextBlockCleanUp_description=Convert String concatenation to Text Block StringConcatToTextBlockStringBuffer_description=Convert String/StringBuffer/StringBuilder concatenation to Text Block StringBuilderForLocalVarsOnlyCleanUp_description=Convert StringBuffer to StringBuilder for local variables +ExplicitEncodingCleanUp_description=Set explicit encoding or default encoding where applicable on methods ''{0}'' using {1} +ExplicitEncodingCleanUpFix_refactor=Use explicit encoding \ No newline at end of file diff --git a/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/fix/UseExplicitEncodingCleanUpCore.java b/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/fix/UseExplicitEncodingCleanUpCore.java new file mode 100644 index 00000000000..9a6d42bdba5 --- /dev/null +++ b/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/fix/UseExplicitEncodingCleanUpCore.java @@ -0,0 +1,127 @@ +/******************************************************************************* + * Copyright (c) 2021 Carsten Hammer. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Carsten Hammer + *******************************************************************************/ +package org.eclipse.jdt.internal.ui.fix; + +import static org.eclipse.jdt.internal.corext.fix.CleanUpConstants.EXPLICITENCODING_AGGREGATE_TO_UTF8; +import static org.eclipse.jdt.internal.corext.fix.CleanUpConstants.EXPLICITENCODING_CLEANUP; +import static org.eclipse.jdt.internal.corext.fix.CleanUpConstants.EXPLICITENCODING_INSERT_UTF8; +import static org.eclipse.jdt.internal.corext.fix.CleanUpConstants.EXPLICITENCODING_KEEP_BEHAVIOR; +import static org.eclipse.jdt.internal.ui.fix.MultiFixMessages.ExplicitEncodingCleanUpFix_refactor; +import static org.eclipse.jdt.internal.ui.fix.MultiFixMessages.ExplicitEncodingCleanUp_description; + +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import org.eclipse.core.runtime.CoreException; + +import org.eclipse.jdt.core.dom.ASTNode; +import org.eclipse.jdt.core.dom.CompilationUnit; + +import org.eclipse.jdt.internal.corext.fix.CompilationUnitRewriteOperationsFixCore; +import org.eclipse.jdt.internal.corext.fix.CompilationUnitRewriteOperationsFixCore.CompilationUnitRewriteOperation; +import org.eclipse.jdt.internal.corext.fix.UseExplicitEncodingFixCore; +import org.eclipse.jdt.internal.corext.fix.helper.ChangeBehavior; +import org.eclipse.jdt.internal.corext.util.Messages; + +import org.eclipse.jdt.ui.cleanup.CleanUpContext; +import org.eclipse.jdt.ui.cleanup.CleanUpRequirements; +import org.eclipse.jdt.ui.cleanup.ICleanUpFix; + +public class UseExplicitEncodingCleanUpCore extends AbstractCleanUp { + public UseExplicitEncodingCleanUpCore(final Map options) { + super(options); + } + public UseExplicitEncodingCleanUpCore() { + } + + @Override + public CleanUpRequirements getRequirements() { + return new CleanUpRequirements(requireAST(), false, false, null); + } + + public boolean requireAST() { + return isEnabled(EXPLICITENCODING_CLEANUP)&& !computeFixSet().isEmpty(); + } + @Override + public ICleanUpFix createFix(final CleanUpContext context) throws CoreException { + CompilationUnit compilationUnit= context.getAST(); + if (compilationUnit == null) { + return null; + } + EnumSet computeFixSet= computeFixSet(); + if(!isEnabled(EXPLICITENCODING_CLEANUP) || computeFixSet.isEmpty()) { + return null; + } + + ChangeBehavior cb= computeRefactorDeepth(); + Set operations= new LinkedHashSet<>(); + Set nodesprocessed= new HashSet<>(); + computeFixSet.forEach(i->i.findOperations(compilationUnit,operations,nodesprocessed,cb)); + if (operations.isEmpty()) { + return null; + } + + CompilationUnitRewriteOperation[] array= operations.toArray(new CompilationUnitRewriteOperationsFixCore.CompilationUnitRewriteOperation[0]); + return new CompilationUnitRewriteOperationsFixCore(ExplicitEncodingCleanUpFix_refactor, + compilationUnit, array); + } + + private ChangeBehavior computeRefactorDeepth() { + ChangeBehavior cb=ChangeBehavior.KEEP_BEHAVIOR; + if(isEnabled(EXPLICITENCODING_KEEP_BEHAVIOR)) { + cb=ChangeBehavior.KEEP_BEHAVIOR; + } + if(isEnabled(EXPLICITENCODING_INSERT_UTF8)) { + cb=ChangeBehavior.ENFORCE_UTF8; + } + if(isEnabled(EXPLICITENCODING_AGGREGATE_TO_UTF8)) { + cb=ChangeBehavior.ENFORCE_UTF8_AGGREGATE; + } + return cb; + } + + @Override + public String[] getStepDescriptions() { + List result= new ArrayList<>(); + if (isEnabled(EXPLICITENCODING_CLEANUP)) { + String with=computeRefactorDeepth().toString(); + result.add(Messages.format(ExplicitEncodingCleanUp_description,new Object[] {String.join(",", computeFixSet().stream().map(UseExplicitEncodingFixCore::toString).collect(Collectors.toList())),with})); //$NON-NLS-1$ + } + return result.toArray(new String[0]); + } + + @Override + public String getPreview() { + StringBuilder sb=new StringBuilder(); + EnumSet computeFixSet= computeFixSet(); + ChangeBehavior cb= computeRefactorDeepth(); + EnumSet.allOf(UseExplicitEncodingFixCore.class).forEach(e->sb.append(e.getPreview(computeFixSet.contains(e),cb))); + return sb.toString(); + } + + private EnumSet computeFixSet() { + EnumSet fixSet= EnumSet.noneOf(UseExplicitEncodingFixCore.class); + + if(isEnabled(EXPLICITENCODING_CLEANUP)) { + fixSet= EnumSet.allOf(UseExplicitEncodingFixCore.class); + } + return fixSet; + } +} diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/CleanUpConstants.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/CleanUpConstants.java index 91d91756c20..2d413344597 100644 --- a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/CleanUpConstants.java +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/CleanUpConstants.java @@ -16,6 +16,7 @@ package org.eclipse.jdt.internal.corext.fix; import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants; +import org.eclipse.jdt.core.manipulation.CleanUpOptionsCore; import org.eclipse.jdt.ui.cleanup.CleanUpOptions; @@ -2347,4 +2348,47 @@ public class CleanUpConstants { * @since 3.3 */ public final static String DEFAULT_SAVE_PARTICIPANT_PROFILE= SAVE_PARTICIPANT_PROFILE; + + /** + * + */ + public static final String EXPLICITENCODING_CLEANUP= "cleanup.explicit_encoding"; //$NON-NLS-1$ + + /** + * Don't change behavior - just replace or insert to make use of platform encoding visible in the code. + *

+ * Possible values: {TRUE, FALSE} + *

+ * + * @see CleanUpOptionsCore#TRUE + * @see CleanUpOptionsCore#FALSE + * + */ + public static final String EXPLICITENCODING_KEEP_BEHAVIOR= "cleanup.explicit_encoding_keep_behavior"; //$NON-NLS-1$ + + /** + * Set all uses of platform encoding explicitly to UTF-8 - This changes behavior of the resulting code! + *

+ * Possible values: {TRUE, FALSE} + *

+ * + * @see CleanUpOptionsCore#TRUE + * @see CleanUpOptionsCore#FALSE + * + */ + public static final String EXPLICITENCODING_INSERT_UTF8= "cleanup.explicit_encoding_insert_utf8"; //$NON-NLS-1$ + + /** + * Set all uses of platform encoding explicitly to UTF-8 - This changes behavior of the resulting code! + * At the same time try to have a single constant per project for this encoding that is referenced whenever + * code is changed to use this charset. That way later it is easy to change the default. + *

+ * Possible values: {TRUE, FALSE} + *

+ * + * @see CleanUpOptionsCore#TRUE + * @see CleanUpOptionsCore#FALSE + * + */ + public static final String EXPLICITENCODING_AGGREGATE_TO_UTF8= "cleanup.explicit_encoding_aggregate_to_utf8"; //$NON-NLS-1$ } diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/LibStandardNames.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/LibStandardNames.java index e44b1db3175..efa01533271 100644 --- a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/LibStandardNames.java +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/LibStandardNames.java @@ -15,8 +15,8 @@ public class LibStandardNames { static final String METHOD_GET_PROPERTY= "getProperty"; //$NON-NLS-1$ - static final String METHOD_DISPLAY_NAME= "displayName"; //$NON-NLS-1$ - static final String METHOD_DEFAULT_CHARSET= "defaultCharset"; //$NON-NLS-1$ + public static final String METHOD_DISPLAY_NAME= "displayName"; //$NON-NLS-1$ + public static final String METHOD_DEFAULT_CHARSET= "defaultCharset"; //$NON-NLS-1$ static final String METHOD_GET_SEPARATOR= "getSeparator"; //$NON-NLS-1$ static final String METHOD_GET_PATH_SEPARATOR= "getPathSeparator"; //$NON-NLS-1$ static final String METHOD_GET_DEFAULT= "getDefault"; //$NON-NLS-1$ @@ -31,6 +31,17 @@ public class LibStandardNames { static final String FIELD_SEPARATOR= "separator"; //$NON-NLS-1$ static final String METHOD_FOREACH= "forEach"; //$NON-NLS-1$ static final String METHOD_VERSION= "version"; //$NON-NLS-1$ - static final String METHOD_TOSTRING= "toString"; //$NON-NLS-1$ static final String METHOD_FEATURE= "feature"; //$NON-NLS-1$ + public static final String METHOD_WARNING= "warning"; //$NON-NLS-1$ + public static final String METHOD_ERROR= "error"; //$NON-NLS-1$ + public static final String METHOD_INFO= "info"; //$NON-NLS-1$ + public static final String METHOD_GET_BYTES= "getBytes"; //$NON-NLS-1$ + public static final String METHOD_STORE_TO_XML= "storeToXML"; //$NON-NLS-1$ + public static final String METHOD_FOR_NAME= "forName"; //$NON-NLS-1$ + public static final String METHOD_NEW_READER= "newReader"; //$NON-NLS-1$ + public static final String METHOD_NEW_WRITER= "newWriter"; //$NON-NLS-1$ + public static final String METHOD_DECODE= "decode"; //$NON-NLS-1$ + public static final String METHOD_ENCODE= "encode"; //$NON-NLS-1$ + public static final String METHOD_TOSTRING= "toString"; //$NON-NLS-1$ + public static final String FIELD_UTF8= "UTF_8"; //$NON-NLS-1$ } diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/UseExplicitEncodingFixCore.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/UseExplicitEncodingFixCore.java new file mode 100644 index 00000000000..626b6780ca6 --- /dev/null +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/UseExplicitEncodingFixCore.java @@ -0,0 +1,128 @@ +/******************************************************************************* + * Copyright (c) 2021 Carsten Hammer. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Carsten Hammer + *******************************************************************************/ +package org.eclipse.jdt.internal.corext.fix; + +import java.util.Set; + +import org.eclipse.core.runtime.CoreException; + +import org.eclipse.text.edits.TextEditGroup; + +import org.eclipse.jdt.core.dom.ASTNode; +import org.eclipse.jdt.core.dom.CompilationUnit; +import org.eclipse.jdt.core.dom.rewrite.TargetSourceRangeComputer; + +import org.eclipse.jdt.internal.common.ReferenceHolder; +import org.eclipse.jdt.internal.corext.dom.ASTNodes; +import org.eclipse.jdt.internal.corext.fix.CompilationUnitRewriteOperationsFixCore.CompilationUnitRewriteOperation; +import org.eclipse.jdt.internal.corext.fix.helper.AbstractExplicitEncoding; +import org.eclipse.jdt.internal.corext.fix.helper.ByteArrayOutputStreamExplicitEncoding; +import org.eclipse.jdt.internal.corext.fix.helper.ChangeBehavior; +import org.eclipse.jdt.internal.corext.fix.helper.ChannelsNewReaderExplicitEncoding; +import org.eclipse.jdt.internal.corext.fix.helper.ChannelsNewWriterExplicitEncoding; +import org.eclipse.jdt.internal.corext.fix.helper.CharsetForNameExplicitEncoding; +import org.eclipse.jdt.internal.corext.fix.helper.FileReaderExplicitEncoding; +import org.eclipse.jdt.internal.corext.fix.helper.FileWriterExplicitEncoding; +import org.eclipse.jdt.internal.corext.fix.helper.FormatterExplicitEncoding; +import org.eclipse.jdt.internal.corext.fix.helper.InputStreamReaderExplicitEncoding; +import org.eclipse.jdt.internal.corext.fix.helper.OutputStreamWriterExplicitEncoding; +import org.eclipse.jdt.internal.corext.fix.helper.PrintStreamExplicitEncoding; +import org.eclipse.jdt.internal.corext.fix.helper.PrintWriterExplicitEncoding; +import org.eclipse.jdt.internal.corext.fix.helper.PropertiesStoreToXMLExplicitEncoding; +import org.eclipse.jdt.internal.corext.fix.helper.ScannerExplicitEncoding; +import org.eclipse.jdt.internal.corext.fix.helper.StringExplicitEncoding; +import org.eclipse.jdt.internal.corext.fix.helper.StringGetBytesExplicitEncoding; +import org.eclipse.jdt.internal.corext.fix.helper.URLDecoderDecodeExplicitEncoding; +import org.eclipse.jdt.internal.corext.fix.helper.URLEncoderEncodeExplicitEncoding; +import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite; +import org.eclipse.jdt.internal.corext.util.Messages; + +import org.eclipse.jdt.internal.ui.fix.MultiFixMessages; + +public enum UseExplicitEncodingFixCore { + + CHARSET(new CharsetForNameExplicitEncoding()), + CHANNELSNEWREADER(new ChannelsNewReaderExplicitEncoding()), + CHANNELSNEWWRITER(new ChannelsNewWriterExplicitEncoding()), + STRING_GETBYTES(new StringGetBytesExplicitEncoding()), + STRING(new StringExplicitEncoding()), + INPUTSTREAMREADER(new InputStreamReaderExplicitEncoding()), + OUTPUTSTREAMWRITER(new OutputStreamWriterExplicitEncoding()), + FILEREADER(new FileReaderExplicitEncoding()), + FILEWRITER(new FileWriterExplicitEncoding()), + PRINTWRITER(new PrintWriterExplicitEncoding()), + PRINTSTREAM(new PrintStreamExplicitEncoding()), + BYTEARRAYOUTPUTSTREAM(new ByteArrayOutputStreamExplicitEncoding()), + FORMATTER(new FormatterExplicitEncoding()), + URLDECODER(new URLDecoderDecodeExplicitEncoding()), + URLENCODER(new URLEncoderEncodeExplicitEncoding()), + SCANNER(new ScannerExplicitEncoding()), + PROPERTIES_STORETOXML(new PropertiesStoreToXMLExplicitEncoding()); + + AbstractExplicitEncoding explicitencoding; + + @SuppressWarnings("unchecked") + UseExplicitEncodingFixCore(AbstractExplicitEncoding explicitencoding) { + this.explicitencoding=(AbstractExplicitEncoding) explicitencoding; + } + + public String getPreview(boolean i, ChangeBehavior cb) { + long countother= explicitencoding.getPreview(!i, cb).lines().count(); + StringBuilder preview= new StringBuilder(explicitencoding.getPreview(i,cb)); + long countnow= preview.toString().lines().count(); + if(countnow operations,final Set nodesprocessed, ChangeBehavior cb) { + explicitencoding.find(this, compilationUnit, operations, nodesprocessed, cb); + } + + public CompilationUnitRewriteOperation rewrite(final ASTNode visited, ChangeBehavior cb, ReferenceHolder data) { + return new CompilationUnitRewriteOperation() { + @Override + public void rewriteAST(final CompilationUnitRewrite cuRewrite, final LinkedProposalModelCore linkedModel) throws CoreException { + TextEditGroup group= createTextEditGroup(Messages.format(MultiFixMessages.ExplicitEncodingCleanUp_description,new Object[] {UseExplicitEncodingFixCore.this.toString(), cb.toString()}), cuRewrite); + cuRewrite.getASTRewrite().setTargetSourceRangeComputer(computer); + explicitencoding.rewrite(UseExplicitEncodingFixCore.this, visited, cuRewrite, group, cb, data); + } + }; + } + + final static TargetSourceRangeComputer computer= new TargetSourceRangeComputer() { + @Override + public SourceRange computeSourceRange(final ASTNode nodeWithComment) { + if (Boolean.TRUE.equals(nodeWithComment.getProperty(ASTNodes.UNTOUCH_COMMENT))) { + return new SourceRange(nodeWithComment.getStartPosition(), nodeWithComment.getLength()); + } + return super.computeSourceRange(nodeWithComment); + } + }; + + @Override + public String toString() { + return explicitencoding.toString(); + } +} diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/AbstractExplicitEncoding.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/AbstractExplicitEncoding.java new file mode 100644 index 00000000000..fad98176878 --- /dev/null +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/AbstractExplicitEncoding.java @@ -0,0 +1,298 @@ +/******************************************************************************* + * Copyright (c) 2021 Carsten Hammer. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Carsten Hammer + *******************************************************************************/ +package org.eclipse.jdt.internal.corext.fix.helper; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.eclipse.text.edits.ReplaceEdit; +import org.eclipse.text.edits.TextEditGroup; + +import org.eclipse.jface.text.BadLocationException; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.JavaModelException; +import org.eclipse.jdt.core.compiler.InvalidInputException; +import org.eclipse.jdt.core.dom.AST; +import org.eclipse.jdt.core.dom.ASTNode; +import org.eclipse.jdt.core.dom.Block; +import org.eclipse.jdt.core.dom.CatchClause; +import org.eclipse.jdt.core.dom.Comment; +import org.eclipse.jdt.core.dom.CompilationUnit; +import org.eclipse.jdt.core.dom.Expression; +import org.eclipse.jdt.core.dom.FieldDeclaration; +import org.eclipse.jdt.core.dom.MethodDeclaration; +import org.eclipse.jdt.core.dom.Name; +import org.eclipse.jdt.core.dom.QualifiedName; +import org.eclipse.jdt.core.dom.SimpleName; +import org.eclipse.jdt.core.dom.SingleVariableDeclaration; +import org.eclipse.jdt.core.dom.StringLiteral; +import org.eclipse.jdt.core.dom.TryStatement; +import org.eclipse.jdt.core.dom.Type; +import org.eclipse.jdt.core.dom.TypeDeclaration; +import org.eclipse.jdt.core.dom.UnionType; +import org.eclipse.jdt.core.dom.VariableDeclarationFragment; +import org.eclipse.jdt.core.dom.VariableDeclarationStatement; +import org.eclipse.jdt.core.dom.rewrite.ASTRewrite; +import org.eclipse.jdt.core.dom.rewrite.ImportRewrite; +import org.eclipse.jdt.core.dom.rewrite.ListRewrite; + +import org.eclipse.jdt.internal.common.ReferenceHolder; +import org.eclipse.jdt.internal.corext.fix.CompilationUnitRewriteOperationsFixCore.CompilationUnitRewriteOperation; +import org.eclipse.jdt.internal.corext.fix.UseExplicitEncodingFixCore; +import org.eclipse.jdt.internal.corext.refactoring.nls.NLSElement; +import org.eclipse.jdt.internal.corext.refactoring.nls.NLSLine; +import org.eclipse.jdt.internal.corext.refactoring.nls.NLSScanner; +import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite; + +/** + * @param Type found in Visitor + */ +public abstract class AbstractExplicitEncoding { + private static final String JAVA_IO_UNSUPPORTED_ENCODING_EXCEPTION= "java.io.UnsupportedEncodingException"; //$NON-NLS-1$ + + private static final String UNSUPPORTED_ENCODING_EXCEPTION= "UnsupportedEncodingException"; //$NON-NLS-1$ + + static Map encodingmap= Map.of( + "UTF-8", "UTF_8", //$NON-NLS-1$ //$NON-NLS-2$ + "UTF-16", "UTF_16", //$NON-NLS-1$ //$NON-NLS-2$ + "UTF-16BE", "UTF_16BE", //$NON-NLS-1$ //$NON-NLS-2$ + "UTF-16LE", "UTF_16LE", //$NON-NLS-1$ //$NON-NLS-2$ + "ISO-8859-1", "ISO_8859_1", //$NON-NLS-1$ //$NON-NLS-2$ + "US-ASCII", "US_ASCII" //$NON-NLS-1$ //$NON-NLS-2$ + ); + + static Set encodings= encodingmap.keySet(); + + static class Nodedata { + public boolean replace; + + public ASTNode visited; + + public String encoding; + + public static Map charsetConstants= new HashMap<>(); + } + + protected static final String ENCODING= "encoding"; //$NON-NLS-1$ + + protected static final String REPLACE= "replace"; //$NON-NLS-1$ + + public abstract void find(UseExplicitEncodingFixCore fixcore, CompilationUnit compilationUnit, Set operations, Set nodesprocessed, ChangeBehavior cb); + + public abstract void rewrite(UseExplicitEncodingFixCore useExplicitEncodingFixCore, T visited, CompilationUnitRewrite cuRewrite, + TextEditGroup group, ChangeBehavior cb, ReferenceHolder data); + + /** + * Adds an import to the class. This method should be used for every class reference added to + * the generated code. + * + * @param typeName a fully qualified name of a type + * @param cuRewrite CompilationUnitRewrite + * @param ast AST + * @return simple name of a class if the import was added and fully qualified name if there was + * a conflict + */ + protected static Name addImport(String typeName, final CompilationUnitRewrite cuRewrite, AST ast) { + String importedName= cuRewrite.getImportRewrite().addImport(typeName); + return ast.newName(importedName); + } + + protected static String findVariableValue(SimpleName variable, ASTNode context) { + ASTNode current= context.getParent(); + while (current != null && !(current instanceof MethodDeclaration) && !(current instanceof TypeDeclaration)) { + current= current.getParent(); + } + + if (current instanceof MethodDeclaration) { + MethodDeclaration method= (MethodDeclaration) current; + List statements= method.getBody().statements(); + + for (Object stmt : statements) { + if (stmt instanceof VariableDeclarationStatement) { + VariableDeclarationStatement varDeclStmt= (VariableDeclarationStatement) stmt; + for (Object frag : varDeclStmt.fragments()) { + VariableDeclarationFragment fragment= (VariableDeclarationFragment) frag; + if (fragment.getName().getIdentifier().equals(variable.getIdentifier())) { + Expression initializer= fragment.getInitializer(); + if (initializer instanceof StringLiteral) { + return ((StringLiteral) initializer).getLiteralValue().toUpperCase(); + } + } + } + } + } + } else if (current instanceof TypeDeclaration) { + TypeDeclaration type= (TypeDeclaration) current; + FieldDeclaration[] fields= type.getFields(); + + for (FieldDeclaration field : fields) { + for (Object frag : field.fragments()) { + VariableDeclarationFragment fragment= (VariableDeclarationFragment) frag; + if (fragment.getName().getIdentifier().equals(variable.getIdentifier())) { + Expression initializer= fragment.getInitializer(); + if (initializer instanceof StringLiteral) { + return ((StringLiteral) initializer).getLiteralValue().toUpperCase(); + } + } + } + } + } + return null; + } + + public abstract String getPreview(boolean afterRefactoring, ChangeBehavior cb); + + protected void removeUnsupportedEncodingException(final ASTNode visited, TextEditGroup group, ASTRewrite rewrite, ImportRewrite importRewriter) { + ASTNode parent= visited.getParent(); + while (parent != null && !(parent instanceof MethodDeclaration) && !(parent instanceof TryStatement)) { + parent= parent.getParent(); + } + + if (parent instanceof MethodDeclaration) { + MethodDeclaration method= (MethodDeclaration) parent; + ListRewrite throwsRewrite= rewrite.getListRewrite(method, MethodDeclaration.THROWN_EXCEPTION_TYPES_PROPERTY); + List thrownExceptions= method.thrownExceptionTypes(); + for (Type exceptionType : thrownExceptions) { + if (exceptionType.toString().equals(UNSUPPORTED_ENCODING_EXCEPTION)) { + throwsRewrite.remove(exceptionType, group); + importRewriter.removeImport(JAVA_IO_UNSUPPORTED_ENCODING_EXCEPTION); + } + } + } else if (parent instanceof TryStatement) { + TryStatement tryStatement= (TryStatement) parent; + + List catchClauses= tryStatement.catchClauses(); + for (CatchClause catchClause : catchClauses) { + SingleVariableDeclaration exception= catchClause.getException(); + Type exceptionType= exception.getType(); + + if (exceptionType instanceof UnionType) { + UnionType unionType= (UnionType) exceptionType; + ListRewrite unionRewrite= rewrite.getListRewrite(unionType, UnionType.TYPES_PROPERTY); + + List types= unionType.types(); + types.stream() + .filter(type -> type.toString().equals(UNSUPPORTED_ENCODING_EXCEPTION)) + .forEach(type -> unionRewrite.remove(type, group)); + + if (types.size() == 1) { + rewrite.replace(unionType, types.get(0), group); + } else if (types.isEmpty()) { + rewrite.remove(catchClause, group); + } + } else if (exceptionType.toString().equals(UNSUPPORTED_ENCODING_EXCEPTION)) { + rewrite.remove(catchClause, group); + importRewriter.removeImport(JAVA_IO_UNSUPPORTED_ENCODING_EXCEPTION); + } + } + + if (tryStatement.catchClauses().isEmpty() && tryStatement.getFinally() == null) { + Block tryBlock= tryStatement.getBody(); + + if (tryStatement.resources().isEmpty() && tryBlock.statements().isEmpty()) { + rewrite.remove(tryStatement, group); + } else if (tryStatement.resources().isEmpty()) { + rewrite.replace(tryStatement, tryBlock, group); + } + } + } + } + + protected void removeNLSComment(CompilationUnitRewrite cuRewrite, ASTNode node, TextEditGroup group) { + CompilationUnit unit= cuRewrite.getRoot(); + ICompilationUnit icu= (ICompilationUnit) cuRewrite.getRoot().getJavaElement(); + + if (icu == null) { + System.err.println("ICompilationUnit is null."); //$NON-NLS-1$ + return; + } + + String source= null; + try { + source= icu.getSource(); + } catch (JavaModelException e) { + e.printStackTrace(); + } + + if (source == null) { + System.err.println("Source code is null."); //$NON-NLS-1$ + return; + } + + int startLine= unit.getLineNumber(node.getStartPosition()); + int endOfLine= unit.getPosition(startLine + 1, 0); + String lineText= source.substring(node.getStartPosition(), endOfLine); + + try { + NLSLine[] lines= NLSScanner.scan(lineText); + + for (NLSLine nlsLine : lines) { + if (nlsLine != null && isConsistent(nlsLine, true)) { + for (NLSElement element : nlsLine.getElements()) { + if (element.hasTag()) { + Comment comment= findCommentNode(unit, element.getTagText()); + if (comment != null) { + // Jetzt entfernen wir den Kommentar als ReplaceEdit. + ReplaceEdit edit= new ReplaceEdit(comment.getStartPosition(), comment.getLength(), ""); //$NON-NLS-1$ + group.addTextEdit(edit); // Die Bearbeitung zur TextEditGroup hinzufügen + System.out.println("Removed NLS comment: " + comment.getStartPosition()); //$NON-NLS-1$ + } + } + } + } + } + } catch (InvalidInputException | BadLocationException e) { + e.printStackTrace(); + } + } + + private boolean isConsistent(NLSLine nlsLine, boolean isTagged) { + NLSElement[] elements= nlsLine.getElements(); + for (NLSElement element : elements) { + if (element.hasTag() != isTagged) { + return false; + } + } + return true; + } + + private Comment findCommentNode(CompilationUnit unit, String commentContent) { + List commentList= unit.getCommentList(); + for (Comment comment : commentList) { + String content= getCommentContent(comment, unit); + if (content != null && content.equals(commentContent)) { + return comment; + } + } + return null; + } + + private String getCommentContent(Comment comment, CompilationUnit unit) { + try { + // Holen des ICompilationUnit-Objekts aus dem CompilationUnit + ICompilationUnit cu= (ICompilationUnit) unit.getJavaElement(); + if (cu != null) { + // Abrufen des Quelltextes des gesamten ICompilationUnit + String source= cu.getSource(); + return source.substring(comment.getStartPosition(), comment.getStartPosition() + comment.getLength()); + } + } catch (JavaModelException e) { + e.printStackTrace(); + } + return null; + } +} diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/ByteArrayOutputStreamExplicitEncoding.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/ByteArrayOutputStreamExplicitEncoding.java new file mode 100644 index 00000000000..281f5e2df48 --- /dev/null +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/ByteArrayOutputStreamExplicitEncoding.java @@ -0,0 +1,173 @@ +/******************************************************************************* + * Copyright (c) 2021 Carsten Hammer. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Carsten Hammer + *******************************************************************************/ +package org.eclipse.jdt.internal.corext.fix.helper; + +import static org.eclipse.jdt.internal.corext.fix.LibStandardNames.METHOD_TOSTRING; + +import java.io.ByteArrayOutputStream; +import java.util.List; +import java.util.Set; + +import org.eclipse.text.edits.TextEditGroup; + +import org.eclipse.jdt.core.dom.AST; +import org.eclipse.jdt.core.dom.ASTNode; +import org.eclipse.jdt.core.dom.CompilationUnit; +import org.eclipse.jdt.core.dom.MethodInvocation; +import org.eclipse.jdt.core.dom.StringLiteral; +import org.eclipse.jdt.core.dom.rewrite.ASTRewrite; +import org.eclipse.jdt.core.dom.rewrite.ImportRewrite; +import org.eclipse.jdt.core.dom.rewrite.ListRewrite; + +import org.eclipse.jdt.internal.common.HelperVisitor; +import org.eclipse.jdt.internal.common.ReferenceHolder; +import org.eclipse.jdt.internal.corext.dom.ASTNodes; +import org.eclipse.jdt.internal.corext.fix.CompilationUnitRewriteOperationsFixCore.CompilationUnitRewriteOperation; +import org.eclipse.jdt.internal.corext.fix.UseExplicitEncodingFixCore; +import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite; +import org.eclipse.jdt.internal.corext.util.JavaModelUtil; + + +/** + * Change from + * + *

+ * ByteArrayOutputStream ba= new ByteArrayOutputStream();
+ *
+ * String result= ba.toString();
+ * 
+ * + *
+ * ByteArrayOutputStream ba= new ByteArrayOutputStream();
+ * try {
+ * 	String result= ba.toString(Charset.defaultCharset().displayName());
+ * } catch (UnsupportedEncodingException e1) {
+ * 	e1.printStackTrace();
+ * }
+ * 
+ * + * since Java 10 + * + *
+ * ByteArrayOutputStream ba= new ByteArrayOutputStream();
+ *
+ * String result= ba.toString(Charset.defaultCharset());
+ * 
+ * + */ +public class ByteArrayOutputStreamExplicitEncoding extends AbstractExplicitEncoding { + + @Override + public void find(UseExplicitEncodingFixCore fixcore, CompilationUnit compilationUnit, Set operations, Set nodesprocessed, ChangeBehavior cb) { + if (!JavaModelUtil.is10OrHigher(compilationUnit.getJavaElement().getJavaProject())) { + /** + * For Java 9 and older just do nothing + */ + return; + } + ReferenceHolder holder= new ReferenceHolder<>(); + HelperVisitor.callMethodInvocationVisitor(ByteArrayOutputStream.class, METHOD_TOSTRING, compilationUnit, holder, nodesprocessed, + (visited, aholder) -> processFoundNode(fixcore, operations, cb, visited, aholder)); + } + + private static boolean processFoundNode(UseExplicitEncodingFixCore fixcore, Set operations, + ChangeBehavior cb, MethodInvocation visited, + ReferenceHolder holder) { + List arguments= visited.arguments(); + if (ASTNodes.usesGivenSignature(visited, ByteArrayOutputStream.class.getCanonicalName(), METHOD_TOSTRING, String.class.getCanonicalName())) { + if (!(arguments.get(0) instanceof StringLiteral)) { + return false; + } + StringLiteral argstring3= (StringLiteral) arguments.get(0); + if (!encodings.contains(argstring3.getLiteralValue())) { + return false; + } + Nodedata nd= new Nodedata(); + nd.encoding= encodingmap.get(argstring3.getLiteralValue()); + nd.replace= true; + nd.visited= argstring3; + holder.put(visited, nd); + operations.add(fixcore.rewrite(visited, cb, holder)); + return false; + } + if (ASTNodes.usesGivenSignature(visited, ByteArrayOutputStream.class.getCanonicalName(), METHOD_TOSTRING)) { + Nodedata nd2= new Nodedata(); + nd2.encoding= null; + nd2.replace= false; + nd2.visited= visited; + holder.put(visited, nd2); + operations.add(fixcore.rewrite(visited, cb, holder)); + return false; + } + return false; + } + + @Override + public void rewrite(UseExplicitEncodingFixCore upp, final MethodInvocation visited, final CompilationUnitRewrite cuRewrite, + TextEditGroup group, ChangeBehavior cb, ReferenceHolder data) { + ASTRewrite rewrite= cuRewrite.getASTRewrite(); + AST ast= cuRewrite.getRoot().getAST(); + ImportRewrite importRewriter= cuRewrite.getImportRewrite(); + Nodedata nodedata= (Nodedata) data.get(visited); + ASTNode callToCharsetDefaultCharset= cb.computeCharsetASTNode(cuRewrite, ast, nodedata.encoding, Nodedata.charsetConstants); + /** + * Add Charset.defaultCharset().displayName() as second (last) parameter of "toString()" + * call Add Charset.defaultCharset() as second (last) parameter + */ + ListRewrite listRewrite= rewrite.getListRewrite(visited, MethodInvocation.ARGUMENTS_PROPERTY); + if (nodedata.replace) { + listRewrite.replace(nodedata.visited, callToCharsetDefaultCharset, group); + } else { + listRewrite.insertLast(callToCharsetDefaultCharset, group); + } + removeUnsupportedEncodingException(visited, group, rewrite, importRewriter); + } + + @Override + public String getPreview(boolean afterRefactoring, ChangeBehavior cb) { + String insert= ""; //$NON-NLS-1$ + switch (cb) { + case KEEP_BEHAVIOR: + insert= "Charset.defaultCharset().displayName()"; //$NON-NLS-1$ + break; + case ENFORCE_UTF8_AGGREGATE: + // insert="charset_constant"; //$NON-NLS-1$ + //$FALL-THROUGH$ + case ENFORCE_UTF8: + insert= "StandardCharsets.UTF_8.displayName()"; //$NON-NLS-1$ + break; + } + if (afterRefactoring) { + return "ByteArrayOutputStream ba=new ByteArrayOutputStream();\n" //$NON-NLS-1$ + + "try {\n" //$NON-NLS-1$ + + " String result=ba.toString(" + insert + ");\n" //$NON-NLS-1$ //$NON-NLS-2$ + + "} catch (UnsupportedEncodingException e1) {\n" //$NON-NLS-1$ + + " e1.printStackTrace();\n" //$NON-NLS-1$ + + "}\n"; //$NON-NLS-1$ + } + return """ + ByteArrayOutputStream ba=new ByteArrayOutputStream(); + try { + String result=ba.toString(); + } catch (UnsupportedEncodingException e1) { + e1.printStackTrace(); + } + """; //$NON-NLS-1$ + } + + @Override + public String toString() { + return "ba.toString()"; //$NON-NLS-1$ + } +} diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/ChangeBehavior.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/ChangeBehavior.java new file mode 100644 index 00000000000..5f265e241ec --- /dev/null +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/ChangeBehavior.java @@ -0,0 +1,226 @@ +/******************************************************************************* + * Copyright (c) 2021 Carsten Hammer. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Carsten Hammer + *******************************************************************************/ +package org.eclipse.jdt.internal.corext.fix.helper; + +import static org.eclipse.jdt.internal.corext.fix.LibStandardNames.METHOD_DEFAULT_CHARSET; +import static org.eclipse.jdt.internal.corext.fix.LibStandardNames.METHOD_DISPLAY_NAME; + +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.Map; + +import org.eclipse.jdt.core.dom.AST; +import org.eclipse.jdt.core.dom.Expression; +import org.eclipse.jdt.core.dom.FieldAccess; +import org.eclipse.jdt.core.dom.FieldDeclaration; +import org.eclipse.jdt.core.dom.MethodInvocation; +import org.eclipse.jdt.core.dom.Modifier; +import org.eclipse.jdt.core.dom.QualifiedName; +import org.eclipse.jdt.core.dom.TypeDeclaration; +import org.eclipse.jdt.core.dom.VariableDeclarationFragment; +import org.eclipse.jdt.core.dom.rewrite.ImportRewrite; + +import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory; +import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite; + +public enum ChangeBehavior { + KEEP_BEHAVIOR() { + @Override + protected Expression computeCharsetASTNode(final CompilationUnitRewrite cuRewrite, AST ast, String charset, Map charsetConstants) { + Expression callToCharsetDefaultCharset= null; + + if (charset != null) { + callToCharsetDefaultCharset= addCharsetUTF8(cuRewrite, ast, charset); + } else { + // needs Java 1.5 + callToCharsetDefaultCharset= addCharsetComputation(cuRewrite, ast); + } + + return callToCharsetDefaultCharset; + } + + @Override + protected String computeCharsetforPreview() { + String insert= "Charset.defaultCharset()"; //$NON-NLS-1$ + return insert; + } + }, + ENFORCE_UTF8() { + @Override + protected Expression computeCharsetASTNode(final CompilationUnitRewrite cuRewrite, AST ast, String charset, Map charsetConstants) { + String charset2= charset == null ? "UTF_8" : charset; //$NON-NLS-1$ + Expression callToCharsetDefaultCharset= addCharsetUTF8(cuRewrite, ast, charset2); + return callToCharsetDefaultCharset; + } + + @Override + protected String computeCharsetforPreview() { + String insert= "StandardCharsets.UTF_8"; //$NON-NLS-1$ + return insert; + } + }, + ENFORCE_UTF8_AGGREGATE() { + @Override + protected Expression computeCharsetASTNode(final CompilationUnitRewrite cuRewrite, AST ast, String charset2, Map charsetConstants) { + String charset= charset2 == null ? "UTF_8" : charset2; //$NON-NLS-1$ + // Generate a valid Java identifier for the charset name (e.g., UTF_8) + String fieldName = charset.toUpperCase().replace('-', '_'); + + // Check if this charset constant is already stored in the map + if (charsetConstants.containsKey(fieldName)) { + return charsetConstants.get(fieldName); + } + + // Add import for StandardCharsets + ImportRewrite importRewrite = cuRewrite.getImportRewrite(); + importRewrite.addImport(StandardCharsets.class.getCanonicalName()); + importRewrite.addImport(Charset.class.getCanonicalName()); + + // Check if the static field already exists in the class + TypeDeclaration enclosingType = (TypeDeclaration) cuRewrite.getRoot().types().get(0); + FieldDeclaration existingField = findStaticCharsetField(enclosingType, fieldName); + + QualifiedName fieldReference; + if (existingField == null) { + // Create a new static field if it doesn't exist + VariableDeclarationFragment fragment = ast.newVariableDeclarationFragment(); + fragment.setName(ast.newSimpleName(fieldName)); + fragment.setInitializer(createCharsetAccessExpression(ast, charset)); + + FieldDeclaration fieldDeclaration = ast.newFieldDeclaration(fragment); + fieldDeclaration.setType(ast.newSimpleType(ast.newName("Charset"))); //$NON-NLS-1$ + fieldDeclaration.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PRIVATE_KEYWORD)); + fieldDeclaration.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.STATIC_KEYWORD)); + fieldDeclaration.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.FINAL_KEYWORD)); + + // Add the new field to the class + cuRewrite.getASTRewrite().getListRewrite(enclosingType, TypeDeclaration.BODY_DECLARATIONS_PROPERTY) + .insertFirst(fieldDeclaration, null); + + // Create a QualifiedName to refer to this new field + fieldReference = ast.newQualifiedName( + ast.newSimpleName(enclosingType.getName().getIdentifier()), + ast.newSimpleName(fragment.getName().getIdentifier()) + ); + } else { + // If the field already exists, find its reference name + VariableDeclarationFragment fragment = (VariableDeclarationFragment) existingField.fragments().get(0); + fieldReference = ast.newQualifiedName( + ast.newSimpleName(enclosingType.getName().getIdentifier()), + fragment.getName() + ); + } + + // Cache the field reference in the map and return it + charsetConstants.put(fieldName, fieldReference); + return fieldReference; + } + + @Override + protected String computeCharsetforPreview() { + return "CharsetConstant"; //$NON-NLS-1$ + } + }; + + abstract protected Expression computeCharsetASTNode(final CompilationUnitRewrite cuRewrite, AST ast, String charset, Map charsetConstants); + + abstract protected String computeCharsetforPreview(); + + protected FieldDeclaration findStaticCharsetField(TypeDeclaration type, String fieldName) { + for (FieldDeclaration field : type.getFields()) { + for (Object fragment : field.fragments()) { + if (fragment instanceof VariableDeclarationFragment) { + VariableDeclarationFragment varFrag = (VariableDeclarationFragment) fragment; + if (varFrag.getName().getIdentifier().equals(fieldName)) { + return field; + } + } + } + } + return null; + } + + protected Expression createCharsetAccessExpression(AST ast, String charset) { + FieldAccess fieldAccess = ast.newFieldAccess(); + fieldAccess.setExpression(ast.newName(StandardCharsets.class.getSimpleName())); + fieldAccess.setName(ast.newSimpleName(charset)); + return fieldAccess; + } + + /** + * Create access to StandardCharsets.UTF_8, needs Java 1.7 or newer + * + * @param cuRewrite CompilationUnitRewrite + * @param ast AST + * @param charset Charset as String + * @return FieldAccess that returns Charset for UTF_8 + */ + protected static FieldAccess addCharsetUTF8(CompilationUnitRewrite cuRewrite, AST ast, String charset) { + /** + * Add import java.nio.charset.StandardCharsets - available since Java 1.7 + */ + ImportRewrite importRewrite= cuRewrite.getImportRewrite(); + importRewrite.addImport(StandardCharsets.class.getCanonicalName()); + /** + * Add field access to StandardCharsets.UTF_8 + */ + FieldAccess fieldaccess= ast.newFieldAccess(); + fieldaccess.setExpression(ASTNodeFactory.newName(ast, StandardCharsets.class.getSimpleName())); + + fieldaccess.setName(ast.newSimpleName(charset)); + return fieldaccess; + } + + /** + * Create call to Charset.defaultCharset(), needs Java 1.5 or newer + * + * @param cuRewrite CompilationUnitRewrite + * @param ast AST + * @return MethodInvocation that returns Charset for platform encoding + */ + protected static MethodInvocation addCharsetComputation(final CompilationUnitRewrite cuRewrite, AST ast) { + /** + * Add import java.nio.charset.Charset + */ + ImportRewrite importRewrite= cuRewrite.getImportRewrite(); + importRewrite.addImport(Charset.class.getCanonicalName()); + /** + * Add call to Charset.defaultCharset() - this is available since Java 1.5 + */ + MethodInvocation firstCall= ast.newMethodInvocation(); + firstCall.setExpression(ASTNodeFactory.newName(ast, Charset.class.getSimpleName())); + firstCall.setName(ast.newSimpleName(METHOD_DEFAULT_CHARSET)); + return firstCall; + } + + /** + * Create call to Charset.defaultCharset().displayName(), needs Java 1.5 or newer + * + * @param cuRewrite CompilationUnitRewrite + * @param ast AST + * @param cb ChangeBehavior + * @param charset Charset as String + * @return MethodInvocation that returns String + */ + protected MethodInvocation addCharsetStringComputation(final CompilationUnitRewrite cuRewrite, AST ast, ChangeBehavior cb, String charset, Map charsetConstants) { + Expression callToCharsetDefaultCharset= computeCharsetASTNode(cuRewrite, ast, charset, charsetConstants); + /** + * Add second call to Charset.defaultCharset().displayName() + */ + MethodInvocation secondCall= ast.newMethodInvocation(); + secondCall.setExpression(callToCharsetDefaultCharset); + secondCall.setName(ast.newSimpleName(METHOD_DISPLAY_NAME)); + return secondCall; + } +} diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/ChannelsNewReaderExplicitEncoding.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/ChannelsNewReaderExplicitEncoding.java new file mode 100644 index 00000000000..f86c0aadc20 --- /dev/null +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/ChannelsNewReaderExplicitEncoding.java @@ -0,0 +1,136 @@ +/******************************************************************************* + * Copyright (c) 2021 Carsten Hammer. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Carsten Hammer + *******************************************************************************/ +package org.eclipse.jdt.internal.corext.fix.helper; + +import static org.eclipse.jdt.internal.corext.fix.LibStandardNames.METHOD_NEW_READER; + +import java.nio.channels.Channels; +import java.nio.channels.ReadableByteChannel; +import java.util.List; +import java.util.Set; + +import org.eclipse.text.edits.TextEditGroup; + +import org.eclipse.jdt.core.dom.AST; +import org.eclipse.jdt.core.dom.ASTNode; +import org.eclipse.jdt.core.dom.CompilationUnit; +import org.eclipse.jdt.core.dom.MethodInvocation; +import org.eclipse.jdt.core.dom.SimpleName; +import org.eclipse.jdt.core.dom.StringLiteral; +import org.eclipse.jdt.core.dom.rewrite.ASTRewrite; +import org.eclipse.jdt.core.dom.rewrite.ImportRewrite; +import org.eclipse.jdt.core.dom.rewrite.ListRewrite; + +import org.eclipse.jdt.internal.common.HelperVisitor; +import org.eclipse.jdt.internal.common.ReferenceHolder; +import org.eclipse.jdt.internal.corext.dom.ASTNodes; +import org.eclipse.jdt.internal.corext.fix.CompilationUnitRewriteOperationsFixCore.CompilationUnitRewriteOperation; +import org.eclipse.jdt.internal.corext.fix.UseExplicitEncodingFixCore; +import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite; +import org.eclipse.jdt.internal.corext.util.JavaModelUtil; + +/** + * Java 10 + * + * Change + * + * Find: Reader r=Channels.newReader(ch,"UTF-8") + * + * Rewrite: Reader r=Channels.newReader(ch,StandardCharsets.UTF_8) + * + * Find: Reader r5 = Channels.newReader(ch, "ISO-8859-1", 0, 1024) + * + * Rewrite: Reader r5 = Channels.newReader(ch, StandardCharsets.ISO_8859_1, 0, 1024) + * + * + * + */ +public class ChannelsNewReaderExplicitEncoding extends AbstractExplicitEncoding { + + @Override + public void find(UseExplicitEncodingFixCore fixcore, CompilationUnit compilationUnit, Set operations, Set nodesprocessed, ChangeBehavior cb) { + if (!JavaModelUtil.is10OrHigher(compilationUnit.getJavaElement().getJavaProject())) { + /** + * For Java 9 and older just do nothing + */ + return; + } + ReferenceHolder datah= new ReferenceHolder<>(); + HelperVisitor.callMethodInvocationVisitor(Channels.class, METHOD_NEW_READER, compilationUnit, datah, nodesprocessed, + (visited, holder) -> processFoundNode(fixcore, operations, cb, visited, holder)); + } + + private static boolean processFoundNode(UseExplicitEncodingFixCore fixcore, + Set operations, ChangeBehavior cb, + MethodInvocation visited, ReferenceHolder holder) { + List arguments= visited.arguments(); + if (ASTNodes.usesGivenSignature(visited, Channels.class.getCanonicalName(), METHOD_NEW_READER, + ReadableByteChannel.class.getCanonicalName(), String.class.getCanonicalName())) { + + ASTNode encodingArg= arguments.get(1); + + String encodingValue= null; + if (encodingArg instanceof StringLiteral) { + encodingValue= ((StringLiteral) encodingArg).getLiteralValue().toUpperCase(); + } else if (encodingArg instanceof SimpleName) { + encodingValue= findVariableValue((SimpleName) encodingArg, visited); + } + + if (encodingValue != null && encodings.contains(encodingValue)) { + Nodedata nd= new Nodedata(); + nd.encoding= encodingmap.get(encodingValue); + nd.replace= true; + nd.visited= encodingArg; + holder.put(visited, nd); + operations.add(fixcore.rewrite(visited, cb, holder)); + return false; + } + } + return false; + } + + @Override + public void rewrite(UseExplicitEncodingFixCore upp, final MethodInvocation visited, final CompilationUnitRewrite cuRewrite, + TextEditGroup group, ChangeBehavior cb, ReferenceHolder data) { + ASTRewrite rewrite= cuRewrite.getASTRewrite(); + AST ast= cuRewrite.getRoot().getAST(); + ImportRewrite importRewriter= cuRewrite.getImportRewrite(); + Nodedata nodedata= (Nodedata) data.get(visited); + ASTNode callToCharsetDefaultCharset= cb.computeCharsetASTNode(cuRewrite, ast, nodedata.encoding,Nodedata.charsetConstants); + /** + * Add Charset.defaultCharset() as second (last) parameter + */ + ListRewrite listRewrite= rewrite.getListRewrite(visited, MethodInvocation.ARGUMENTS_PROPERTY); + if (nodedata.replace) { + listRewrite.replace(nodedata.visited, callToCharsetDefaultCharset, group); + removeNLSComment(cuRewrite, visited, group); + } else { + listRewrite.insertLast(callToCharsetDefaultCharset, group); + } + removeUnsupportedEncodingException(visited, group, rewrite, importRewriter); + } + + @Override + public String getPreview(boolean afterRefactoring, ChangeBehavior cb) { + if (afterRefactoring) { + return "Reader r=Channels.newReader(ch,StandardCharsets.UTF_8);\n"; //$NON-NLS-1$ + } + return "Reader r=Channels.newReader(ch,\"UTF-8\");\n"; //$NON-NLS-1$ + } + + @Override + public String toString() { + return "Channels.newReader(ch,StandardCharsets.UTF_8)"; //$NON-NLS-1$ + } +} diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/ChannelsNewWriterExplicitEncoding.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/ChannelsNewWriterExplicitEncoding.java new file mode 100644 index 00000000000..c513a67204e --- /dev/null +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/ChannelsNewWriterExplicitEncoding.java @@ -0,0 +1,126 @@ +/******************************************************************************* + * Copyright (c) 2021 Carsten Hammer. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Carsten Hammer + *******************************************************************************/ +package org.eclipse.jdt.internal.corext.fix.helper; + +import static org.eclipse.jdt.internal.corext.fix.LibStandardNames.METHOD_NEW_WRITER; + +import java.nio.channels.Channels; +import java.nio.channels.WritableByteChannel; +import java.util.List; +import java.util.Set; + +import org.eclipse.text.edits.TextEditGroup; + +import org.eclipse.jdt.core.dom.AST; +import org.eclipse.jdt.core.dom.ASTNode; +import org.eclipse.jdt.core.dom.CompilationUnit; +import org.eclipse.jdt.core.dom.MethodInvocation; +import org.eclipse.jdt.core.dom.SimpleName; +import org.eclipse.jdt.core.dom.StringLiteral; +import org.eclipse.jdt.core.dom.rewrite.ASTRewrite; +import org.eclipse.jdt.core.dom.rewrite.ImportRewrite; +import org.eclipse.jdt.core.dom.rewrite.ListRewrite; + +import org.eclipse.jdt.internal.common.HelperVisitor; +import org.eclipse.jdt.internal.common.ReferenceHolder; +import org.eclipse.jdt.internal.corext.dom.ASTNodes; +import org.eclipse.jdt.internal.corext.fix.CompilationUnitRewriteOperationsFixCore.CompilationUnitRewriteOperation; +import org.eclipse.jdt.internal.corext.fix.UseExplicitEncodingFixCore; +import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite; +import org.eclipse.jdt.internal.corext.util.JavaModelUtil; + +/** + * Java 10 + * + * Find: Channels.newWriter(ch,"UTF-8") + * + * Rewrite: Channels.newWriter(ch,StandardCharsets.UTF_8) + * + */ +public class ChannelsNewWriterExplicitEncoding extends AbstractExplicitEncoding { + + @Override + public void find(UseExplicitEncodingFixCore fixcore, CompilationUnit compilationUnit, Set operations, Set nodesprocessed, ChangeBehavior cb) { + if (!JavaModelUtil.is10OrHigher(compilationUnit.getJavaElement().getJavaProject())) { + /** + * For Java 9 and older just do nothing + */ + return; + } + ReferenceHolder datah= new ReferenceHolder<>(); + HelperVisitor.callMethodInvocationVisitor(Channels.class, METHOD_NEW_WRITER, compilationUnit, datah, nodesprocessed, + (visited, holder) -> processFoundNode(fixcore, operations, cb, visited, holder)); + } + + private static boolean processFoundNode(UseExplicitEncodingFixCore fixcore, + Set operations, ChangeBehavior cb, + MethodInvocation visited, ReferenceHolder holder) { + List arguments= visited.arguments(); + if (ASTNodes.usesGivenSignature(visited, Channels.class.getCanonicalName(), METHOD_NEW_WRITER, WritableByteChannel.class.getCanonicalName(), String.class.getCanonicalName())) { + + ASTNode encodingArg= arguments.get(1); + + String encodingValue= null; + if (encodingArg instanceof StringLiteral) { + encodingValue= ((StringLiteral) encodingArg).getLiteralValue(); + } else if (encodingArg instanceof SimpleName) { + encodingValue= findVariableValue((SimpleName) encodingArg, visited); + } + + if (encodingValue != null && encodings.contains(encodingValue.toUpperCase())) { + Nodedata nd= new Nodedata(); + nd.encoding= encodingmap.get(encodingValue.toUpperCase()); + nd.replace= true; + nd.visited= encodingArg; + holder.put(visited, nd); + operations.add(fixcore.rewrite(visited, cb, holder)); + return false; + } + } + return false; + } + + @Override + public void rewrite(UseExplicitEncodingFixCore upp, final MethodInvocation visited, final CompilationUnitRewrite cuRewrite, + TextEditGroup group, ChangeBehavior cb, ReferenceHolder data) { + ASTRewrite rewrite= cuRewrite.getASTRewrite(); + AST ast= cuRewrite.getRoot().getAST(); + ImportRewrite importRewriter= cuRewrite.getImportRewrite(); + Nodedata nodedata= (Nodedata) data.get(visited); + ASTNode callToCharsetDefaultCharset= cb.computeCharsetASTNode(cuRewrite, ast, nodedata.encoding,Nodedata.charsetConstants); + /** + * Add Charset.defaultCharset() as second (last) parameter + */ + ListRewrite listRewrite= rewrite.getListRewrite(visited, MethodInvocation.ARGUMENTS_PROPERTY); + if (nodedata.replace) { + listRewrite.replace(nodedata.visited, callToCharsetDefaultCharset, group); + } else { + listRewrite.insertLast(callToCharsetDefaultCharset, group); + } + removeUnsupportedEncodingException(visited, group, rewrite, importRewriter); + } + + @Override + public String getPreview(boolean afterRefactoring, ChangeBehavior cb) { + if (afterRefactoring) { + return "Writer w=Channels.newWriter(ch, StandardCharsets.UTF_8);\n"; //$NON-NLS-1$ + } + return "Writer w=Channels.newWriter(ch, \"UTF-8\");\n"; //$NON-NLS-1$ + } + + @Override + public String toString() { + return "Channels.newWriter(ch,StandardCharsets.UTF_8)"; //$NON-NLS-1$ + } +} diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/CharsetForNameExplicitEncoding.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/CharsetForNameExplicitEncoding.java new file mode 100644 index 00000000000..965755310d7 --- /dev/null +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/CharsetForNameExplicitEncoding.java @@ -0,0 +1,116 @@ +/******************************************************************************* + * Copyright (c) 2021 Carsten Hammer. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Carsten Hammer + *******************************************************************************/ +package org.eclipse.jdt.internal.corext.fix.helper; + +import static org.eclipse.jdt.internal.corext.fix.LibStandardNames.METHOD_FOR_NAME; + +import java.nio.charset.Charset; +import java.util.List; +import java.util.Set; + +import org.eclipse.text.edits.TextEditGroup; + +import org.eclipse.jdt.core.dom.AST; +import org.eclipse.jdt.core.dom.ASTNode; +import org.eclipse.jdt.core.dom.CompilationUnit; +import org.eclipse.jdt.core.dom.MethodInvocation; +import org.eclipse.jdt.core.dom.SimpleName; +import org.eclipse.jdt.core.dom.StringLiteral; +import org.eclipse.jdt.core.dom.rewrite.ASTRewrite; + +import org.eclipse.jdt.internal.common.HelperVisitor; +import org.eclipse.jdt.internal.common.ReferenceHolder; +import org.eclipse.jdt.internal.corext.dom.ASTNodes; +import org.eclipse.jdt.internal.corext.fix.CompilationUnitRewriteOperationsFixCore.CompilationUnitRewriteOperation; +import org.eclipse.jdt.internal.corext.fix.UseExplicitEncodingFixCore; +import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite; +import org.eclipse.jdt.internal.corext.util.JavaModelUtil; + +/** + * Java 18 + * + * Find: Charset.forName("UTF-8") + * + * Rewrite: StandardCharsets.UTF_8 + * + * Find: Charset.forName("UTF-16") + * + * Rewrite: StandardCharsets.UTF_16 + */ +public class CharsetForNameExplicitEncoding extends AbstractExplicitEncoding { + + @Override + public void find(UseExplicitEncodingFixCore fixcore, CompilationUnit compilationUnit, Set operations, Set nodesprocessed, ChangeBehavior cb) { + if (!JavaModelUtil.is18OrHigher(compilationUnit.getJavaElement().getJavaProject())) { + /** + * For Java 17 and older just do nothing + */ + return; + } + ReferenceHolder datah= new ReferenceHolder<>(); + HelperVisitor.callMethodInvocationVisitor(Charset.class, METHOD_FOR_NAME, compilationUnit, datah, nodesprocessed, + (visited, holder) -> processFoundNode(fixcore, operations, cb, visited, holder)); + } + + private static boolean processFoundNode(UseExplicitEncodingFixCore fixcore, + Set operations, ChangeBehavior cb, + MethodInvocation visited, ReferenceHolder holder) { + List arguments= visited.arguments(); + if (!ASTNodes.usesGivenSignature(visited, Charset.class.getCanonicalName(), METHOD_FOR_NAME, String.class.getCanonicalName())) { + return true; + } + ASTNode encodingArg= arguments.get(0); + + String encodingValue= null; + if (encodingArg instanceof StringLiteral) { + encodingValue= ((StringLiteral) encodingArg).getLiteralValue().toUpperCase(); + } else if (encodingArg instanceof SimpleName) { + encodingValue= findVariableValue((SimpleName) encodingArg, visited); + } + + if (encodingValue != null && encodings.contains(encodingValue)) { + Nodedata nd= new Nodedata(); + nd.encoding= encodingmap.get(encodingValue); + nd.replace= true; + nd.visited= encodingArg; + holder.put(visited, nd); + operations.add(fixcore.rewrite(visited, cb, holder)); + return false; + } + return false; + } + + @Override + public void rewrite(UseExplicitEncodingFixCore upp, final MethodInvocation visited, final CompilationUnitRewrite cuRewrite, + TextEditGroup group, ChangeBehavior cb, ReferenceHolder data) { + ASTRewrite rewrite= cuRewrite.getASTRewrite(); + AST ast= cuRewrite.getRoot().getAST(); + Nodedata nodedata= (Nodedata) data.get(visited); + ASTNode callToCharsetDefaultCharset= cb.computeCharsetASTNode(cuRewrite, ast, nodedata.encoding,Nodedata.charsetConstants); + ASTNodes.replaceButKeepComment(rewrite, visited, callToCharsetDefaultCharset, group); + } + + @Override + public String getPreview(boolean afterRefactoring, ChangeBehavior cb) { + if (afterRefactoring) { + return "Charset s=StandardCharsets.UTF_8;\n"; //$NON-NLS-1$ + } + return "Charset s=Charset.forName(\"UTF-8\");\n"; //$NON-NLS-1$ + } + + @Override + public String toString() { + return "Charset.forName(\"UTF-8\")"; //$NON-NLS-1$ + } +} diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/FileReaderExplicitEncoding.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/FileReaderExplicitEncoding.java new file mode 100644 index 00000000000..60c4eee720a --- /dev/null +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/FileReaderExplicitEncoding.java @@ -0,0 +1,116 @@ +/******************************************************************************* + * Copyright (c) 2021 Carsten Hammer. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Carsten Hammer + *******************************************************************************/ +package org.eclipse.jdt.internal.corext.fix.helper; + +import java.io.FileInputStream; +import java.io.FileReader; +import java.io.InputStreamReader; +import java.util.List; +import java.util.Set; + +import org.eclipse.text.edits.TextEditGroup; + +import org.eclipse.jdt.core.dom.AST; +import org.eclipse.jdt.core.dom.ASTNode; +import org.eclipse.jdt.core.dom.ClassInstanceCreation; +import org.eclipse.jdt.core.dom.CompilationUnit; +import org.eclipse.jdt.core.dom.StringLiteral; +import org.eclipse.jdt.core.dom.rewrite.ASTRewrite; + +import org.eclipse.jdt.internal.common.HelperVisitor; +import org.eclipse.jdt.internal.common.ReferenceHolder; +import org.eclipse.jdt.internal.corext.dom.ASTNodes; +import org.eclipse.jdt.internal.corext.fix.CompilationUnitRewriteOperationsFixCore.CompilationUnitRewriteOperation; +import org.eclipse.jdt.internal.corext.fix.UseExplicitEncodingFixCore; +import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite; + +/** + * Change + * + * Find: Reader is=new FileReader("file.txt") + * + * Rewrite: Reader is=new InputStreamReader(new + * FileInputStream("file.txt"),Charset.defaultCharset()); + * + * Charset.defaultCharset() is available since Java 1.5 + * + */ +public class FileReaderExplicitEncoding extends AbstractExplicitEncoding { + + @Override + public void find(UseExplicitEncodingFixCore fixcore, CompilationUnit compilationUnit, Set operations, Set nodesprocessed, ChangeBehavior cb) { + ReferenceHolder datah= new ReferenceHolder<>(); + HelperVisitor.callClassInstanceCreationVisitor(FileReader.class, compilationUnit, datah, nodesprocessed, (visited, holder) -> processFoundNode(fixcore, operations, cb, visited, holder)); + } + + private static boolean processFoundNode(UseExplicitEncodingFixCore fixcore, + Set operations, ChangeBehavior cb, + ClassInstanceCreation visited, ReferenceHolder holder) { + List arguments= visited.arguments(); + switch (arguments.size()) { + case 1: + break; + case 2: + if (!(arguments.get(1) instanceof StringLiteral)) { + return false; + } + StringLiteral argstring3= (StringLiteral) arguments.get(1); + if (!encodings.contains(argstring3.getLiteralValue())) { + return false; + } + holder.put(argstring3, encodingmap.get(argstring3.getLiteralValue())); + break; + default: + return false; + } + operations.add(fixcore.rewrite(visited, cb, holder)); + return false; + } + + @Override + public void rewrite(UseExplicitEncodingFixCore upp, final ClassInstanceCreation visited, final CompilationUnitRewrite cuRewrite, + TextEditGroup group, ChangeBehavior cb, ReferenceHolder data) { + ASTRewrite rewrite= cuRewrite.getASTRewrite(); + AST ast= cuRewrite.getRoot().getAST(); + ASTNode callToCharsetDefaultCharset= cb.computeCharsetASTNode(cuRewrite, ast, (String) data.get(visited),Nodedata.charsetConstants); + /** + * new FileInputStream() + */ + ClassInstanceCreation fisclassInstance= ast.newClassInstanceCreation(); + fisclassInstance.setType(ast.newSimpleType(addImport(FileInputStream.class.getCanonicalName(), cuRewrite, ast))); + fisclassInstance.arguments().add(ASTNodes.createMoveTarget(rewrite, ASTNodes.getUnparenthesedExpression((ASTNode) visited.arguments().get(0)))); + /** + * new InputStreamReader(new FileInputStream()) + */ + ClassInstanceCreation isrclassInstance= ast.newClassInstanceCreation(); + isrclassInstance.setType(ast.newSimpleType(addImport(InputStreamReader.class.getCanonicalName(), cuRewrite, ast))); + isrclassInstance.arguments().add(fisclassInstance); + isrclassInstance.arguments().add(callToCharsetDefaultCharset); + + ASTNodes.replaceButKeepComment(rewrite, visited, isrclassInstance, group); + } + + @Override + public String getPreview(boolean afterRefactoring, ChangeBehavior cb) { + if (afterRefactoring) { + return "Reader r=new InputStreamReader(new FileInputStream(inputfile)," + cb.computeCharsetforPreview() + ");\n"; //$NON-NLS-1$ //$NON-NLS-2$ + } + return "Reader r=new FileReader(inputfile);\n"; //$NON-NLS-1$ + } + + @Override + public String toString() { + return "new FileReader(inputfile)"; //$NON-NLS-1$ + } +} diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/FileWriterExplicitEncoding.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/FileWriterExplicitEncoding.java new file mode 100644 index 00000000000..a51ee99bf11 --- /dev/null +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/FileWriterExplicitEncoding.java @@ -0,0 +1,95 @@ +/******************************************************************************* + * Copyright (c) 2021 Carsten Hammer. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Carsten Hammer + *******************************************************************************/ +package org.eclipse.jdt.internal.corext.fix.helper; + +import java.io.FileOutputStream; +import java.io.FileWriter; +import java.io.OutputStreamWriter; +import java.util.Set; + +import org.eclipse.text.edits.TextEditGroup; + +import org.eclipse.jdt.core.dom.AST; +import org.eclipse.jdt.core.dom.ASTNode; +import org.eclipse.jdt.core.dom.ClassInstanceCreation; +import org.eclipse.jdt.core.dom.CompilationUnit; +import org.eclipse.jdt.core.dom.rewrite.ASTRewrite; + +import org.eclipse.jdt.internal.common.HelperVisitor; +import org.eclipse.jdt.internal.common.ReferenceHolder; +import org.eclipse.jdt.internal.corext.dom.ASTNodes; +import org.eclipse.jdt.internal.corext.fix.CompilationUnitRewriteOperationsFixCore.CompilationUnitRewriteOperation; +import org.eclipse.jdt.internal.corext.fix.UseExplicitEncodingFixCore; +import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite; + +/** + * Change + * + * Writer fw=new FileWriter("file.txt") Writer fw=new OutputStreamWriter(new + * FileOutputStream("file.txt"),defaultCharset); + * + * Charset.defaultCharset() is available since Java 1.5 + * + */ +public class FileWriterExplicitEncoding extends AbstractExplicitEncoding { + + @Override + public void find(UseExplicitEncodingFixCore fixcore, CompilationUnit compilationUnit, Set operations, Set nodesprocessed, ChangeBehavior cb) { + ReferenceHolder datah= new ReferenceHolder<>(); + HelperVisitor.callClassInstanceCreationVisitor(FileWriter.class, compilationUnit, datah, nodesprocessed, (visited, holder) -> processFoundNode(fixcore, operations, cb, visited, holder)); + } + + private static boolean processFoundNode(UseExplicitEncodingFixCore fixcore, Set operations, + ChangeBehavior cb, ClassInstanceCreation visited, + ReferenceHolder holder) { + operations.add(fixcore.rewrite(visited, cb, holder)); + return false; + } + + @Override + public void rewrite(UseExplicitEncodingFixCore upp, final ClassInstanceCreation visited, final CompilationUnitRewrite cuRewrite, + TextEditGroup group, ChangeBehavior cb, ReferenceHolder data) { + ASTRewrite rewrite= cuRewrite.getASTRewrite(); + AST ast= cuRewrite.getRoot().getAST(); + ASTNode callToCharsetDefaultCharset= cb.computeCharsetASTNode(cuRewrite, ast, (String) data.get(visited),Nodedata.charsetConstants); + /** + * new FileInputStream() + */ + ClassInstanceCreation fosclassInstance= ast.newClassInstanceCreation(); + fosclassInstance.setType(ast.newSimpleType(addImport(FileOutputStream.class.getCanonicalName(), cuRewrite, ast))); + fosclassInstance.arguments().add(ASTNodes.createMoveTarget(rewrite, ASTNodes.getUnparenthesedExpression((ASTNode) visited.arguments().get(0)))); + /** + * new InputStreamReader(new FileInputStream()) + */ + ClassInstanceCreation oswclassInstance= ast.newClassInstanceCreation(); + oswclassInstance.setType(ast.newSimpleType(addImport(OutputStreamWriter.class.getCanonicalName(), cuRewrite, ast))); + oswclassInstance.arguments().add(fosclassInstance); + oswclassInstance.arguments().add(callToCharsetDefaultCharset); + + ASTNodes.replaceButKeepComment(rewrite, visited, oswclassInstance, group); + } + + @Override + public String getPreview(boolean afterRefactoring, ChangeBehavior cb) { + if (afterRefactoring) { + return "Writer w=new OutputStreamWriter(new FileOutputStream(outputfile)," + cb.computeCharsetforPreview() + ");\n"; //$NON-NLS-1$ //$NON-NLS-2$ + } + return "Writer w=new FileWriter(outputfile);\n"; //$NON-NLS-1$ + } + + @Override + public String toString() { + return "new FileWriter(outputfile)"; //$NON-NLS-1$ + } +} diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/FormatterExplicitEncoding.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/FormatterExplicitEncoding.java new file mode 100644 index 00000000000..bb386ea49f0 --- /dev/null +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/FormatterExplicitEncoding.java @@ -0,0 +1,146 @@ +/******************************************************************************* + * Copyright (c) 2021 Carsten Hammer. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Carsten Hammer + *******************************************************************************/ +package org.eclipse.jdt.internal.corext.fix.helper; + +import java.util.Formatter; +import java.util.List; +import java.util.Set; + +import org.eclipse.text.edits.TextEditGroup; + +import org.eclipse.jdt.core.dom.AST; +import org.eclipse.jdt.core.dom.ASTNode; +import org.eclipse.jdt.core.dom.ClassInstanceCreation; +import org.eclipse.jdt.core.dom.CompilationUnit; +import org.eclipse.jdt.core.dom.StringLiteral; +import org.eclipse.jdt.core.dom.rewrite.ASTRewrite; +import org.eclipse.jdt.core.dom.rewrite.ImportRewrite; +import org.eclipse.jdt.core.dom.rewrite.ListRewrite; + +import org.eclipse.jdt.internal.common.HelperVisitor; +import org.eclipse.jdt.internal.common.ReferenceHolder; +import org.eclipse.jdt.internal.corext.fix.CompilationUnitRewriteOperationsFixCore.CompilationUnitRewriteOperation; +import org.eclipse.jdt.internal.corext.fix.UseExplicitEncodingFixCore; +import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite; + +/** + * + * Find: new java.util.Formatter(new File(), String cs) throws UnsupportedEncodingException + * + * Rewrite: new java.util.Formatter(new File(), Charset cs) + * + * Find: new java.util.Formatter(new File(), String cs,new java.util.Locale()) + * + * Rewrite: new java.util.Formatter(new File(), Charset cs,new java.util.Locale()) + * + * Find: new java.util.Formatter(new java.io.OutputStream(), String cs) + * + * Rewrite: new java.util.Formatter(new java.io.OutputStream(), Charset cs) + * + * Find: new java.util.Formatter(new java.io.OutputStream(), String cs,new java.util.Locale()) + * + * Rewrite: new java.util.Formatter(new java.io.OutputStream(), Charset cs,new java.util.Locale()) + * + * Find: new java.util.Formatter(new String(), String cs) + * + * Rewrite: new java.util.Formatter(new String(), Charset cs) + * + * Find: new java.util.Formatter(new String(), String cs,new java.util.Locale()) + * + * Rewrite: new java.util.Formatter(new String(), Charset cs,new java.util.Locale()) + * + * Find: new java.util.Formatter(new File()) + * + * Rewrite: new java.util.Formatter(new File(), Charset.defaultCharset()) depends on + * https://docs.oracle.com/en/java/javase/20/docs/api/java.base/java/lang/System.html#file.encoding + * + */ +public class FormatterExplicitEncoding extends AbstractExplicitEncoding { + + @Override + public void find(UseExplicitEncodingFixCore fixcore, CompilationUnit compilationUnit, Set operations, Set nodesprocessed, ChangeBehavior cb) { + ReferenceHolder datah= new ReferenceHolder<>(); + HelperVisitor.callClassInstanceCreationVisitor(Formatter.class, compilationUnit, datah, nodesprocessed, (visited, holder) -> processFoundNode(fixcore, operations, cb, visited, holder)); + } + + private static boolean processFoundNode(UseExplicitEncodingFixCore fixcore, + Set operations, + ChangeBehavior cb, + ClassInstanceCreation visited, + ReferenceHolder holder) { + List arguments= visited.arguments(); + Nodedata nd= new Nodedata(); + + switch (arguments.size()) { + case 2: + case 3: + if (arguments.get(1) instanceof StringLiteral) { + StringLiteral argString= (StringLiteral) arguments.get(1); + String encodingKey= argString.getLiteralValue().toUpperCase(); + + if (encodings.contains(encodingKey)) { + nd.encoding= encodingmap.get(encodingKey); + nd.replace= true; + nd.visited= argString; + holder.put(visited, nd); + operations.add(fixcore.rewrite(visited, cb, holder)); + } + } + break; + case 1: + nd.encoding= null; + nd.replace= false; + nd.visited= visited; + holder.put(visited, nd); + operations.add(fixcore.rewrite(visited, cb, holder)); + break; + default: + break; + } + return false; + } + + @Override + public void rewrite(UseExplicitEncodingFixCore upp, final ClassInstanceCreation visited, final CompilationUnitRewrite cuRewrite, + TextEditGroup group, ChangeBehavior cb, ReferenceHolder data) { + ASTRewrite rewrite= cuRewrite.getASTRewrite(); + AST ast= cuRewrite.getRoot().getAST(); + ImportRewrite importRewriter= cuRewrite.getImportRewrite(); + Nodedata nodedata= (Nodedata) data.get(visited); + ASTNode callToCharsetDefaultCharset= cb.computeCharsetASTNode(cuRewrite, ast, nodedata.encoding,Nodedata.charsetConstants); + /** + * Add Charset.defaultCharset() as second (last) parameter + */ + ListRewrite listRewrite= rewrite.getListRewrite(visited, ClassInstanceCreation.ARGUMENTS_PROPERTY); + if (nodedata.replace) { + listRewrite.replace(nodedata.visited, callToCharsetDefaultCharset, group); + } else { + listRewrite.insertLast(callToCharsetDefaultCharset, group); + } + removeUnsupportedEncodingException(visited, group, rewrite, importRewriter); + } + + @Override + public String getPreview(boolean afterRefactoring, ChangeBehavior cb) { + if (afterRefactoring) { + return "Formatter r=new java.util.Formatter(out, " + cb.computeCharsetforPreview() + ");\n"; //$NON-NLS-1$ //$NON-NLS-2$ + } + return "Formatter r=new java.util.Formatter(out);\n"; //$NON-NLS-1$ + } + + @Override + public String toString() { + return "new java.util.Formatter(out)"; //$NON-NLS-1$ + } +} diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/InputStreamReaderExplicitEncoding.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/InputStreamReaderExplicitEncoding.java new file mode 100644 index 00000000000..e409f8612e9 --- /dev/null +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/InputStreamReaderExplicitEncoding.java @@ -0,0 +1,120 @@ +/******************************************************************************* + * Copyright (c) 2021 Carsten Hammer. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Carsten Hammer + *******************************************************************************/ +package org.eclipse.jdt.internal.corext.fix.helper; + +import java.io.InputStreamReader; +import java.util.List; +import java.util.Set; + +import org.eclipse.text.edits.TextEditGroup; + +import org.eclipse.jdt.core.dom.ASTNode; +import org.eclipse.jdt.core.dom.ClassInstanceCreation; +import org.eclipse.jdt.core.dom.CompilationUnit; +import org.eclipse.jdt.core.dom.StringLiteral; +import org.eclipse.jdt.core.dom.rewrite.ASTRewrite; +import org.eclipse.jdt.core.dom.rewrite.ListRewrite; + +import org.eclipse.jdt.internal.common.HelperVisitor; +import org.eclipse.jdt.internal.common.ReferenceHolder; +import org.eclipse.jdt.internal.corext.fix.CompilationUnitRewriteOperationsFixCore.CompilationUnitRewriteOperation; +import org.eclipse.jdt.internal.corext.fix.UseExplicitEncodingFixCore; +import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite; + +/** + * + * Find: InputStreamReader(InputStream in, String cs) + * + * Rewrite: InputStreamReader(InputStream in, Charset cs) is available since Java 1.4 + * + * Charset.defaultCharset() is available since Java 1.5 + * + */ +public class InputStreamReaderExplicitEncoding extends AbstractExplicitEncoding { + + @Override + public void find(UseExplicitEncodingFixCore fixcore, CompilationUnit compilationUnit, Set operations, Set nodesprocessed, ChangeBehavior cb) { + ReferenceHolder datah= new ReferenceHolder<>(); + HelperVisitor.callClassInstanceCreationVisitor(InputStreamReader.class, compilationUnit, datah, nodesprocessed, + (visited, holder) -> processFoundNode(fixcore, operations, cb, visited, holder)); + } + + private static boolean processFoundNode(UseExplicitEncodingFixCore fixcore, + Set operations, ChangeBehavior cb, + ClassInstanceCreation visited, ReferenceHolder holder) { + List arguments= visited.arguments(); + switch (arguments.size()) { + case 2: + if (!(arguments.get(1) instanceof StringLiteral)) { + return false; + } + StringLiteral argstring3= (StringLiteral) arguments.get(1); + if (!encodings.contains(argstring3.getLiteralValue().toUpperCase())) { + return false; + } + Nodedata nd= new Nodedata(); + nd.encoding= encodingmap.get(argstring3.getLiteralValue().toUpperCase()); + nd.replace= true; + nd.visited= argstring3; + holder.put(visited, nd); + operations.add(fixcore.rewrite(visited, cb, holder)); + break; + case 1: + Nodedata nd2= new Nodedata(); + nd2.encoding= null; + nd2.replace= false; + nd2.visited= visited; + holder.put(visited, nd2); + operations.add(fixcore.rewrite(visited, cb, holder)); + break; + default: + break; + } + + return false; + } + + @Override + public void rewrite(UseExplicitEncodingFixCore upp, ClassInstanceCreation visited, CompilationUnitRewrite cuRewrite, + TextEditGroup group, ChangeBehavior cb, ReferenceHolder data) { + ASTRewrite rewrite = cuRewrite.getASTRewrite(); + Nodedata nodedata = (Nodedata) data.get(visited); + + ASTNode callToCharsetDefaultCharset = cb.computeCharsetASTNode(cuRewrite, cuRewrite.getRoot().getAST(), + nodedata.encoding, Nodedata.charsetConstants); + + ListRewrite listRewrite = rewrite.getListRewrite(visited, ClassInstanceCreation.ARGUMENTS_PROPERTY); + if (nodedata.replace) { + listRewrite.replace(nodedata.visited, callToCharsetDefaultCharset, group); + removeNLSComment(cuRewrite, visited, group); + } else { + listRewrite.insertLast(callToCharsetDefaultCharset, group); + } + + removeUnsupportedEncodingException(visited, group, rewrite, cuRewrite.getImportRewrite()); + } + + @Override + public String getPreview(boolean afterRefactoring, ChangeBehavior cb) { + if (afterRefactoring) { + return "Reader r=new InputStreamReader(in, " + cb.computeCharsetforPreview() + ");\nInputStreamReader is=new InputStreamReader(new FileInputStream(\"\"), \"UTF-8\");\n"; //$NON-NLS-1$ //$NON-NLS-2$ + } + return "Reader r=new InputStreamReader(in);\nInputStreamReader is=new InputStreamReader(new FileInputStream(\"\"), StandardCharsets.UTF_8);\n"; //$NON-NLS-1$ + } + + @Override + public String toString() { + return "new InputStreamReader(in)"; //$NON-NLS-1$ + } +} diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/OutputStreamWriterExplicitEncoding.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/OutputStreamWriterExplicitEncoding.java new file mode 100644 index 00000000000..125664b7fe9 --- /dev/null +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/OutputStreamWriterExplicitEncoding.java @@ -0,0 +1,135 @@ +/******************************************************************************* + * Copyright (c) 2021 Carsten Hammer. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Carsten Hammer + *******************************************************************************/ +package org.eclipse.jdt.internal.corext.fix.helper; + +import java.io.OutputStreamWriter; +import java.util.List; +import java.util.Set; + +import org.eclipse.text.edits.TextEditGroup; + +import org.eclipse.jdt.core.dom.AST; +import org.eclipse.jdt.core.dom.ASTNode; +import org.eclipse.jdt.core.dom.ClassInstanceCreation; +import org.eclipse.jdt.core.dom.CompilationUnit; +import org.eclipse.jdt.core.dom.StringLiteral; +import org.eclipse.jdt.core.dom.rewrite.ASTRewrite; +import org.eclipse.jdt.core.dom.rewrite.ImportRewrite; +import org.eclipse.jdt.core.dom.rewrite.ListRewrite; + +import org.eclipse.jdt.internal.common.HelperVisitor; +import org.eclipse.jdt.internal.common.ReferenceHolder; +import org.eclipse.jdt.internal.corext.fix.CompilationUnitRewriteOperationsFixCore.CompilationUnitRewriteOperation; +import org.eclipse.jdt.internal.corext.fix.UseExplicitEncodingFixCore; +import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite; + +/** + * Change + * + * Find: OutputStreamWriter os=new OutputStreamWriter(InputStream in, String cs) + * + * Rewrite: OutputStreamWriter os=new OutputStreamWriter(InputStream in, CharSet cs) + * + * + * Find: OutputStreamWriter os=new OutputStreamWriter(InputStream in) + * + * Rewrite: OutputStreamWriter os=new OutputStreamWriter(InputStream in, Charset.defaultCharset()) + * + * + * Find: OutputStreamWriter os=new OutputStreamWriter(InputStream in) + * + * Rewrite: OutputStreamWriter os=new OutputStreamWriter(InputStream in, StandardCharsets.UTF_8) + * + * Charset.defaultCharset() is available since Java 1.5 + * + */ +public class OutputStreamWriterExplicitEncoding extends AbstractExplicitEncoding { + + @Override + public void find(UseExplicitEncodingFixCore fixcore, CompilationUnit compilationUnit, Set operations, Set nodesprocessed, ChangeBehavior cb) { + ReferenceHolder datah= new ReferenceHolder<>(); + HelperVisitor.callClassInstanceCreationVisitor(OutputStreamWriter.class, compilationUnit, datah, nodesprocessed, + (visited, holder) -> processFoundNode(fixcore, operations, cb, visited, holder)); + } + + private static boolean processFoundNode(UseExplicitEncodingFixCore fixcore, + Set operations, ChangeBehavior cb, + ClassInstanceCreation visited, ReferenceHolder holder) { + List arguments= visited.arguments(); + switch (arguments.size()) { + case 2: + if (!(arguments.get(1) instanceof StringLiteral)) { + return false; + } + StringLiteral argstring3= (StringLiteral) arguments.get(1); + if (!encodings.contains(argstring3.getLiteralValue())) { + return false; + } + Nodedata nd= new Nodedata(); + nd.encoding= encodingmap.get(argstring3.getLiteralValue()); + nd.replace= true; + nd.visited= argstring3; + holder.put(visited, nd); + operations.add(fixcore.rewrite(visited, cb, holder)); + break; + case 1: + Nodedata nd2= new Nodedata(); + nd2.encoding= null; + nd2.replace= false; + nd2.visited= visited; + holder.put(visited, nd2); + operations.add(fixcore.rewrite(visited, cb, holder)); + break; + default: + break; + } + + return false; + } + + @Override + public void rewrite(UseExplicitEncodingFixCore upp, final ClassInstanceCreation visited, final CompilationUnitRewrite cuRewrite, + TextEditGroup group, ChangeBehavior cb, ReferenceHolder data) { + ASTRewrite rewrite= cuRewrite.getASTRewrite(); + AST ast= cuRewrite.getRoot().getAST(); + ImportRewrite importRewriter= cuRewrite.getImportRewrite(); + Nodedata nodedata= (Nodedata) data.get(visited); + ASTNode callToCharsetDefaultCharset= cb.computeCharsetASTNode(cuRewrite, ast, nodedata.encoding,Nodedata.charsetConstants); + /** + * Add Charset.defaultCharset() as second (last) parameter + */ + ListRewrite listRewrite= rewrite.getListRewrite(visited, ClassInstanceCreation.ARGUMENTS_PROPERTY); + if (nodedata.replace) { + listRewrite.replace(nodedata.visited, callToCharsetDefaultCharset, group); + removeNLSComment(cuRewrite, visited, group); + } else { + listRewrite.insertLast(callToCharsetDefaultCharset, group); + } + removeUnsupportedEncodingException(visited, group, rewrite, importRewriter); + } + + @Override + public String getPreview(boolean afterRefactoring, ChangeBehavior cb) { + if (afterRefactoring) { + return "Writer w = new OutputStreamWriter(out, " + cb.computeCharsetforPreview() //$NON-NLS-1$ + + ");\nOutputStreamWriter os=new OutputStreamWriter(new FileOutputStream(\"\"), StandardCharsets.UTF_8);\n"; //$NON-NLS-1$ + } + return "Writer w = new OutputStreamWriter(out);\nOutputStreamWriter os=new OutputStreamWriter(new FileOutputStream(\"\"), \"UTF-8\");\n"; //$NON-NLS-1$ + } + + @Override + public String toString() { + return "new OutputStreamWriter(out)"; //$NON-NLS-1$ + } +} diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/PrintStreamExplicitEncoding.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/PrintStreamExplicitEncoding.java new file mode 100644 index 00000000000..57fde8df388 --- /dev/null +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/PrintStreamExplicitEncoding.java @@ -0,0 +1,144 @@ +/******************************************************************************* + * Copyright (c) 2021 Carsten Hammer. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Carsten Hammer + *******************************************************************************/ +package org.eclipse.jdt.internal.corext.fix.helper; + +import java.io.BufferedWriter; +import java.io.FileOutputStream; +import java.io.OutputStreamWriter; +import java.io.PrintStream; +import java.util.List; +import java.util.Set; + +import org.eclipse.text.edits.TextEditGroup; + +import org.eclipse.jdt.core.dom.AST; +import org.eclipse.jdt.core.dom.ASTNode; +import org.eclipse.jdt.core.dom.ClassInstanceCreation; +import org.eclipse.jdt.core.dom.CompilationUnit; +import org.eclipse.jdt.core.dom.StringLiteral; +import org.eclipse.jdt.core.dom.rewrite.ASTRewrite; + +import org.eclipse.jdt.internal.common.HelperVisitor; +import org.eclipse.jdt.internal.common.ReferenceHolder; +import org.eclipse.jdt.internal.corext.dom.ASTNodes; +import org.eclipse.jdt.internal.corext.fix.CompilationUnitRewriteOperationsFixCore.CompilationUnitRewriteOperation; +import org.eclipse.jdt.internal.corext.fix.UseExplicitEncodingFixCore; +import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite; + +/** + * Change + * + * Find: Stream fw=new PrintStream("file.txt", "UTF-8") + * + * Rewrite: Stream fw=new PrintStream("file.txt", StandardCharsets.UTF_8) + * + * Find: Stream fw=new PrintStream(new File("file.txt"), "UTF-8") + * + * Rewrite: Stream fw=new PrintStream(new File("file.txt"), StandardCharsets.UTF_8) + * + * Find: Stream fw=new PrintStream(new java.io.OutputStream(), boolean, "UTF-8") + * + * Rewrite: Stream fw=new PrintStream(new java.io.OutputStream(), boolean, StandardCharsets.UTF_8) + * + */ +public class PrintStreamExplicitEncoding extends AbstractExplicitEncoding { + + @Override + public void find(UseExplicitEncodingFixCore fixcore, CompilationUnit compilationUnit, Set operations, Set nodesprocessed, ChangeBehavior cb) { + ReferenceHolder datah= new ReferenceHolder<>(); + HelperVisitor.callClassInstanceCreationVisitor(PrintStream.class, compilationUnit, datah, nodesprocessed, (visited, holder) -> processFoundNode(fixcore, operations, cb, visited, holder)); + } + + private static boolean processFoundNode(UseExplicitEncodingFixCore fixcore, Set operations, + ChangeBehavior cb, ClassInstanceCreation visited, + ReferenceHolder holder) { + List arguments= visited.arguments(); + switch (arguments.size()) { + case 1: + break; + case 2: + if (!(arguments.get(1) instanceof StringLiteral)) { + return false; + } + StringLiteral argstring3= (StringLiteral) arguments.get(1); + if (!encodings.contains(argstring3.getLiteralValue())) { + return false; + } + holder.put(argstring3, encodingmap.get(argstring3.getLiteralValue())); + break; + case 3: + if (!(arguments.get(2) instanceof StringLiteral)) { + return false; + } + StringLiteral argstring4= (StringLiteral) arguments.get(2); + if (!encodings.contains(argstring4.getLiteralValue())) { + return false; + } + holder.put(argstring4, encodingmap.get(argstring4.getLiteralValue())); + break; + default: + return false; + } + operations.add(fixcore.rewrite(visited, cb, holder)); + return false; + } + + @Override + public void rewrite(UseExplicitEncodingFixCore upp, final ClassInstanceCreation visited, final CompilationUnitRewrite cuRewrite, + TextEditGroup group, ChangeBehavior cb, ReferenceHolder data) { + ASTRewrite rewrite= cuRewrite.getASTRewrite(); + AST ast= cuRewrite.getRoot().getAST(); + ASTNode callToCharsetDefaultCharset= cb.computeCharsetASTNode(cuRewrite, ast, (String) data.get(visited),Nodedata.charsetConstants); + /** + * new FileOutputStream() + */ + ClassInstanceCreation fosclassInstance= ast.newClassInstanceCreation(); + fosclassInstance.setType(ast.newSimpleType(addImport(FileOutputStream.class.getCanonicalName(), cuRewrite, ast))); + fosclassInstance.arguments().add(ASTNodes.createMoveTarget(rewrite, ASTNodes.getUnparenthesedExpression((ASTNode) visited.arguments().get(0)))); + /** + * new OutputStreamWriter(new FileOutputStream()) + */ + ClassInstanceCreation oswclassInstance= ast.newClassInstanceCreation(); + oswclassInstance.setType(ast.newSimpleType(addImport(OutputStreamWriter.class.getCanonicalName(), cuRewrite, ast))); + oswclassInstance.arguments().add(fosclassInstance); + oswclassInstance.arguments().add(callToCharsetDefaultCharset); + /** + * new BufferedWriter(new OutputStreamWriter(new FileOutputStream())) + */ + ClassInstanceCreation bwclassInstance= ast.newClassInstanceCreation(); + bwclassInstance.setType(ast.newSimpleType(addImport(BufferedWriter.class.getCanonicalName(), cuRewrite, ast))); + bwclassInstance.arguments().add(oswclassInstance); + + ASTNodes.replaceButKeepComment(rewrite, visited, bwclassInstance, group); + } + + @Override + public String getPreview(boolean afterRefactoring, ChangeBehavior cb) { + if (afterRefactoring) { + return "Stream w=new PrintStream(\"out.txt\"," + cb.computeCharsetforPreview() + ");\n" + //$NON-NLS-1$ //$NON-NLS-2$ + "Stream w=new PrintStream(\"out.txt\",StandardCharsets.UTF_8);\n" + //$NON-NLS-1$ + "Stream w=new PrintStream(new File(\"out.txt\"),StandardCharsets.UTF_8);\n"; //$NON-NLS-1$ + } + return """ + Stream w=new PrintStream("out.txt"); + Stream w=new PrintStream("out.txt","UTF-8"); + Stream w=new PrintStream(new File("out.txt"),"UTF-8"); + """; //$NON-NLS-1$ + } + + @Override + public String toString() { + return "new PrintStream(\"out.txt\")"; //$NON-NLS-1$ + } +} diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/PrintWriterExplicitEncoding.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/PrintWriterExplicitEncoding.java new file mode 100644 index 00000000000..5b0ed886d55 --- /dev/null +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/PrintWriterExplicitEncoding.java @@ -0,0 +1,119 @@ +/******************************************************************************* + * Copyright (c) 2021 Carsten Hammer. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Carsten Hammer + *******************************************************************************/ +package org.eclipse.jdt.internal.corext.fix.helper; + +import java.io.BufferedWriter; +import java.io.FileOutputStream; +import java.io.OutputStreamWriter; +import java.io.PrintWriter; +import java.util.Set; + +import org.eclipse.text.edits.TextEditGroup; + +import org.eclipse.jdt.core.dom.AST; +import org.eclipse.jdt.core.dom.ASTNode; +import org.eclipse.jdt.core.dom.ClassInstanceCreation; +import org.eclipse.jdt.core.dom.CompilationUnit; +import org.eclipse.jdt.core.dom.rewrite.ASTRewrite; + +import org.eclipse.jdt.internal.common.HelperVisitor; +import org.eclipse.jdt.internal.common.ReferenceHolder; +import org.eclipse.jdt.internal.corext.dom.ASTNodes; +import org.eclipse.jdt.internal.corext.fix.CompilationUnitRewriteOperationsFixCore.CompilationUnitRewriteOperation; +import org.eclipse.jdt.internal.corext.fix.UseExplicitEncodingFixCore; +import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite; +import org.eclipse.jdt.internal.corext.util.JavaModelUtil; + +/** + * + * Java 10 + * + * Change + * + * Find: Writer fw=new PrintWriter("file.txt") + * + * Rewrite: Writer fw=new BufferedWriter(new OutputStreamWriter(new + * FileOutputStream("file.txt"),defaultCharset))); + * + * Find: Writer fw=new PrintWriter(new File("file.txt")) + * + * Rewrite: Writer fw=new BufferedWriter(new OutputStreamWriter(new + * FileOutputStream("file.txt"),defaultCharset))); + * + * Charset.defaultCharset() is available since Java 1.5 + * + */ +public class PrintWriterExplicitEncoding extends AbstractExplicitEncoding { + + @Override + public void find(UseExplicitEncodingFixCore fixcore, CompilationUnit compilationUnit, Set operations, Set nodesprocessed, ChangeBehavior cb) { + if (!JavaModelUtil.is10OrHigher(compilationUnit.getJavaElement().getJavaProject())) { + /** + * For Java 9 and older just do nothing + */ + return; + } + ReferenceHolder datah= new ReferenceHolder<>(); + HelperVisitor.callClassInstanceCreationVisitor(PrintWriter.class, compilationUnit, datah, nodesprocessed, (visited, holder) -> processFoundNode(fixcore, operations, cb, visited, holder)); + } + + private static boolean processFoundNode(UseExplicitEncodingFixCore fixcore, Set operations, + ChangeBehavior cb, ClassInstanceCreation visited, + ReferenceHolder holder) { + operations.add(fixcore.rewrite(visited, cb, holder)); + return false; + } + + @Override + public void rewrite(UseExplicitEncodingFixCore upp, final ClassInstanceCreation visited, final CompilationUnitRewrite cuRewrite, + TextEditGroup group, ChangeBehavior cb, ReferenceHolder data) { + ASTRewrite rewrite= cuRewrite.getASTRewrite(); + AST ast= cuRewrite.getRoot().getAST(); + ASTNode callToCharsetDefaultCharset= cb.computeCharsetASTNode(cuRewrite, ast, (String) data.get(visited),Nodedata.charsetConstants); + /** + * new FileOutputStream() + */ + ClassInstanceCreation fosclassInstance= ast.newClassInstanceCreation(); + fosclassInstance.setType(ast.newSimpleType(addImport(FileOutputStream.class.getCanonicalName(), cuRewrite, ast))); + fosclassInstance.arguments().add(ASTNodes.createMoveTarget(rewrite, ASTNodes.getUnparenthesedExpression((ASTNode) visited.arguments().get(0)))); + /** + * new OutputStreamWriter(new FileOutputStream()) + */ + ClassInstanceCreation oswclassInstance= ast.newClassInstanceCreation(); + oswclassInstance.setType(ast.newSimpleType(addImport(OutputStreamWriter.class.getCanonicalName(), cuRewrite, ast))); + oswclassInstance.arguments().add(fosclassInstance); + oswclassInstance.arguments().add(callToCharsetDefaultCharset); + /** + * new BufferedWriter(new OutputStreamWriter(new FileOutputStream())) + */ + ClassInstanceCreation bwclassInstance= ast.newClassInstanceCreation(); + bwclassInstance.setType(ast.newSimpleType(addImport(BufferedWriter.class.getCanonicalName(), cuRewrite, ast))); + bwclassInstance.arguments().add(oswclassInstance); + + ASTNodes.replaceButKeepComment(rewrite, visited, bwclassInstance, group); + } + + @Override + public String getPreview(boolean afterRefactoring, ChangeBehavior cb) { + if (afterRefactoring) { + return "Writer w=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputfile)," + cb.computeCharsetforPreview() + "));\n"; //$NON-NLS-1$ //$NON-NLS-2$ + } + return "Writer w=new PrintWriter(outputfile);\n"; //$NON-NLS-1$ + } + + @Override + public String toString() { + return "new PrintWriter(outputfile)"; //$NON-NLS-1$ + } +} diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/PropertiesStoreToXMLExplicitEncoding.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/PropertiesStoreToXMLExplicitEncoding.java new file mode 100644 index 00000000000..008cef31145 --- /dev/null +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/PropertiesStoreToXMLExplicitEncoding.java @@ -0,0 +1,132 @@ +/******************************************************************************* + * Copyright (c) 2021 Carsten Hammer. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Carsten Hammer + *******************************************************************************/ +package org.eclipse.jdt.internal.corext.fix.helper; + +import static org.eclipse.jdt.internal.corext.fix.LibStandardNames.METHOD_STORE_TO_XML; + +import java.util.List; +import java.util.Properties; +import java.util.Set; + +import org.eclipse.text.edits.TextEditGroup; + +import org.eclipse.jdt.core.dom.AST; +import org.eclipse.jdt.core.dom.ASTNode; +import org.eclipse.jdt.core.dom.CompilationUnit; +import org.eclipse.jdt.core.dom.MethodInvocation; +import org.eclipse.jdt.core.dom.StringLiteral; +import org.eclipse.jdt.core.dom.rewrite.ASTRewrite; +import org.eclipse.jdt.core.dom.rewrite.ImportRewrite; +import org.eclipse.jdt.core.dom.rewrite.ListRewrite; + +import org.eclipse.jdt.internal.common.HelperVisitor; +import org.eclipse.jdt.internal.common.ReferenceHolder; +import org.eclipse.jdt.internal.corext.fix.CompilationUnitRewriteOperationsFixCore.CompilationUnitRewriteOperation; +import org.eclipse.jdt.internal.corext.fix.UseExplicitEncodingFixCore; +import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite; +import org.eclipse.jdt.internal.corext.util.JavaModelUtil; + +/** + * Find: Properties.storeToXML(java.io.OutputStream,"comment","UTF-8") throws + * UnsupportedEncodingException By default the UTF-8 character encoding is used so + * Properties.storeToXML(java.io.OutputStream,"comment") is the same as + * Properties.storeToXML(java.io.OutputStream,"comment", StandardCharsets.UTF_8) + * + * Rewrite: Properties.storeToXML(java.io.OutputStream,"comment", StandardCharsets.UTF_8) + * + */ +public class PropertiesStoreToXMLExplicitEncoding extends AbstractExplicitEncoding { + + @Override + public void find(UseExplicitEncodingFixCore fixcore, CompilationUnit compilationUnit, Set operations, Set nodesprocessed, ChangeBehavior cb) { + if (!JavaModelUtil.is10OrHigher(compilationUnit.getJavaElement().getJavaProject())) { + /** + * For Java 9 and older just do nothing + */ + return; + } + ReferenceHolder datah= new ReferenceHolder<>(); + HelperVisitor.callMethodInvocationVisitor(Properties.class, METHOD_STORE_TO_XML, compilationUnit, datah, nodesprocessed, + (visited, holder) -> processFoundNode(fixcore, operations, cb, visited, holder)); + } + + private static boolean processFoundNode(UseExplicitEncodingFixCore fixcore, + Set operations, ChangeBehavior cb, + MethodInvocation visited, ReferenceHolder holder) { + List arguments= visited.arguments(); + switch (arguments.size()) { + case 3: + if (!(arguments.get(2) instanceof StringLiteral)) { + return false; + } + StringLiteral argstring3= (StringLiteral) arguments.get(2); + if (!encodings.contains(argstring3.getLiteralValue().toUpperCase())) { + return false; + } + Nodedata nd= new Nodedata(); + nd.encoding= encodingmap.get(argstring3.getLiteralValue().toUpperCase()); + nd.replace= true; + nd.visited= argstring3; + holder.put(visited, nd); + operations.add(fixcore.rewrite(visited, cb, holder)); + break; + case 2: + Nodedata nd2= new Nodedata(); + nd2.encoding= "UTF_8"; //$NON-NLS-1$ + nd2.replace= false; + nd2.visited= visited; + holder.put(visited, nd2); + operations.add(fixcore.rewrite(visited, cb, holder)); + break; + default: + return false; + } + return false; + } + + @Override + public void rewrite(UseExplicitEncodingFixCore upp, final MethodInvocation visited, final CompilationUnitRewrite cuRewrite, + TextEditGroup group, ChangeBehavior cb, ReferenceHolder data) { + ASTRewrite rewrite= cuRewrite.getASTRewrite(); + AST ast= cuRewrite.getRoot().getAST(); + ImportRewrite importRewriter= cuRewrite.getImportRewrite(); + Nodedata nodedata= (Nodedata) data.get(visited); + ASTNode callToCharsetDefaultCharset= cb.computeCharsetASTNode(cuRewrite, ast, nodedata.encoding,Nodedata.charsetConstants); + /** + * Add StandardCharsets.UTF_8 as third (last) parameter + */ + ListRewrite listRewrite= rewrite.getListRewrite(visited, MethodInvocation.ARGUMENTS_PROPERTY); + if (nodedata.replace) { + listRewrite.replace(nodedata.visited, callToCharsetDefaultCharset, group); + } else { + listRewrite.insertLast(callToCharsetDefaultCharset, group); + } + removeUnsupportedEncodingException(visited, group, rewrite, importRewriter); + } + + @Override + public String getPreview(boolean afterRefactoring, ChangeBehavior cb) { + if (afterRefactoring) { + return "Properties p=new Properties();\n" + //$NON-NLS-1$ + "p.storeToXML(java.io.OutputStream,String,StandardCharsets.UTF_8);\n"; //$NON-NLS-1$ + } + return "Properties p=new Properties();\n" + //$NON-NLS-1$ + "p.storeToXML(java.io.OutputStream,String,\"UTF-8\");\n"; //$NON-NLS-1$ + } + + @Override + public String toString() { + return "Properties.storeToXML()"; //$NON-NLS-1$ + } +} diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/ScannerExplicitEncoding.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/ScannerExplicitEncoding.java new file mode 100644 index 00000000000..398e7838e6b --- /dev/null +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/ScannerExplicitEncoding.java @@ -0,0 +1,144 @@ +/******************************************************************************* + * Copyright (c) 2021 Carsten Hammer. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Carsten Hammer + *******************************************************************************/ +package org.eclipse.jdt.internal.corext.fix.helper; + +import java.util.List; +import java.util.Scanner; +import java.util.Set; + +import org.eclipse.text.edits.TextEditGroup; + +import org.eclipse.jdt.core.dom.AST; +import org.eclipse.jdt.core.dom.ASTNode; +import org.eclipse.jdt.core.dom.ClassInstanceCreation; +import org.eclipse.jdt.core.dom.CompilationUnit; +import org.eclipse.jdt.core.dom.StringLiteral; +import org.eclipse.jdt.core.dom.rewrite.ASTRewrite; +import org.eclipse.jdt.core.dom.rewrite.ListRewrite; + +import org.eclipse.jdt.internal.common.HelperVisitor; +import org.eclipse.jdt.internal.common.ReferenceHolder; +import org.eclipse.jdt.internal.corext.fix.CompilationUnitRewriteOperationsFixCore.CompilationUnitRewriteOperation; +import org.eclipse.jdt.internal.corext.fix.UseExplicitEncodingFixCore; +import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite; +import org.eclipse.jdt.internal.corext.util.JavaModelUtil; + +/** + * + * Java 10 + * + * Change + * + * Find: new java.util.Scanner(new File("filename.txt"),"UTF-8") + * + * Rewrite: new java.util.Scanner(new File("filename.txt"),StandardCharsets.UTF_8); + * + * Find: new java.util.Scanner("filename.txt", "UTF-8") + * + * Rewrite: new java.util.Scanner("filename.txt", StandardCharsets.UTF_8) + * + * Find: new java.util.Scanner(java.io.OutputStream, "UTF-8") + * + * Rewrite: new java.util.Scanner(java.io.OutputStream, StandardCharsets.UTF_8) + * + * Find: new java.util.Scanner(java.io.OutputStream) + * + * Rewrite: new java.util.Scanner(java.io.OutputStream, Charset.defaultCharset()) + */ +public class ScannerExplicitEncoding extends AbstractExplicitEncoding { + + @Override + public void find(UseExplicitEncodingFixCore fixcore, CompilationUnit compilationUnit, Set operations, Set nodesprocessed, ChangeBehavior cb) { + if (!JavaModelUtil.is10OrHigher(compilationUnit.getJavaElement().getJavaProject())) { + /** + * For Java 9 and older just do nothing + */ + return; + } + ReferenceHolder datah= new ReferenceHolder<>(); + HelperVisitor.callClassInstanceCreationVisitor(Scanner.class, compilationUnit, datah, nodesprocessed, (visited, holder) -> processFoundNode(fixcore, operations, cb, visited, holder)); + } + + private static boolean processFoundNode(UseExplicitEncodingFixCore fixcore, Set operations, + ChangeBehavior cb, ClassInstanceCreation visited, + ReferenceHolder holder) { + List arguments= visited.arguments(); + Nodedata nd= new Nodedata(); + + switch (arguments.size()) { + case 4: + case 2: + int encodingIndex= (arguments.size() == 4) ? 3 : 1; + ASTNode argumentNode= arguments.get(encodingIndex); + + if (argumentNode instanceof StringLiteral) { + StringLiteral encodingLiteral= (StringLiteral) argumentNode; + String encodingValue= encodingLiteral.getLiteralValue().toUpperCase(); + + if (encodings.contains(encodingValue)) { + nd.encoding= encodingmap.get(encodingValue); + nd.replace= true; + nd.visited= encodingLiteral; + holder.put(visited, nd); + operations.add(fixcore.rewrite(visited, cb, holder)); + } + } + break; + + case 1: + nd.encoding= null; + nd.replace= false; + nd.visited= visited; + holder.put(visited, nd); + operations.add(fixcore.rewrite(visited, cb, holder)); + break; + + default: + break; + } + + return false; + } + + @Override + public void rewrite(UseExplicitEncodingFixCore upp, final ClassInstanceCreation visited, final CompilationUnitRewrite cuRewrite, + TextEditGroup group, ChangeBehavior cb, ReferenceHolder data) { + ASTRewrite rewrite= cuRewrite.getASTRewrite(); + AST ast= cuRewrite.getRoot().getAST(); + Nodedata nodedata= (Nodedata) data.get(visited); + ASTNode callToCharsetDefaultCharset= cb.computeCharsetASTNode(cuRewrite, ast, nodedata.encoding,Nodedata.charsetConstants); + /** + * Add Charset.defaultCharset() as second (last) parameter + */ + ListRewrite listRewrite= rewrite.getListRewrite(visited, ClassInstanceCreation.ARGUMENTS_PROPERTY); + if (nodedata.replace) { + listRewrite.replace(nodedata.visited, callToCharsetDefaultCharset, group); + } else { + listRewrite.insertLast(callToCharsetDefaultCharset, group); + } + } + + @Override + public String getPreview(boolean afterRefactoring, ChangeBehavior cb) { + if (afterRefactoring) { + return "new java.util.Scanner(\"asdf\",StandardCharsets.UTF_8);\n"; //$NON-NLS-1$ + } + return "new java.util.Scanner(\"asdf\", \"UTF-8\");\n"; //$NON-NLS-1$ + } + + @Override + public String toString() { + return "new java.util.Scanner()"; //$NON-NLS-1$ + } +} diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/StringExplicitEncoding.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/StringExplicitEncoding.java new file mode 100644 index 00000000000..ac43bd8932d --- /dev/null +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/StringExplicitEncoding.java @@ -0,0 +1,141 @@ +/******************************************************************************* + * Copyright (c) 2021 Carsten Hammer. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Carsten Hammer + *******************************************************************************/ +package org.eclipse.jdt.internal.corext.fix.helper; + +import java.util.List; +import java.util.Set; + +import org.eclipse.text.edits.TextEditGroup; + +import org.eclipse.jdt.core.dom.AST; +import org.eclipse.jdt.core.dom.ASTNode; +import org.eclipse.jdt.core.dom.ClassInstanceCreation; +import org.eclipse.jdt.core.dom.CompilationUnit; +import org.eclipse.jdt.core.dom.StringLiteral; +import org.eclipse.jdt.core.dom.rewrite.ASTRewrite; +import org.eclipse.jdt.core.dom.rewrite.ImportRewrite; +import org.eclipse.jdt.core.dom.rewrite.ListRewrite; + +import org.eclipse.jdt.internal.common.HelperVisitor; +import org.eclipse.jdt.internal.common.ReferenceHolder; +import org.eclipse.jdt.internal.corext.fix.CompilationUnitRewriteOperationsFixCore.CompilationUnitRewriteOperation; +import org.eclipse.jdt.internal.corext.fix.UseExplicitEncodingFixCore; +import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite; +import org.eclipse.jdt.internal.corext.util.JavaModelUtil; + +/** + * + * Java 10 + * + * Change + * + * Find: String s=new String(byte[],"UTF-8") + * + * Rewrite: String s=new String(byte[],StandardCharsets.UTF_8); + * + * Find: String s=new String(byte[],int, int, "UTF-8") + * + * Rewrite: String s=new String(byte[],int, int, StandardCharsets.UTF_8) + * + */ +public class StringExplicitEncoding extends AbstractExplicitEncoding { + + @Override + public void find(UseExplicitEncodingFixCore fixcore, CompilationUnit compilationUnit, Set operations, Set nodesprocessed, ChangeBehavior cb) { + if (!JavaModelUtil.is10OrHigher(compilationUnit.getJavaElement().getJavaProject())) { + /** + * For Java 9 and older just do nothing + */ + return; + } + ReferenceHolder datah= new ReferenceHolder<>(); + HelperVisitor.callClassInstanceCreationVisitor(String.class, compilationUnit, datah, nodesprocessed, (visited, holder) -> processFoundNode(fixcore, operations, cb, visited, holder)); + } + + private static boolean processFoundNode(UseExplicitEncodingFixCore fixcore, Set operations, + ChangeBehavior cb, ClassInstanceCreation visited, + ReferenceHolder holder) { + List arguments= visited.arguments(); + switch (arguments.size()) { + case 4: + if (!(arguments.get(3) instanceof StringLiteral)) { + return false; + } + StringLiteral argstring4= (StringLiteral) arguments.get(3); + if (!encodings.contains(argstring4.getLiteralValue().toUpperCase())) { + return false; + } + Nodedata nd= new Nodedata(); + nd.encoding= encodingmap.get(argstring4.getLiteralValue().toUpperCase()); + nd.replace= true; + nd.visited= argstring4; + holder.put(visited, nd); + operations.add(fixcore.rewrite(visited, cb, holder)); + break; + case 2: + if (!(arguments.get(1) instanceof StringLiteral)) { + return false; + } + StringLiteral argstring3= (StringLiteral) arguments.get(1); + if (!encodings.contains(argstring3.getLiteralValue().toUpperCase())) { + return false; + } + Nodedata nd2= new Nodedata(); + nd2.encoding= encodingmap.get(argstring3.getLiteralValue().toUpperCase()); + nd2.replace= true; + nd2.visited= argstring3; + holder.put(visited, nd2); + operations.add(fixcore.rewrite(visited, cb, holder)); + break; + case 1: + default: + break; + } + + return false; + } + + @Override + public void rewrite(UseExplicitEncodingFixCore upp, final ClassInstanceCreation visited, final CompilationUnitRewrite cuRewrite, + TextEditGroup group, ChangeBehavior cb, ReferenceHolder data) { + ASTRewrite rewrite= cuRewrite.getASTRewrite(); + AST ast= cuRewrite.getRoot().getAST(); + ImportRewrite importRewriter= cuRewrite.getImportRewrite(); + Nodedata nodedata= (Nodedata) data.get(visited); + ASTNode callToCharsetDefaultCharset= cb.computeCharsetASTNode(cuRewrite, ast, nodedata.encoding,Nodedata.charsetConstants); + /** + * Add Charset.defaultCharset() as second (last) parameter + */ + ListRewrite listRewrite= rewrite.getListRewrite(visited, ClassInstanceCreation.ARGUMENTS_PROPERTY); + if (nodedata.replace) { + listRewrite.replace(nodedata.visited, callToCharsetDefaultCharset, group); + } else { + listRewrite.insertLast(callToCharsetDefaultCharset, group); + } + removeUnsupportedEncodingException(visited, group, rewrite, importRewriter); + } + + @Override + public String getPreview(boolean afterRefactoring, ChangeBehavior cb) { + if (afterRefactoring) { + return "String s=new String(byte[]," + cb.computeCharsetforPreview() + ");\n"; //$NON-NLS-1$ //$NON-NLS-2$ + } + return "String s=new String(byte[],\"UTF-8\");\n"; //$NON-NLS-1$ + } + + @Override + public String toString() { + return "new String(byte[])"; //$NON-NLS-1$ + } +} diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/StringGetBytesExplicitEncoding.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/StringGetBytesExplicitEncoding.java new file mode 100644 index 00000000000..a16d6b47669 --- /dev/null +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/StringGetBytesExplicitEncoding.java @@ -0,0 +1,124 @@ +/******************************************************************************* + * Copyright (c) 2021 Carsten Hammer. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Carsten Hammer + *******************************************************************************/ +package org.eclipse.jdt.internal.corext.fix.helper; + +import static org.eclipse.jdt.internal.corext.fix.LibStandardNames.METHOD_GET_BYTES; + +import java.util.List; +import java.util.Set; + +import org.eclipse.text.edits.TextEditGroup; + +import org.eclipse.jdt.core.dom.AST; +import org.eclipse.jdt.core.dom.ASTNode; +import org.eclipse.jdt.core.dom.CompilationUnit; +import org.eclipse.jdt.core.dom.MethodInvocation; +import org.eclipse.jdt.core.dom.StringLiteral; +import org.eclipse.jdt.core.dom.rewrite.ASTRewrite; +import org.eclipse.jdt.core.dom.rewrite.ImportRewrite; +import org.eclipse.jdt.core.dom.rewrite.ListRewrite; + +import org.eclipse.jdt.internal.common.HelperVisitor; +import org.eclipse.jdt.internal.common.ReferenceHolder; +import org.eclipse.jdt.internal.corext.fix.CompilationUnitRewriteOperationsFixCore.CompilationUnitRewriteOperation; +import org.eclipse.jdt.internal.corext.fix.UseExplicitEncodingFixCore; +import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite; + +/** + * Find: String.getBytes() + * + * Rewrite: String.getBytes(Charset.defaultCharset()) + * + * Find: String.getBytes("Utf-8") + * + * Rewrite: String.getBytes(StandardCharsets.UTF_8) + */ +public class StringGetBytesExplicitEncoding extends AbstractExplicitEncoding { + + @Override + public void find(UseExplicitEncodingFixCore fixcore, CompilationUnit compilationUnit, Set operations, Set nodesprocessed, ChangeBehavior cb) { + ReferenceHolder datah= new ReferenceHolder<>(); + HelperVisitor.callMethodInvocationVisitor(String.class, METHOD_GET_BYTES, compilationUnit, datah, nodesprocessed, + (visited, holder) -> processFoundNode(fixcore, operations, cb, visited, holder)); + } + + private static boolean processFoundNode(UseExplicitEncodingFixCore fixcore, + Set operations, ChangeBehavior cb, + MethodInvocation visited, ReferenceHolder holder) { + List arguments= visited.arguments(); + switch (arguments.size()) { + case 1: + if (!(arguments.get(0) instanceof StringLiteral)) { + return false; + } + StringLiteral argstring3= (StringLiteral) arguments.get(0); + if (!encodings.contains(argstring3.getLiteralValue().toUpperCase())) { + return false; + } + Nodedata nd= new Nodedata(); + nd.encoding= encodingmap.get(argstring3.getLiteralValue().toUpperCase()); + nd.replace= true; + nd.visited= argstring3; + holder.put(visited, nd); + break; + case 0: + Nodedata nd2= new Nodedata(); + nd2.encoding= null; + nd2.replace= false; + nd2.visited= visited; + holder.put(visited, nd2); + break; + default: + return false; + } + operations.add(fixcore.rewrite(visited, cb, holder)); + return false; + } + + @Override + public void rewrite(UseExplicitEncodingFixCore upp, final MethodInvocation visited, final CompilationUnitRewrite cuRewrite, + TextEditGroup group, ChangeBehavior cb, ReferenceHolder data) { + ASTRewrite rewrite= cuRewrite.getASTRewrite(); + AST ast= cuRewrite.getRoot().getAST(); + ImportRewrite importRewriter= cuRewrite.getImportRewrite(); + Nodedata nodedata= (Nodedata) data.get(visited); + ASTNode callToCharsetDefaultCharset= cb.computeCharsetASTNode(cuRewrite, ast, nodedata.encoding,Nodedata.charsetConstants); + /** + * Add Charset.defaultCharset() as second (last) parameter + */ + ListRewrite listRewrite= rewrite.getListRewrite(visited, MethodInvocation.ARGUMENTS_PROPERTY); + if (nodedata.replace) { + listRewrite.replace(nodedata.visited, callToCharsetDefaultCharset, group); + removeNLSComment(cuRewrite, visited, group); + } else { + listRewrite.insertLast(callToCharsetDefaultCharset, group); + } + removeUnsupportedEncodingException(visited, group, rewrite, importRewriter); + } + + @Override + public String getPreview(boolean afterRefactoring, ChangeBehavior cb) { + if (afterRefactoring) { + return "String s=\"asdf\";\n" + //$NON-NLS-1$ + "byte[] bytes= s.getBytes(" + cb.computeCharsetforPreview() + ");\n"; //$NON-NLS-1$ //$NON-NLS-2$ + } + return "String s=\"asdf\";\n" + //$NON-NLS-1$ + "byte[] bytes= s.getBytes();\n"; //$NON-NLS-1$ + } + + @Override + public String toString() { + return "String.getBytes()"; //$NON-NLS-1$ + } +} diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/URLDecoderDecodeExplicitEncoding.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/URLDecoderDecodeExplicitEncoding.java new file mode 100644 index 00000000000..017892cba76 --- /dev/null +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/URLDecoderDecodeExplicitEncoding.java @@ -0,0 +1,156 @@ +/******************************************************************************* + * Copyright (c) 2021 Carsten Hammer. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Carsten Hammer + *******************************************************************************/ +package org.eclipse.jdt.internal.corext.fix.helper; + +import static org.eclipse.jdt.internal.corext.fix.LibStandardNames.METHOD_DECODE; + +import java.net.URLDecoder; +import java.util.List; +import java.util.Set; + +import org.eclipse.text.edits.TextEditGroup; + +import org.eclipse.jdt.core.dom.AST; +import org.eclipse.jdt.core.dom.ASTNode; +import org.eclipse.jdt.core.dom.CompilationUnit; +import org.eclipse.jdt.core.dom.MethodInvocation; +import org.eclipse.jdt.core.dom.SimpleName; +import org.eclipse.jdt.core.dom.StringLiteral; +import org.eclipse.jdt.core.dom.rewrite.ASTRewrite; +import org.eclipse.jdt.core.dom.rewrite.ImportRewrite; +import org.eclipse.jdt.core.dom.rewrite.ListRewrite; + +import org.eclipse.jdt.internal.common.HelperVisitor; +import org.eclipse.jdt.internal.common.ReferenceHolder; +import org.eclipse.jdt.internal.corext.dom.ASTNodes; +import org.eclipse.jdt.internal.corext.fix.CompilationUnitRewriteOperationsFixCore.CompilationUnitRewriteOperation; +import org.eclipse.jdt.internal.corext.fix.UseExplicitEncodingFixCore; +import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite; +import org.eclipse.jdt.internal.corext.util.JavaModelUtil; + +/** + * Java 10 + * + * Find: java.net.URLDecoder.decode("asdf","UTF-8") + * + * Rewrite: java.net.URLDecoder.decode("asdf",StandardCharsets.UTF_8) + * + * Find: java.net.URLDecoder.decode("asdf") Without the parameter the default is the file.encoding + * system property so Charset.defaultCharset() URLDecoder.decode("asdf") is (nearly) the same as + * URLDecoder.decode("asdf",Charset.defaultCharset()) But it is not really better (other than that + * you can see that it is depending on the default charset) + * + * KEEP + * + * Rewrite: java.net.URLDecoder.decode("asdf",Charset.defaultCharset()) + * + * USE_UTF8 + * + * Rewrite: java.net.URLDecoder.decode("asdf",StandardCharsets.UTF_8) This changes how the code + * works but it might be the better choice if you want to get rid of depending on environment + * settings + */ +public class URLDecoderDecodeExplicitEncoding extends AbstractExplicitEncoding { + + @Override + public void find(UseExplicitEncodingFixCore fixcore, CompilationUnit compilationUnit, Set operations, Set nodesprocessed, ChangeBehavior cb) { + if (!JavaModelUtil.is10OrHigher(compilationUnit.getJavaElement().getJavaProject())) { + /** + * For Java 9 and older just do nothing + */ + return; + } + ReferenceHolder datah= new ReferenceHolder<>(); + HelperVisitor.callMethodInvocationVisitor(URLDecoder.class, METHOD_DECODE, compilationUnit, datah, nodesprocessed, + (visited, holder) -> processFoundNode(fixcore, operations, cb, visited, holder)); + } + + private static boolean processFoundNode(UseExplicitEncodingFixCore fixcore, + Set operations, ChangeBehavior cb, + MethodInvocation visited, ReferenceHolder holder) { + List arguments= visited.arguments(); + if (ASTNodes.usesGivenSignature(visited, URLDecoder.class.getCanonicalName(), METHOD_DECODE, String.class.getCanonicalName(), String.class.getCanonicalName())) { + ASTNode encodingArg= arguments.get(1); + + String encodingValue= null; + if (encodingArg instanceof StringLiteral) { + encodingValue= ((StringLiteral) encodingArg).getLiteralValue().toUpperCase(); + } else if (encodingArg instanceof SimpleName) { + encodingValue= findVariableValue((SimpleName) encodingArg, visited); + } + + if (encodingValue != null && encodings.contains(encodingValue)) { + Nodedata nd= new Nodedata(); + nd.encoding= encodingmap.get(encodingValue); + nd.replace= true; + nd.visited= encodingArg; + holder.put(visited, nd); + operations.add(fixcore.rewrite(visited, cb, holder)); + return false; + } + } + if (ASTNodes.usesGivenSignature(visited, URLDecoder.class.getCanonicalName(), METHOD_DECODE, String.class.getCanonicalName())) { + Nodedata nd= new Nodedata(); + switch (cb) { + case KEEP_BEHAVIOR: + nd.encoding= null; + break; + case ENFORCE_UTF8: + nd.encoding= "UTF_8"; //$NON-NLS-1$ + break; + case ENFORCE_UTF8_AGGREGATE: + break; + } + nd.replace= false; + nd.visited= visited; + holder.put(visited, nd); + operations.add(fixcore.rewrite(visited, cb, holder)); + return false; + } + return false; + } + + @Override + public void rewrite(UseExplicitEncodingFixCore upp, final MethodInvocation visited, final CompilationUnitRewrite cuRewrite, + TextEditGroup group, ChangeBehavior cb, ReferenceHolder data) { + ASTRewrite rewrite= cuRewrite.getASTRewrite(); + AST ast= cuRewrite.getRoot().getAST(); + ImportRewrite importRewriter= cuRewrite.getImportRewrite(); + Nodedata nodedata= (Nodedata) data.get(visited); + ASTNode callToCharsetDefaultCharset= cb.computeCharsetASTNode(cuRewrite, ast, nodedata.encoding,Nodedata.charsetConstants); + /** + * Add Charset.defaultCharset() or StandardCharsets.UTF_8 as second (last) parameter + */ + ListRewrite listRewrite= rewrite.getListRewrite(visited, MethodInvocation.ARGUMENTS_PROPERTY); + if (nodedata.replace) { + listRewrite.replace(nodedata.visited, callToCharsetDefaultCharset, group); + } else { + listRewrite.insertLast(callToCharsetDefaultCharset, group); + } + removeUnsupportedEncodingException(visited, group, rewrite, importRewriter); + } + + @Override + public String getPreview(boolean afterRefactoring, ChangeBehavior cb) { + if (afterRefactoring) { + return "java.net.URLDecoder.decode(\"asdf\", StandardCharsets.UTF_8);\n"; //$NON-NLS-1$ + } + return "java.net.URLDecoder.decode(\"asdf\", \"UTF-8\");\n"; //$NON-NLS-1$ + } + + @Override + public String toString() { + return "URLDecoder.decode()"; //$NON-NLS-1$ + } +} diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/URLEncoderEncodeExplicitEncoding.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/URLEncoderEncodeExplicitEncoding.java new file mode 100644 index 00000000000..ea78b5f2461 --- /dev/null +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/helper/URLEncoderEncodeExplicitEncoding.java @@ -0,0 +1,157 @@ +/******************************************************************************* + * Copyright (c) 2021 Carsten Hammer. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Carsten Hammer + *******************************************************************************/ +package org.eclipse.jdt.internal.corext.fix.helper; + +import static org.eclipse.jdt.internal.corext.fix.LibStandardNames.METHOD_ENCODE; + +import java.net.URLEncoder; +import java.util.List; +import java.util.Set; + +import org.eclipse.text.edits.TextEditGroup; + +import org.eclipse.jdt.core.dom.AST; +import org.eclipse.jdt.core.dom.ASTNode; +import org.eclipse.jdt.core.dom.CompilationUnit; +import org.eclipse.jdt.core.dom.MethodInvocation; +import org.eclipse.jdt.core.dom.SimpleName; +import org.eclipse.jdt.core.dom.StringLiteral; +import org.eclipse.jdt.core.dom.rewrite.ASTRewrite; +import org.eclipse.jdt.core.dom.rewrite.ImportRewrite; +import org.eclipse.jdt.core.dom.rewrite.ListRewrite; + +import org.eclipse.jdt.internal.common.HelperVisitor; +import org.eclipse.jdt.internal.common.ReferenceHolder; +import org.eclipse.jdt.internal.corext.dom.ASTNodes; +import org.eclipse.jdt.internal.corext.fix.CompilationUnitRewriteOperationsFixCore.CompilationUnitRewriteOperation; +import org.eclipse.jdt.internal.corext.fix.UseExplicitEncodingFixCore; +import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite; +import org.eclipse.jdt.internal.corext.util.JavaModelUtil; + +/** + * Java 10 + * + * Find: java.net.URLEncoder.encode("asdf","UTF-8") + * + * Rewrite: java.net.URLEncoder.encode("asdf",StandardCharsets.UTF_8) + * + * Find: java.net.URLEncoder.encode("asdf") Without the parameter the default is the file.encoding + * system property so Charset.defaultCharset() URLEncoder.encode("asdf") is (nearly) the same as + * URLEncoder.encode("asdf",Charset.defaultCharset()) But it is not really better (other than that + * you can see that it is depending on the default charset) + * + * KEEP + * + * Rewrite: java.net.URLEncoder.encode("asdf",Charset.defaultCharset()) + * + * USE_UTF8 + * + * Rewrite: java.net.URLEncoder.encode("asdf",StandardCharsets.UTF_8) This changes how the code + * works but it might be the better choice if you want to get rid of depending on environment + * settings + */ +public class URLEncoderEncodeExplicitEncoding extends AbstractExplicitEncoding { + + @Override + public void find(UseExplicitEncodingFixCore fixcore, CompilationUnit compilationUnit, Set operations, Set nodesprocessed, ChangeBehavior cb) { + if (!JavaModelUtil.is10OrHigher(compilationUnit.getJavaElement().getJavaProject())) { + /** + * For Java 9 and older just do nothing + */ + return; + } + ReferenceHolder datah= new ReferenceHolder<>(); + Nodedata.charsetConstants.clear(); + HelperVisitor.callMethodInvocationVisitor(URLEncoder.class, METHOD_ENCODE, compilationUnit, datah, nodesprocessed, + (visited, holder) -> processFoundNode(fixcore, operations, cb, visited, holder)); + } + + private static boolean processFoundNode(UseExplicitEncodingFixCore fixcore, + Set operations, ChangeBehavior cb, + MethodInvocation visited, ReferenceHolder holder) { + List arguments= visited.arguments(); + if (ASTNodes.usesGivenSignature(visited, URLEncoder.class.getCanonicalName(), METHOD_ENCODE, String.class.getCanonicalName(), String.class.getCanonicalName())) { + ASTNode encodingArg= arguments.get(1); + + String encodingValue= null; + if (encodingArg instanceof StringLiteral) { + encodingValue= ((StringLiteral) encodingArg).getLiteralValue().toUpperCase(); + } else if (encodingArg instanceof SimpleName) { + encodingValue= findVariableValue((SimpleName) encodingArg, visited); + } + + if (encodingValue != null && encodings.contains(encodingValue)) { + Nodedata nd= new Nodedata(); + nd.encoding= encodingmap.get(encodingValue); + nd.replace= true; + nd.visited= encodingArg; + holder.put(visited, nd); + operations.add(fixcore.rewrite(visited, cb, holder)); + return false; + } + } + if (ASTNodes.usesGivenSignature(visited, URLEncoder.class.getCanonicalName(), METHOD_ENCODE, String.class.getCanonicalName())) { + Nodedata nd= new Nodedata(); + switch (cb) { + case KEEP_BEHAVIOR: + nd.encoding= null; + break; + case ENFORCE_UTF8: + nd.encoding= "UTF_8"; //$NON-NLS-1$ + break; + case ENFORCE_UTF8_AGGREGATE: + break; + } + nd.replace= false; + nd.visited= visited; + holder.put(visited, nd); + operations.add(fixcore.rewrite(visited, cb, holder)); + return false; + } + return false; + } + + @Override + public void rewrite(UseExplicitEncodingFixCore upp, final MethodInvocation visited, final CompilationUnitRewrite cuRewrite, + TextEditGroup group, ChangeBehavior cb, ReferenceHolder data) { + ASTRewrite rewrite= cuRewrite.getASTRewrite(); + AST ast= cuRewrite.getRoot().getAST(); + ImportRewrite importRewriter= cuRewrite.getImportRewrite(); + Nodedata nodedata= (Nodedata) data.get(visited); + ASTNode callToCharsetDefaultCharset= cb.computeCharsetASTNode(cuRewrite, ast, nodedata.encoding,Nodedata.charsetConstants); + /** + * Add Charset.defaultCharset() as second (last) parameter + */ + ListRewrite listRewrite= rewrite.getListRewrite(visited, MethodInvocation.ARGUMENTS_PROPERTY); + if (nodedata.replace) { + listRewrite.replace(nodedata.visited, callToCharsetDefaultCharset, group); + } else { + listRewrite.insertLast(callToCharsetDefaultCharset, group); + } + removeUnsupportedEncodingException(visited, group, rewrite, importRewriter); + } + + @Override + public String getPreview(boolean afterRefactoring, ChangeBehavior cb) { + if (afterRefactoring) { + return "java.net.URLEncoder.encode(\"asdf\", StandardCharsets.UTF_8);\n"; //$NON-NLS-1$ + } + return "java.net.URLEncoder.encode(\"asdf\", \"UTF-8\");\n"; //$NON-NLS-1$ + } + + @Override + public String toString() { + return "URLEncoder.encode()"; //$NON-NLS-1$ + } +} diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/AutomatedSuite.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/AutomatedSuite.java index 8e68d4be111..915eb8bed05 100644 --- a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/AutomatedSuite.java +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/AutomatedSuite.java @@ -40,6 +40,9 @@ import org.eclipse.jdt.ui.tests.model.ContentProviderTests; import org.eclipse.jdt.ui.tests.packageview.PackageExplorerTests; import org.eclipse.jdt.ui.tests.quickfix.QuickFixTestSuite; +import org.eclipse.jdt.ui.tests.quickfix.Java10.QuickFixJava10TestSuite; +import org.eclipse.jdt.ui.tests.quickfix.Java22.QuickFixJava22TestSuite; +import org.eclipse.jdt.ui.tests.quickfix.Java8.QuickFixJava8TestSuite; import org.eclipse.jdt.ui.tests.refactoring.RefactoringTests; import org.eclipse.jdt.ui.tests.search.SearchTest; import org.eclipse.jdt.ui.tests.views.SmokeViewsTest; @@ -59,6 +62,9 @@ CoreTests.class, CoreTestSuite.class, QuickFixTestSuite.class, + QuickFixJava8TestSuite.class, + QuickFixJava10TestSuite.class, + QuickFixJava22TestSuite.class, NewJavaProjectWizardTest.class, NewTypeWizardTest.class, diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/jarexport/FatJarExportTests.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/jarexport/FatJarExportTests.java index c28cc193745..1a3be6ecefe 100644 --- a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/jarexport/FatJarExportTests.java +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/jarexport/FatJarExportTests.java @@ -36,7 +36,6 @@ import org.junit.After; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; @@ -89,6 +88,7 @@ import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.ui.jarpackager.IJarExportRunnable; import org.eclipse.jdt.ui.jarpackager.JarPackageData; +import org.eclipse.jdt.ui.tests.core.rules.Java1d8ProjectTestSetup; import org.eclipse.jdt.ui.tests.core.rules.ProjectTestSetup; import org.eclipse.jdt.internal.ui.JavaPlugin; @@ -104,18 +104,22 @@ public class FatJarExportTests { + private static final String TEST_SETUP_PROJECT= "TestSetupProject1d8"; + private static final String TEST_SETUP_PROJECT_MYLIB_STDOUT_JAR= TEST_SETUP_PROJECT+"/mylib_stdout.jar"; + private static final String TEST_SETUP_PROJECT_OTHEROUT= TEST_SETUP_PROJECT+"/otherout"; + private static final String TEST_SETUP_PROJECT_MYLIB_SIG_JAR= TEST_SETUP_PROJECT+"/mylib_sig.jar"; + private static final String TEST_SETUP_PROJECT_CF= TEST_SETUP_PROJECT+"/cf"; + private static final String CREATE_RUNNABLE_JAR_FOR_PROJECT_TEST_SETUP_PROJECT= "Create Runnable Jar for Project TestSetupProject1d8"; + private static final String TEST_SETUP_PROJECT_BIN= TEST_SETUP_PROJECT+"/bin"; + @Rule - public ProjectTestSetup pts=new ProjectTestSetup(); + public ProjectTestSetup pts=new Java1d8ProjectTestSetup(); @Rule public TestName tn=new TestName(); private static final int JAVA_RUN_TIMEOUT= 300; // 10th of a second - @BeforeClass - public static void setUpTest() { - } - private IJavaProject fProject; private IPackageFragmentRoot fMainRoot; @@ -465,7 +469,7 @@ private static void assertAntScript(JarPackageData data, IPath antScriptLocation private static void assertAntScriptCopy(String archiveName, IPath antScriptLocation, String[] filesets, String[] zipfilesets) throws Exception { String subfolderName= archiveName.replaceFirst("^(.*)[.]jar$", "$1_lib"); //$NON-NLS-1$//$NON-NLS-2$ - String projectNameValue= "Create Runnable Jar for Project TestSetupProject"; //$NON-NLS-1$ + String projectNameValue= "Create Runnable Jar for Project TestSetupProject1d8"; //$NON-NLS-1$ projectNameValue+= " with libraries in sub-folder"; //$NON-NLS-1$ Element xmlProject= readXML(antScriptLocation); @@ -529,7 +533,7 @@ private static void assertAntScriptCopy(String archiveName, IPath antScriptLocat } private static void assertAntScriptPackage(String archiveName, IPath antScriptLocation, String[] filesets, String[] zipfilesets) throws Exception { - String projectNameValue= "Create Runnable Jar for Project TestSetupProject"; //$NON-NLS-1$ + String projectNameValue= CREATE_RUNNABLE_JAR_FOR_PROJECT_TEST_SETUP_PROJECT; //$NON-NLS-1$ projectNameValue+= " with Jar-in-Jar Loader"; //$NON-NLS-1$ Element xmlProject= readXML(antScriptLocation); @@ -597,7 +601,7 @@ private static void assertAntScriptPackage(String archiveName, IPath antScriptLo } private static void assertAntScriptExtract(String archiveName, IPath antScriptLocation, String[] filesets, String[] zipfilesets) throws Exception { - String projectNameValue= "Create Runnable Jar for Project TestSetupProject"; //$NON-NLS-1$ + String projectNameValue= "Create Runnable Jar for Project TestSetupProject1d8"; //$NON-NLS-1$ Element xmlProject= readXML(antScriptLocation); assertEquals("project", xmlProject.getNodeName()); //$NON-NLS-1$ @@ -666,7 +670,6 @@ private static Element readXML(IPath xmlFilePath) throws Exception { DocumentBuilder parser= XmlProcessorFactoryJdtJunit.createDocumentBuilderFactoryWithErrorOnDOCTYPE().newDocumentBuilder(); parser.setErrorHandler(new DefaultHandler()); Element root= parser.parse(new InputSource(in)).getDocumentElement(); - in.close(); return root; } @@ -684,21 +687,21 @@ public void exportSameSrcRoot() throws Exception { JarPackageData data= createAndRunFatJar(fProject, getName(), true, new ExtractLibraryHandler()); assertAntScript(data, antScriptLocation(getName()), new ExtractLibraryHandler(), - new String[] { "TestSetupProject/bin" }, //$NON-NLS-1$ - new String[] { "rtstubs15.jar" }); //$NON-NLS-1$ + new String[] { TEST_SETUP_PROJECT_BIN }, //$NON-NLS-1$ + new String[] { "rtstubs18.jar" }); //$NON-NLS-1$ // Jar-in-Jar loader data= createAndRunFatJar(fProject, getName() + "_JiJ", true, new PackageLibraryHandler()); //$NON-NLS-1$ assertAntScript(data, antScriptLocation(getName() + "_JiJ"), //$NON-NLS-1$ new PackageLibraryHandler(), - new String[] { "TestSetupProject/bin" }, //$NON-NLS-1$ - new String[] { "rtstubs15.jar" }); //$NON-NLS-1$ + new String[] { TEST_SETUP_PROJECT_BIN }, //$NON-NLS-1$ + new String[] { "rtstubs18.jar" }); //$NON-NLS-1$ // sub-folder libraries data= createAndRunFatJar(fProject, getName() + "_SL", true, new CopyLibraryHandler()); //$NON-NLS-1$ assertAntScript(data, antScriptLocation(getName() + "_SL"), //$NON-NLS-1$ - new CopyLibraryHandler(), new String[] { "TestSetupProject/bin" }, //$NON-NLS-1$ - new String[] { "rtstubs15.jar" }); //$NON-NLS-1$ + new CopyLibraryHandler(), new String[] { TEST_SETUP_PROJECT_BIN }, //$NON-NLS-1$ + new String[] { "rtstubs18.jar" }); //$NON-NLS-1$ } finally { pack.delete(true, null); } @@ -714,21 +717,21 @@ public void exportSrcRootWithOutputFolder() throws Exception { JarPackageData data= createAndRunFatJar(fProject, getName(), true, new ExtractLibraryHandler()); assertAntScript(data, antScriptLocation(getName()), new ExtractLibraryHandler(), - new String[] { "TestSetupProject/bin", "TestSetupProject/otherout" },//$NON-NLS-1$ //$NON-NLS-2$ - new String[] { "rtstubs15.jar" }); //$NON-NLS-1$ + new String[] { TEST_SETUP_PROJECT_BIN, TEST_SETUP_PROJECT_OTHEROUT },//$NON-NLS-1$ //$NON-NLS-2$ + new String[] { "rtstubs18.jar" }); //$NON-NLS-1$ // Jar-in-Jar loader data= createAndRunFatJar(fProject, getName() + "_JiJ", true, new PackageLibraryHandler()); //$NON-NLS-1$ assertAntScript(data, antScriptLocation(getName() + "_JiJ"), //$NON-NLS-1$ new PackageLibraryHandler(), - new String[] { "TestSetupProject/bin", "TestSetupProject/otherout" },//$NON-NLS-2$ //$NON-NLS-1$ - new String[] { "rtstubs15.jar" }); //$NON-NLS-1$ + new String[] { TEST_SETUP_PROJECT_BIN, TEST_SETUP_PROJECT_OTHEROUT },//$NON-NLS-2$ //$NON-NLS-1$ + new String[] { "rtstubs18.jar" }); //$NON-NLS-1$ // sub-folder libraries data= createAndRunFatJar(fProject, getName() + "_SL", true, new CopyLibraryHandler()); //$NON-NLS-1$ assertAntScript(data, antScriptLocation(getName() + "_SL"), //$NON-NLS-1$ - new CopyLibraryHandler(), new String[] { "TestSetupProject/bin", "TestSetupProject/otherout" },//$NON-NLS-2$ //$NON-NLS-1$ - new String[] { "rtstubs15.jar" }); //$NON-NLS-1$ + new CopyLibraryHandler(), new String[] { TEST_SETUP_PROJECT_BIN, TEST_SETUP_PROJECT_OTHEROUT },//$NON-NLS-2$ //$NON-NLS-1$ + new String[] { "rtstubs18.jar" }); //$NON-NLS-1$ } finally { JavaProjectHelper.removeSourceContainer(fProject, root.getElementName()); } @@ -744,21 +747,21 @@ public void exportOtherSrcRoot() throws Exception { JarPackageData data= createAndRunFatJar(fProject, getName(), true, new ExtractLibraryHandler()); assertAntScript(data, antScriptLocation(getName()), new ExtractLibraryHandler(), - new String[] { "TestSetupProject/bin" }, new String[] { "rtstubs15.jar" }); //$NON-NLS-1$ //$NON-NLS-2$ + new String[] { TEST_SETUP_PROJECT_BIN }, new String[] { "rtstubs18.jar" }); //$NON-NLS-1$ //$NON-NLS-2$ // Jar-in-Jar loader data= createAndRunFatJar(fProject, getName() + "_JiJ", true, new PackageLibraryHandler()); //$NON-NLS-1$ assertAntScript(data, antScriptLocation(getName() + "_JiJ"), //$NON-NLS-1$ new PackageLibraryHandler(), - new String[] { "TestSetupProject/bin" }, //$NON-NLS-1$ - new String[] { "rtstubs15.jar" }); //$NON-NLS-1$ + new String[] { TEST_SETUP_PROJECT_BIN }, //$NON-NLS-1$ + new String[] { "rtstubs18.jar" }); //$NON-NLS-1$ // sub-folder libraries data= createAndRunFatJar(fProject, getName() + "_SL", true, new CopyLibraryHandler()); //$NON-NLS-1$ assertAntScript(data, antScriptLocation(getName() + "_SL"), //$NON-NLS-1$ new CopyLibraryHandler(), - new String[] { "TestSetupProject/bin" }, //$NON-NLS-1$ - new String[] { "rtstubs15.jar" }); //$NON-NLS-1$ + new String[] { TEST_SETUP_PROJECT_BIN }, //$NON-NLS-1$ + new String[] { "rtstubs18.jar" }); //$NON-NLS-1$ } finally { JavaProjectHelper.removeSourceContainer(fProject, root.getElementName()); } @@ -779,21 +782,21 @@ public void exportOtherProject() throws Exception { JarPackageData data= createAndRunFatJar(fProject, getName(), true, new ExtractLibraryHandler()); assertAntScript(data, antScriptLocation(getName()), new ExtractLibraryHandler(), - new String[] { "TestSetupProject/bin", "OtherProject/bin" }, new String[] { "rtstubs15.jar" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + new String[] { TEST_SETUP_PROJECT_BIN, "OtherProject/bin" }, new String[] { "rtstubs18.jar" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ // Jar-in-Jar loader data= createAndRunFatJar(fProject, getName() + "_JiJ", true, new PackageLibraryHandler()); //$NON-NLS-1$ assertAntScript(data, antScriptLocation(getName() + "_JiJ"), //$NON-NLS-1$ new PackageLibraryHandler(), - new String[] { "TestSetupProject/bin", "OtherProject/bin" },//$NON-NLS-1$ //$NON-NLS-2$ - new String[] { "rtstubs15.jar" }); //$NON-NLS-1$ + new String[] { TEST_SETUP_PROJECT_BIN, "OtherProject/bin" },//$NON-NLS-1$ //$NON-NLS-2$ + new String[] { "rtstubs18.jar" }); //$NON-NLS-1$ // sub-folder libraries data= createAndRunFatJar(fProject, getName() + "_SL", true, new CopyLibraryHandler()); //$NON-NLS-1$ assertAntScript(data, antScriptLocation(getName() + "_SL"), //$NON-NLS-1$ new CopyLibraryHandler(), - new String[] { "TestSetupProject/bin", "OtherProject/bin" },//$NON-NLS-1$ //$NON-NLS-2$ - new String[] { "rtstubs15.jar" }); //$NON-NLS-1$ + new String[] { TEST_SETUP_PROJECT_BIN, "OtherProject/bin" },//$NON-NLS-1$ //$NON-NLS-2$ + new String[] { "rtstubs18.jar" }); //$NON-NLS-1$ } finally { JavaProjectHelper.removeFromClasspath(fProject, otherProject.getProject().getFullPath()); JavaProjectHelper.delete(otherProject); @@ -809,22 +812,22 @@ public void exportInternalLib() throws Exception { JarPackageData data= createAndRunFatJar(fProject, getName(), true, new ExtractLibraryHandler()); assertAntScript(data, antScriptLocation(getName()), new ExtractLibraryHandler(), - new String[] { "TestSetupProject/bin" }, //$NON-NLS-1$ - new String[] { "rtstubs15.jar", "TestSetupProject/mylib_stdout.jar" }); //$NON-NLS-1$ //$NON-NLS-2$ + new String[] { TEST_SETUP_PROJECT_BIN }, //$NON-NLS-1$ + new String[] { "rtstubs18.jar", TEST_SETUP_PROJECT_MYLIB_STDOUT_JAR }); //$NON-NLS-1$ //$NON-NLS-2$ // Jar-in-Jar loader data= createAndRunFatJar(fProject, getName() + "_JiJ", true, new PackageLibraryHandler()); //$NON-NLS-1$ assertAntScript(data, antScriptLocation(getName() + "_JiJ"), //$NON-NLS-1$ new PackageLibraryHandler(), - new String[] { "TestSetupProject/bin" },//$NON-NLS-1$ - new String[] { "rtstubs15.jar", "mylib_stdout.jar" }); //$NON-NLS-1$ //$NON-NLS-2$ + new String[] { TEST_SETUP_PROJECT_BIN },//$NON-NLS-1$ + new String[] { "rtstubs18.jar", "mylib_stdout.jar" }); //$NON-NLS-1$ //$NON-NLS-2$ // sub-folder libraries data= createAndRunFatJar(fProject, getName() + "_SL", true, new CopyLibraryHandler()); //$NON-NLS-1$ assertAntScript(data, antScriptLocation(getName() + "_SL"), //$NON-NLS-1$ new CopyLibraryHandler(), - new String[] { "TestSetupProject/bin" },//$NON-NLS-1$ - new String[] { "rtstubs15.jar", "mylib_stdout.jar" }); //$NON-NLS-1$ //$NON-NLS-2$ + new String[] { TEST_SETUP_PROJECT_BIN },//$NON-NLS-1$ + new String[] { "rtstubs18.jar", "mylib_stdout.jar" }); //$NON-NLS-1$ //$NON-NLS-2$ } finally { JavaProjectHelper.removeFromClasspath(fProject, root.getPath()); } @@ -839,21 +842,21 @@ public void exportInternalLib_UncompressedJar() throws Exception { JarPackageData data= createAndRunFatJar(fProject, getName(), false, new ExtractLibraryHandler()); assertAntScript(data, antScriptLocation(getName()), new ExtractLibraryHandler(), - new String[] { "TestSetupProject/bin" }, new String[] { "rtstubs15.jar", "TestSetupProject/mylib_stdout.jar" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + new String[] { TEST_SETUP_PROJECT_BIN }, new String[] { "rtstubs18.jar", TEST_SETUP_PROJECT_MYLIB_STDOUT_JAR }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ // Jar-in-Jar loader data= createAndRunFatJar(fProject, getName() + "_JiJ", true, new PackageLibraryHandler()); //$NON-NLS-1$ assertAntScript(data, antScriptLocation(getName() + "_JiJ"), //$NON-NLS-1$ new PackageLibraryHandler(), - new String[] { "TestSetupProject/bin" }, //$NON-NLS-1$ - new String[] { "rtstubs15.jar", "mylib_stdout.jar" }); //$NON-NLS-1$ //$NON-NLS-2$ + new String[] { TEST_SETUP_PROJECT_BIN }, //$NON-NLS-1$ + new String[] { "rtstubs18.jar", "mylib_stdout.jar" }); //$NON-NLS-1$ //$NON-NLS-2$ // sub-folder libraries data= createAndRunFatJar(fProject, getName() + "_SL", true, new CopyLibraryHandler()); //$NON-NLS-1$ assertAntScript(data, antScriptLocation(getName() + "_SL"), //$NON-NLS-1$ new CopyLibraryHandler(), - new String[] { "TestSetupProject/bin" }, //$NON-NLS-1$ - new String[] { "rtstubs15.jar", "mylib_stdout.jar" }); //$NON-NLS-1$ //$NON-NLS-2$ + new String[] { TEST_SETUP_PROJECT_BIN }, //$NON-NLS-1$ + new String[] { "rtstubs18.jar", "mylib_stdout.jar" }); //$NON-NLS-1$ //$NON-NLS-2$ } finally { JavaProjectHelper.removeFromClasspath(fProject, root.getPath()); } @@ -869,20 +872,20 @@ public void exportExternalLib() throws Exception { JarPackageData data= createAndRunFatJar(fProject, getName(), true, new ExtractLibraryHandler()); assertAntScript(data, antScriptLocation(getName()), new ExtractLibraryHandler(), - new String[] { "TestSetupProject/bin" }, new String[] { "rtstubs15.jar", "testresources/mylib_stdout.jar" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + new String[] { TEST_SETUP_PROJECT_BIN }, new String[] { "rtstubs18.jar", "testresources/mylib_stdout.jar" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ // Jar-in-Jar loader data= createAndRunFatJar(fProject, getName() + "_JiJ", true, new PackageLibraryHandler()); //$NON-NLS-1$ assertAntScript(data, antScriptLocation(getName() + "_JiJ"), //$NON-NLS-1$ new PackageLibraryHandler(), - new String[] { "TestSetupProject/bin" }, //$NON-NLS-1$ - new String[] { "rtstubs15.jar", "mylib_stdout.jar" }); //$NON-NLS-1$ //$NON-NLS-2$ + new String[] { TEST_SETUP_PROJECT_BIN }, //$NON-NLS-1$ + new String[] { "rtstubs18.jar", "mylib_stdout.jar" }); //$NON-NLS-1$ //$NON-NLS-2$ // sub-folder libraries data= createAndRunFatJar(fProject, getName() + "_SL", true, new CopyLibraryHandler()); //$NON-NLS-1$ assertAntScript(data, antScriptLocation(getName() + "_SL"), //$NON-NLS-1$ - new CopyLibraryHandler(), new String[] { "TestSetupProject/bin" }, //$NON-NLS-1$ - new String[] { "rtstubs15.jar", "mylib_stdout.jar" }); //$NON-NLS-1$ //$NON-NLS-2$ + new CopyLibraryHandler(), new String[] { "TestSetupProject1d8/bin" }, //$NON-NLS-1$ + new String[] { "rtstubs18.jar", "mylib_stdout.jar" }); //$NON-NLS-1$ //$NON-NLS-2$ } finally { JavaProjectHelper.removeFromClasspath(fProject, root.getPath()); } @@ -898,20 +901,20 @@ public void classFolder() throws Exception { JarPackageData data= createAndRunFatJar(fProject, getName(), true, new ExtractLibraryHandler()); assertAntScript(data, antScriptLocation(getName()), new ExtractLibraryHandler(), - new String[] { "TestSetupProject/bin", "TestSetupProject/cf" }, new String[] { "rtstubs15.jar" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + new String[] { TEST_SETUP_PROJECT_BIN, TEST_SETUP_PROJECT_CF }, new String[] { "rtstubs18.jar" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ // Jar-in-Jar loader data= createAndRunFatJar(fProject, getName() + "_JiJ", true, new PackageLibraryHandler()); //$NON-NLS-1$ assertAntScript(data, antScriptLocation(getName() + "_JiJ"), //$NON-NLS-1$ new PackageLibraryHandler(), - new String[] { "TestSetupProject/bin", "TestSetupProject/cf" },//$NON-NLS-1$ //$NON-NLS-2$ - new String[] { "rtstubs15.jar" }); //$NON-NLS-1$ + new String[] { TEST_SETUP_PROJECT_BIN, TEST_SETUP_PROJECT_CF },//$NON-NLS-1$ //$NON-NLS-2$ + new String[] { "rtstubs18.jar" }); //$NON-NLS-1$ // sub-folder libraries data= createAndRunFatJar(fProject, getName() + "_SL", true, new CopyLibraryHandler()); //$NON-NLS-1$ assertAntScript(data, antScriptLocation(getName() + "_SL"), //$NON-NLS-1$ - new CopyLibraryHandler(), new String[] { "TestSetupProject/bin", "TestSetupProject/cf" },//$NON-NLS-1$ //$NON-NLS-2$ - new String[] { "rtstubs15.jar" }); //$NON-NLS-1$ + new CopyLibraryHandler(), new String[] { TEST_SETUP_PROJECT_BIN, TEST_SETUP_PROJECT_CF },//$NON-NLS-1$ //$NON-NLS-2$ + new String[] { "rtstubs18.jar" }); //$NON-NLS-1$ } finally { JavaProjectHelper.removeFromClasspath(fProject, root.getPath()); } @@ -928,20 +931,20 @@ public void variable() throws Exception { JarPackageData data= createAndRunFatJar(fProject, getName(), true, new ExtractLibraryHandler()); assertAntScript(data, antScriptLocation(getName()), new ExtractLibraryHandler(), - new String[] { "TestSetupProject/bin" }, new String[] { "rtstubs15.jar", "testresources/mylib_stdout.jar" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + new String[] { TEST_SETUP_PROJECT_BIN }, new String[] { "rtstubs18.jar", "testresources/mylib_stdout.jar" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ // Jar-in-Jar loader data= createAndRunFatJar(fProject, getName() + "_JiJ", true, new PackageLibraryHandler()); //$NON-NLS-1$ assertAntScript(data, antScriptLocation(getName() + "_JiJ"), //$NON-NLS-1$ new PackageLibraryHandler(), - new String[] { "TestSetupProject/bin" }, //$NON-NLS-1$ - new String[] { "rtstubs15.jar", "mylib_stdout.jar" }); //$NON-NLS-1$ //$NON-NLS-2$ + new String[] { TEST_SETUP_PROJECT_BIN }, //$NON-NLS-1$ + new String[] { "rtstubs18.jar", "mylib_stdout.jar" }); //$NON-NLS-1$ //$NON-NLS-2$ // sub-folder libraries data= createAndRunFatJar(fProject, getName() + "_SL", true, new CopyLibraryHandler()); //$NON-NLS-1$ assertAntScript(data, antScriptLocation(getName() + "_SL"), //$NON-NLS-1$ - new CopyLibraryHandler(), new String[] { "TestSetupProject/bin" }, //$NON-NLS-1$ - new String[] { "rtstubs15.jar", "mylib_stdout.jar" }); //$NON-NLS-1$ //$NON-NLS-2$ + new CopyLibraryHandler(), new String[] { TEST_SETUP_PROJECT_BIN }, //$NON-NLS-1$ + new String[] { "rtstubs18.jar", "mylib_stdout.jar" }); //$NON-NLS-1$ //$NON-NLS-2$ } finally { JavaProjectHelper.removeFromClasspath(fProject, new Path("MYLIB")); //$NON-NLS-1$ } @@ -957,20 +960,20 @@ public void signedLibs() throws Exception { JarPackageData data= createAndRunFatJar(fProject, getName(), true, new ExtractLibraryHandler()); assertAntScript(data, antScriptLocation(getName()), new ExtractLibraryHandler(), - new String[] { "TestSetupProject/bin" }, new String[] { "rtstubs15.jar", "TestSetupProject/mylib_sig.jar" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + new String[] { TEST_SETUP_PROJECT_BIN }, new String[] { "rtstubs18.jar", TEST_SETUP_PROJECT_MYLIB_SIG_JAR }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ // Jar-in-Jar loader data= createAndRunFatJar(fProject, getName() + "_JiJ", true, new PackageLibraryHandler()); //$NON-NLS-1$ assertAntScript(data, antScriptLocation(getName() + "_JiJ"), //$NON-NLS-1$ new PackageLibraryHandler(), - new String[] { "TestSetupProject/bin" }, //$NON-NLS-1$ - new String[] { "rtstubs15.jar", "mylib_sig.jar" }); //$NON-NLS-1$ //$NON-NLS-2$ + new String[] { TEST_SETUP_PROJECT_BIN }, //$NON-NLS-1$ + new String[] { "rtstubs18.jar", "mylib_sig.jar" }); //$NON-NLS-1$ //$NON-NLS-2$ // sub-folder libraries data= createAndRunFatJar(fProject, getName() + "_SL", true, new CopyLibraryHandler()); //$NON-NLS-1$ assertAntScript(data, antScriptLocation(getName() + "_SL"), //$NON-NLS-1$ - new CopyLibraryHandler(), new String[] { "TestSetupProject/bin" }, //$NON-NLS-1$ - new String[] { "rtstubs15.jar", "mylib_sig.jar" }); //$NON-NLS-1$ //$NON-NLS-2$ + new CopyLibraryHandler(), new String[] { TEST_SETUP_PROJECT_BIN }, //$NON-NLS-1$ + new String[] { "rtstubs18.jar", "mylib_sig.jar" }); //$NON-NLS-1$ //$NON-NLS-2$ } finally { JavaProjectHelper.removeFromClasspath(fProject, root.getPath()); } @@ -987,20 +990,20 @@ public void externalClassFolder() throws Exception { JarPackageData data= createAndRunFatJar(fProject, getName(), true, new ExtractLibraryHandler()); assertAntScript(data, antScriptLocation(getName()), new ExtractLibraryHandler(), - new String[] { "TestSetupProject/bin", "testresources/externalClassFolder" }, new String[] { "rtstubs15.jar" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + new String[] { TEST_SETUP_PROJECT_BIN, "testresources/externalClassFolder" }, new String[] { "rtstubs18.jar" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ // Jar-in-Jar loader data= createAndRunFatJar(fProject, getName() + "_JiJ", true, new PackageLibraryHandler()); //$NON-NLS-1$ assertAntScript(data, antScriptLocation(getName() + "_JiJ"), //$NON-NLS-1$ new PackageLibraryHandler(), - new String[] { "TestSetupProject/bin", "testresources/externalClassFolder" }, //$NON-NLS-1$ - new String[] { "rtstubs15.jar" }); //$NON-NLS-1$ + new String[] { TEST_SETUP_PROJECT_BIN, "testresources/externalClassFolder" }, //$NON-NLS-1$ + new String[] { "rtstubs18.jar" }); //$NON-NLS-1$ // sub-folder libraries data= createAndRunFatJar(fProject, getName() + "_SL", true, new CopyLibraryHandler()); //$NON-NLS-1$ assertAntScript(data, antScriptLocation(getName() + "_SL"), //$NON-NLS-1$ - new CopyLibraryHandler(), new String[] { "TestSetupProject/bin", "testresources/externalClassFolder" }, //$NON-NLS-1$ - new String[] { "rtstubs15.jar" }); //$NON-NLS-1$ + new CopyLibraryHandler(), new String[] { TEST_SETUP_PROJECT_BIN, "testresources/externalClassFolder" }, //$NON-NLS-1$ + new String[] { "rtstubs18.jar" }); //$NON-NLS-1$ } finally { JavaProjectHelper.removeFromClasspath(fProject, externalRoot.getPath()); } diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/jarexport/PlainJarExportTests.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/jarexport/PlainJarExportTests.java index 3dd9d51766e..5026e4a45fc 100644 --- a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/jarexport/PlainJarExportTests.java +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/jarexport/PlainJarExportTests.java @@ -28,7 +28,6 @@ import org.junit.After; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; @@ -52,21 +51,18 @@ import org.eclipse.jdt.ui.jarpackager.IJarExportRunnable; import org.eclipse.jdt.ui.jarpackager.JarPackageData; +import org.eclipse.jdt.ui.tests.core.rules.Java1d8ProjectTestSetup; import org.eclipse.jdt.ui.tests.core.rules.ProjectTestSetup; import org.eclipse.jdt.internal.ui.jarpackager.JarPackagerUtil; public class PlainJarExportTests { @Rule - public ProjectTestSetup pts= new ProjectTestSetup(); + public ProjectTestSetup pts= new Java1d8ProjectTestSetup(); @Rule public TestName tn= new TestName(); - @BeforeClass - public static void setUpTest() { - } - private IJavaProject fProject; private IPackageFragmentRoot fMainRoot; private ICompilationUnit fCU; diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/AssistQuickFixTest12.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/AssistQuickFixTest12.java index a6b1707192c..d408f96ec0e 100644 --- a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/AssistQuickFixTest12.java +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/AssistQuickFixTest12.java @@ -65,7 +65,7 @@ public void testSplitSwitchCaseStatement() throws Exception { module test { } """; - IPackageFragment def= fSourceFolder.createPackageFragment("", false, null); + IPackageFragment def= fSourceFolder.createPackageFragment("test", false, null); def.createCompilationUnit("module-info.java", str, false, null); IPackageFragment pack= fSourceFolder.createPackageFragment("test", false, null); @@ -82,7 +82,7 @@ public static void foo(Day day) { } } } - + enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY; } @@ -113,7 +113,7 @@ public static void foo(Day day) { } } } - + enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY; } @@ -133,7 +133,7 @@ public void testSplitSwitchCaseLabelRuleStatement() throws Exception { module test { } """; - IPackageFragment def= fSourceFolder.createPackageFragment("", false, null); + IPackageFragment def= fSourceFolder.createPackageFragment("test", false, null); def.createCompilationUnit("module-info.java", str, false, null); IPackageFragment pack= fSourceFolder.createPackageFragment("test", false, null); @@ -148,7 +148,7 @@ public static void foo(Day day) { }; } } - + enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY; } @@ -173,7 +173,7 @@ public static void foo(Day day) { }; } } - + enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY; } diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/Java10/ExplicitEncodingCleanUpTest.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/Java10/ExplicitEncodingCleanUpTest.java new file mode 100644 index 00000000000..c1f05c344ca --- /dev/null +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/Java10/ExplicitEncodingCleanUpTest.java @@ -0,0 +1,132 @@ +/******************************************************************************* + * Copyright (c) 2024 Carsten Hammer and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.quickfix.Java10; + +import java.nio.charset.UnsupportedCharsetException; +import java.util.Hashtable; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; + +import org.eclipse.jdt.testplugin.TestOptions; + +import org.eclipse.core.runtime.CoreException; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.JavaCore; +import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants; + +import org.eclipse.jdt.internal.corext.fix.CleanUpConstants; + +import org.eclipse.jdt.ui.tests.quickfix.rules.AbstractEclipseJava; +import org.eclipse.jdt.ui.tests.quickfix.rules.EclipseJava10; + +import org.eclipse.jdt.internal.ui.JavaPlugin; + +public class ExplicitEncodingCleanUpTest { + + @BeforeEach + protected void setUp() throws Exception,UnsupportedCharsetException { + Hashtable defaultOptions= TestOptions.getDefaultOptions(); + defaultOptions.put(DefaultCodeFormatterConstants.FORMATTER_LINE_SPLIT, Integer.toString(120)); + JavaCore.setOptions(defaultOptions); + TestOptions.initializeCodeGenerationOptions(); + // Use load since restore doesn't really restore the defaults. + JavaPlugin.getDefault().getCodeTemplateStore().load(); + } + + @RegisterExtension + AbstractEclipseJava context= new EclipseJava10(); + + @ParameterizedTest + @EnumSource(ExplicitEncodingPatternsKeepBehavior.class) + public void testExplicitEncodingParametrizedKeepBehavior(ExplicitEncodingPatternsKeepBehavior test) throws CoreException { + IPackageFragment pack= context.getfSourceFolder().createPackageFragment("test1", false, null); + ICompilationUnit cu= pack.createCompilationUnit("E1.java", test.given, false, null); + context.enable(CleanUpConstants.EXPLICITENCODING_CLEANUP); + context.enable(CleanUpConstants.EXPLICITENCODING_KEEP_BEHAVIOR); + context.disable(CleanUpConstants.EXPLICITENCODING_INSERT_UTF8); + context.disable(CleanUpConstants.EXPLICITENCODING_AGGREGATE_TO_UTF8); +// context.assertRefactoringResultAsExpected(new ICompilationUnit[] { cu }, new String[] { test.expected }, null); + context.enable(CleanUpConstants.REMOVE_UNNECESSARY_NLS_TAGS); + context.assertRefactoringResultAsExpected(new ICompilationUnit[] { cu }, new String[] { test.expected }, null); + } + + @ParameterizedTest + @EnumSource(ExplicitEncodingPatternsPreferUTF8.class) + public void testExplicitEncodingParametrizedPreferUTF8(ExplicitEncodingPatternsPreferUTF8 test) throws CoreException { + IPackageFragment pack= context.getfSourceFolder().createPackageFragment("test1", false, null); + ICompilationUnit cu= pack.createCompilationUnit("E1.java", test.given, false, null); + context.enable(CleanUpConstants.EXPLICITENCODING_CLEANUP); + context.disable(CleanUpConstants.EXPLICITENCODING_KEEP_BEHAVIOR); + context.enable(CleanUpConstants.EXPLICITENCODING_INSERT_UTF8); + context.disable(CleanUpConstants.EXPLICITENCODING_AGGREGATE_TO_UTF8); + context.assertRefactoringResultAsExpected(new ICompilationUnit[] { cu }, new String[] { test.expected }, null); + } + +// @Disabled("Not Implemented") + @ParameterizedTest + @EnumSource(ExplicitEncodingPatternsAggregateUTF8.class) + public void testExplicitEncodingParametrizedAggregateUTF8(ExplicitEncodingPatternsAggregateUTF8 test) throws CoreException { + IPackageFragment pack= context.getfSourceFolder().createPackageFragment("test1", false, null); + ICompilationUnit cu= pack.createCompilationUnit("E1.java", test.given, false, null); + context.enable(CleanUpConstants.EXPLICITENCODING_CLEANUP); + context.disable(CleanUpConstants.EXPLICITENCODING_KEEP_BEHAVIOR); + context.disable(CleanUpConstants.EXPLICITENCODING_INSERT_UTF8); + context.enable(CleanUpConstants.EXPLICITENCODING_AGGREGATE_TO_UTF8); + context.assertRefactoringResultAsExpected(new ICompilationUnit[] { cu }, new String[] { test.expected }, null); + } + + @Test + public void testExplicitEncodingdonttouch() throws CoreException { + IPackageFragment pack= context.getfSourceFolder().createPackageFragment("test1", false, null); + ICompilationUnit cu= pack.createCompilationUnit("E2.java", + """ + package test1; + + import java.io.ByteArrayOutputStream; + import java.io.InputStreamReader; + import java.io.IOException; + import java.nio.charset.Charset; + import java.io.FileInputStream; + import java.io.FileNotFoundException; + import java.io.UnsupportedEncodingException; + + public class E2 { + void method() throws UnsupportedEncodingException, IOException { + String s="asdf"; //$NON-NLS-1$ + byte[] bytes= s.getBytes(Charset.defaultCharset()); + System.out.println(bytes.length); + ByteArrayOutputStream ba=new ByteArrayOutputStream(); + String result=ba.toString(Charset.defaultCharset().displayName()); + try ( + InputStreamReader is=new InputStreamReader(new FileInputStream(""), Charset.defaultCharset()); //$NON-NLS-1$ + ){ } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } + """, + false, null); + + context.enable(CleanUpConstants.EXPLICITENCODING_CLEANUP); + context.enable(CleanUpConstants.EXPLICITENCODING_KEEP_BEHAVIOR); + + context.assertRefactoringHasNoChange(new ICompilationUnit[] { cu }); + } +} diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/Java10/ExplicitEncodingPatternsAggregateUTF8.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/Java10/ExplicitEncodingPatternsAggregateUTF8.java new file mode 100644 index 00000000000..ed74fde51e0 --- /dev/null +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/Java10/ExplicitEncodingPatternsAggregateUTF8.java @@ -0,0 +1,1939 @@ +/******************************************************************************* + * Copyright (c) 2024 Carsten Hammer and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.quickfix.Java10; + +public enum ExplicitEncodingPatternsAggregateUTF8 { + + CHARSET(""" + package test1; + + import java.io.ByteArrayOutputStream; + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Reader; + import java.nio.charset.Charset; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + Charset cs1= Charset.forName("UTF-8"); + Charset cs1b= Charset.forName("Utf-8"); + Charset cs2= Charset.forName("UTF-16"); + Charset cs3= Charset.forName("UTF-16BE"); + Charset cs4= Charset.forName("UTF-16LE"); + Charset cs5= Charset.forName("ISO-8859-1"); + Charset cs6= Charset.forName("US-ASCII"); + String result= cs1.toString(); + } + } + } + """, + """ + package test1; + + import java.io.ByteArrayOutputStream; + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Reader; + import java.nio.charset.Charset; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + Charset cs1= Charset.forName("UTF-8"); + Charset cs1b= Charset.forName("Utf-8"); + Charset cs2= Charset.forName("UTF-16"); + Charset cs3= Charset.forName("UTF-16BE"); + Charset cs4= Charset.forName("UTF-16LE"); + Charset cs5= Charset.forName("ISO-8859-1"); + Charset cs6= Charset.forName("US-ASCII"); + String result= cs1.toString(); + } + } + } + """), + BYTEARRAYOUTSTREAM(""" + package test1; + + import java.io.ByteArrayOutputStream; + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Reader; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + ByteArrayOutputStream ba=new ByteArrayOutputStream(); + String result=ba.toString(); + ByteArrayOutputStream ba2=new ByteArrayOutputStream(); + String result2=ba2.toString("UTF-8"); + } + } + } + """, + + """ +package test1; + +import java.io.ByteArrayOutputStream; +import java.io.InputStreamReader; +import java.io.FileInputStream; +import java.io.FileReader; +import java.io.Reader; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.io.FileNotFoundException; + +public class E1 { + private static final Charset UTF_8 = StandardCharsets.UTF_8; + + void method(String filename) { + ByteArrayOutputStream ba=new ByteArrayOutputStream(); + String result=ba.toString(E1.UTF_8); + ByteArrayOutputStream ba2=new ByteArrayOutputStream(); + String result2=ba2.toString(E1.UTF_8); + } + } +} + """), + FILEREADER(""" + package test1; + + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Reader; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + try { + Reader is=new FileReader(filename); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } + } + """, + + """ +package test1; + +import java.io.InputStreamReader; +import java.io.FileInputStream; +import java.io.FileReader; +import java.io.Reader; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.io.FileNotFoundException; + +public class E1 { + private static final Charset UTF_8 = StandardCharsets.UTF_8; + + void method(String filename) { + try { + Reader is=new InputStreamReader(new FileInputStream(filename), E1.UTF_8); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } +} +"""), + FILEWRITER(""" + package test1; + + import java.io.FileWriter; + import java.io.Writer; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + try { + Writer fw=new FileWriter(filename); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } + } + """, + + """ +package test1; + +import java.io.FileWriter; +import java.io.OutputStreamWriter; +import java.io.Writer; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; + +public class E1 { + private static final Charset UTF_8 = StandardCharsets.UTF_8; + + void method(String filename) { + try { + Writer fw=new OutputStreamWriter(new FileOutputStream(filename), E1.UTF_8); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } +} + """), + INPUTSTREAMREADER( +""" +package test1; + +import java.io.InputStreamReader; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.UnsupportedEncodingException; + +public class E1 { + + void method(String filename) { + try { + // Standardkonstruktor ohne Encoding + InputStreamReader is1 = new InputStreamReader(new FileInputStream("file1.txt")); //$NON-NLS-1$ + + // String Literal Encodings, die nach StandardCharsets umgeschrieben werden sollten + InputStreamReader is2 = new InputStreamReader(new FileInputStream("file2.txt"), "UTF-8"); //$NON-NLS-1$ //$NON-NLS-2$ + InputStreamReader is3 = new InputStreamReader(new FileInputStream("file3.txt"), "ISO-8859-1"); //$NON-NLS-1$ //$NON-NLS-2$ + InputStreamReader is4 = new InputStreamReader(new FileInputStream("file4.txt"), "US-ASCII"); //$NON-NLS-1$ //$NON-NLS-2$ + + // String-basiertes Encoding, das in Charset umgeschrieben werden kann, jedoch ohne vordefinierte Konstante + InputStreamReader is5 = new InputStreamReader(new FileInputStream("file5.txt"), "UTF-16"); //$NON-NLS-1$ //$NON-NLS-2$ + + // String-basierte Encodings mit Groß-/Kleinschreibungsvarianten + InputStreamReader is6 = new InputStreamReader(new FileInputStream("file6.txt"), "utf-8"); //$NON-NLS-1$ //$NON-NLS-2$ + InputStreamReader is7 = new InputStreamReader(new FileInputStream("file7.txt"), "Utf-8"); //$NON-NLS-1$ //$NON-NLS-2$ + + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); // Sollte nach Cleanup entfernt werden + } + } + + void methodWithTryCatch(String filename) { + try { + // Variante, bei der UnsupportedEncodingException behandelt wird + InputStreamReader is8 = new InputStreamReader(new FileInputStream("file8.txt"), "UTF-8"); //$NON-NLS-1$ //$NON-NLS-2$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); // Sollte nach Cleanup entfernt werden + } + } + + void methodWithoutException(String filename) throws UnsupportedEncodingException, FileNotFoundException { + // Case ohne Try-Catch-Block, sollte Charset-Konstanten direkt ersetzen + InputStreamReader is9 = new InputStreamReader(new FileInputStream("file9.txt"), "UTF-8"); //$NON-NLS-1$ //$NON-NLS-2$ + } + + void methodWithVariableEncoding(String filename) throws UnsupportedEncodingException, FileNotFoundException { + // Case, bei dem das Encoding aus einer Variablen kommt, Cleanup sollte hier keine Änderungen machen + String encoding = "UTF-8"; //$NON-NLS-1$ + InputStreamReader is10 = new InputStreamReader(new FileInputStream("file10.txt"), encoding); //$NON-NLS-1$ + } + + void methodWithNonStandardEncoding(String filename) { + try { + // Case mit nicht vordefiniertem Charset, sollte keine Umwandlung in StandardCharsets erfolgen + InputStreamReader is11 = new InputStreamReader(new FileInputStream("file11.txt"), "windows-1252"); //$NON-NLS-1$ //$NON-NLS-2$ + } catch (FileNotFoundException | UnsupportedEncodingException e) { + e.printStackTrace(); + } + } + + // Methode mit "throws UnsupportedEncodingException" zur Prüfung des Cleanups + void methodWithThrows(String filename) throws FileNotFoundException, UnsupportedEncodingException { + InputStreamReader is3 = new InputStreamReader(new FileInputStream(filename), "UTF-8"); //$NON-NLS-1$ + } +} +""", + +""" +package test1; + +import java.io.InputStreamReader; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.io.FileInputStream; +import java.io.FileNotFoundException; + +public class E1 { + + private static final Charset UTF_16 = StandardCharsets.UTF_16; + private static final Charset US_ASCII = StandardCharsets.US_ASCII; + private static final Charset ISO_8859_1 = StandardCharsets.ISO_8859_1; + private static final Charset UTF_8 = StandardCharsets.UTF_8; + + void method(String filename) { + try { + // Standardkonstruktor ohne Encoding + InputStreamReader is1 = new InputStreamReader(new FileInputStream("file1.txt"), E1.UTF_8); //$NON-NLS-1$ + + // String Literal Encodings, die nach StandardCharsets umgeschrieben werden sollten + InputStreamReader is2 = new InputStreamReader(new FileInputStream("file2.txt"), E1.UTF_8); //$NON-NLS-1$ //$NON-NLS-2$ + InputStreamReader is3 = new InputStreamReader(new FileInputStream("file3.txt"), E1.ISO_8859_1); //$NON-NLS-1$ //$NON-NLS-2$ + InputStreamReader is4 = new InputStreamReader(new FileInputStream("file4.txt"), E1.US_ASCII); //$NON-NLS-1$ //$NON-NLS-2$ + + // String-basiertes Encoding, das in Charset umgeschrieben werden kann, jedoch ohne vordefinierte Konstante + InputStreamReader is5 = new InputStreamReader(new FileInputStream("file5.txt"), E1.UTF_16); //$NON-NLS-1$ //$NON-NLS-2$ + + // String-basierte Encodings mit Groß-/Kleinschreibungsvarianten + InputStreamReader is6 = new InputStreamReader(new FileInputStream("file6.txt"), E1.UTF_8); //$NON-NLS-1$ //$NON-NLS-2$ + InputStreamReader is7 = new InputStreamReader(new FileInputStream("file7.txt"), E1.UTF_8); //$NON-NLS-1$ //$NON-NLS-2$ + + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + + void methodWithTryCatch(String filename) { + try { + // Variante, bei der UnsupportedEncodingException behandelt wird + InputStreamReader is8 = new InputStreamReader(new FileInputStream("file8.txt"), E1.UTF_8); //$NON-NLS-1$ //$NON-NLS-2$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + + void methodWithoutException(String filename) throws FileNotFoundException { + // Case ohne Try-Catch-Block, sollte Charset-Konstanten direkt ersetzen + InputStreamReader is9 = new InputStreamReader(new FileInputStream("file9.txt"), E1.UTF_8); //$NON-NLS-1$ //$NON-NLS-2$ + } + + void methodWithVariableEncoding(String filename) throws UnsupportedEncodingException, FileNotFoundException { + // Case, bei dem das Encoding aus einer Variablen kommt, Cleanup sollte hier keine Änderungen machen + String encoding = "UTF-8"; //$NON-NLS-1$ + InputStreamReader is10 = new InputStreamReader(new FileInputStream("file10.txt"), encoding); //$NON-NLS-1$ + } + + void methodWithNonStandardEncoding(String filename) { + try { + // Case mit nicht vordefiniertem Charset, sollte keine Umwandlung in StandardCharsets erfolgen + InputStreamReader is11 = new InputStreamReader(new FileInputStream("file11.txt"), "windows-1252"); //$NON-NLS-1$ //$NON-NLS-2$ + } catch (FileNotFoundException | UnsupportedEncodingException e) { + e.printStackTrace(); + } + } + + // Methode mit "throws UnsupportedEncodingException" zur Prüfung des Cleanups + void methodWithThrows(String filename) throws FileNotFoundException { + InputStreamReader is3 = new InputStreamReader(new FileInputStream(filename), E1.UTF_8); //$NON-NLS-1$ + } +} +"""), + OUTPUTSTREAMWRITER( +""" +package test1; + +import java.io.FileOutputStream; +import java.io.OutputStreamWriter; +import java.io.FileNotFoundException; +import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; + +public class E1 { + private static final String ENCODING_UTF8 = "UTF-8"; // Konstante für Encoding + + void method(String filename) { + try { + // Standard-Konstruktor ohne Encoding + OutputStreamWriter os1 = new OutputStreamWriter(new FileOutputStream(filename)); + + // Konstruktor mit String-Encoding (UTF-8) -> muss durch StandardCharsets.UTF_8 ersetzt werden + OutputStreamWriter os2 = new OutputStreamWriter(new FileOutputStream(filename), "UTF-8"); // "UTF-8" als String-Literal + + // Konstruktor mit String-Encoding (ISO-8859-1) -> muss durch StandardCharsets.ISO_8859_1 ersetzt werden + OutputStreamWriter os3 = new OutputStreamWriter(new FileOutputStream(filename), "ISO-8859-1"); // "ISO-8859-1" als String-Literal + + // Konstruktor mit String-Encoding (US-ASCII) -> muss durch StandardCharsets.US_ASCII ersetzt werden + OutputStreamWriter os4 = new OutputStreamWriter(new FileOutputStream(filename), "US-ASCII"); // "US-ASCII" als String-Literal + + // Konstruktor mit String-Encoding (UTF-16) -> muss durch StandardCharsets.UTF_16 ersetzt werden + OutputStreamWriter os5 = new OutputStreamWriter(new FileOutputStream(filename), "UTF-16"); // "UTF-16" als String-Literal + + // Der Konstruktor mit einer benutzerdefinierten Konstante bleibt unverändert + OutputStreamWriter os6 = new OutputStreamWriter(new FileOutputStream(filename), ENCODING_UTF8); // bleibt unverändert + + // Fälle ohne Entsprechung in StandardCharsets (bleiben unverändert) + OutputStreamWriter os7 = new OutputStreamWriter(new FileOutputStream(filename), "windows-1252"); // bleibt unverändert + OutputStreamWriter os8 = new OutputStreamWriter(new FileOutputStream(filename), "Shift_JIS"); // bleibt unverändert + + // Hier wird `UnsupportedEncodingException` geworfen (vor dem Cleanup) + OutputStreamWriter os9 = new OutputStreamWriter(new FileOutputStream(filename), "non-existing-encoding"); // wirft UnsupportedEncodingException + + // Aufruf mit einer ungültigen Zeichenkodierung und catch für UnsupportedEncodingException + try { + OutputStreamWriter os10 = new OutputStreamWriter(new FileOutputStream(filename), "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (UnsupportedEncodingException e) { + // Hier wird die UnsupportedEncodingException abgefangen + e.printStackTrace(); + } + + // Beispiele mit StandardCharsets-Konstanten, die unverändert bleiben + OutputStreamWriter os11 = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.UTF_8); // bleibt unverändert + OutputStreamWriter os12 = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.ISO_8859_1); // bleibt unverändert + OutputStreamWriter os13 = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.US_ASCII); // bleibt unverändert + OutputStreamWriter os14 = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.UTF_16); // bleibt unverändert + + // Beispiel mit Charset.forName und einer Konstanten, die als Parameter übergeben wird (bleibt unverändert) + OutputStreamWriter os15 = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.UTF_16); + } catch (FileNotFoundException e) { + // Datei nicht gefunden + e.printStackTrace(); + } catch (UnsupportedEncodingException e) { + // Hier wird die UnsupportedEncodingException abgefangen + e.printStackTrace(); + } + } + + // Methodendeklaration, die `UnsupportedEncodingException` wirft (und durch den Cleanup angepasst wird) + void methodWithThrows(String filename) throws UnsupportedEncodingException { + OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(filename), "non-existing-encoding"); // wirft UnsupportedEncodingException + } + + // Neue Methode: methodWithThrowsChange() - nach dem Cleanup wird keine UnsupportedEncodingException mehr geworfen + void methodWithThrowsChange(String filename) throws FileNotFoundException { + // Nach dem Cleanup, der String "UTF-8" wird zu einer StandardCharset-Konstanten geändert + OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(filename), "UTF-8"); // wirft keine UnsupportedEncodingException mehr + } + + // Methode mit einem try-catch, um die UnsupportedEncodingException zu behandeln (und durch den Cleanup angepasst wird) + void methodWithCatch(String filename) { + try { + OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(filename), "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (UnsupportedEncodingException e) { + // Hier wird die UnsupportedEncodingException abgefangen + e.printStackTrace(); + } + } + + // Neue Methode: methodWithCatchChange() - nach dem Cleanup wird keine UnsupportedEncodingException mehr abgefangen + void methodWithCatchChange(String filename) { + try { + // Nach dem Cleanup wird "UTF-8" ersetzt + OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(filename), "UTF-8"); // keine UnsupportedEncodingException + } catch (UnsupportedEncodingException e) { + // Dieser Block wird nicht mehr erreicht, da keine UnsupportedEncodingException mehr geworfen wird + e.printStackTrace(); + } + } +} +""", + +""" +package test1; + +import java.io.FileOutputStream; +import java.io.OutputStreamWriter; +import java.io.FileNotFoundException; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; + +public class E1 { + private static final Charset UTF_16 = StandardCharsets.UTF_16; + private static final Charset US_ASCII = StandardCharsets.US_ASCII; + private static final Charset ISO_8859_1 = StandardCharsets.ISO_8859_1; + private static final Charset UTF_8 = StandardCharsets.UTF_8; + private static final String ENCODING_UTF8 = "UTF-8"; // Konstante für Encoding + + void method(String filename) { + try { + // Standard-Konstruktor ohne Encoding + OutputStreamWriter os1 = new OutputStreamWriter(new FileOutputStream(filename), E1.UTF_8); + + // Konstruktor mit String-Encoding (UTF-8) -> muss durch StandardCharsets.UTF_8 ersetzt werden + OutputStreamWriter os2 = new OutputStreamWriter(new FileOutputStream(filename), E1.UTF_8); // "UTF-8" als String-Literal + + // Konstruktor mit String-Encoding (ISO-8859-1) -> muss durch StandardCharsets.ISO_8859_1 ersetzt werden + OutputStreamWriter os3 = new OutputStreamWriter(new FileOutputStream(filename), E1.ISO_8859_1); // "ISO-8859-1" als String-Literal + + // Konstruktor mit String-Encoding (US-ASCII) -> muss durch StandardCharsets.US_ASCII ersetzt werden + OutputStreamWriter os4 = new OutputStreamWriter(new FileOutputStream(filename), E1.US_ASCII); // "US-ASCII" als String-Literal + + // Konstruktor mit String-Encoding (UTF-16) -> muss durch StandardCharsets.UTF_16 ersetzt werden + OutputStreamWriter os5 = new OutputStreamWriter(new FileOutputStream(filename), E1.UTF_16); // "UTF-16" als String-Literal + + // Der Konstruktor mit einer benutzerdefinierten Konstante bleibt unverändert + OutputStreamWriter os6 = new OutputStreamWriter(new FileOutputStream(filename), ENCODING_UTF8); // bleibt unverändert + + // Fälle ohne Entsprechung in StandardCharsets (bleiben unverändert) + OutputStreamWriter os7 = new OutputStreamWriter(new FileOutputStream(filename), "windows-1252"); // bleibt unverändert + OutputStreamWriter os8 = new OutputStreamWriter(new FileOutputStream(filename), "Shift_JIS"); // bleibt unverändert + + // Hier wird `UnsupportedEncodingException` geworfen (vor dem Cleanup) + OutputStreamWriter os9 = new OutputStreamWriter(new FileOutputStream(filename), "non-existing-encoding"); // wirft UnsupportedEncodingException + + // Aufruf mit einer ungültigen Zeichenkodierung und catch für UnsupportedEncodingException + try { + OutputStreamWriter os10 = new OutputStreamWriter(new FileOutputStream(filename), "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (UnsupportedEncodingException e) { + // Hier wird die UnsupportedEncodingException abgefangen + e.printStackTrace(); + } + + // Beispiele mit StandardCharsets-Konstanten, die unverändert bleiben + OutputStreamWriter os11 = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.UTF_8); // bleibt unverändert + OutputStreamWriter os12 = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.ISO_8859_1); // bleibt unverändert + OutputStreamWriter os13 = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.US_ASCII); // bleibt unverändert + OutputStreamWriter os14 = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.UTF_16); // bleibt unverändert + + // Beispiel mit Charset.forName und einer Konstanten, die als Parameter übergeben wird (bleibt unverändert) + OutputStreamWriter os15 = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.UTF_16); + } catch (FileNotFoundException e) { + // Datei nicht gefunden + e.printStackTrace(); + } + } + + // Methodendeklaration, die `UnsupportedEncodingException` wirft (und durch den Cleanup angepasst wird) + void methodWithThrows(String filename) throws UnsupportedEncodingException { + OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(filename), "non-existing-encoding"); // wirft UnsupportedEncodingException + } + + // Neue Methode: methodWithThrowsChange() - nach dem Cleanup wird keine UnsupportedEncodingException mehr geworfen + void methodWithThrowsChange(String filename) throws FileNotFoundException { + // Nach dem Cleanup, der String "UTF-8" wird zu einer StandardCharset-Konstanten geändert + OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(filename), E1.UTF_8); // wirft keine UnsupportedEncodingException mehr + } + + // Methode mit einem try-catch, um die UnsupportedEncodingException zu behandeln (und durch den Cleanup angepasst wird) + void methodWithCatch(String filename) { + try { + OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(filename), "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (UnsupportedEncodingException e) { + // Hier wird die UnsupportedEncodingException abgefangen + e.printStackTrace(); + } + } + + // Neue Methode: methodWithCatchChange() - nach dem Cleanup wird keine UnsupportedEncodingException mehr abgefangen + void methodWithCatchChange(String filename) { + try { + // Nach dem Cleanup wird "UTF-8" ersetzt + OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(filename), E1.UTF_8); // keine UnsupportedEncodingException + } + } +} +"""), + CHANNELSNEWREADER( +""" +package test1; + +import java.io.Reader; +import java.nio.channels.ReadableByteChannel; +import java.nio.channels.Channels; +import java.nio.charset.StandardCharsets; +import java.nio.charset.CharsetDecoder; + +public class E1 { + private static final String ENCODING_UTF8 = "UTF-8"; // Konstante für Encoding + + void method(ReadableByteChannel ch, CharsetDecoder decoder) { + // Fälle für StandardCharsets-Konstanten + Reader r1 = Channels.newReader(ch, "UTF-8"); // soll StandardCharsets.UTF_8 werden + Reader r2 = Channels.newReader(ch, "ISO-8859-1"); // soll StandardCharsets.ISO_8859_1 werden + Reader r3 = Channels.newReader(ch, "US-ASCII"); // soll StandardCharsets.US_ASCII werden + Reader r4 = Channels.newReader(ch, "UTF-16"); // soll StandardCharsets.UTF_16 werden + + // Aufruf mit einer String-Konstanten (soll unverändert bleiben) + Reader r5 = Channels.newReader(ch, ENCODING_UTF8); // bleibt unverändert + + // Fälle ohne Entsprechung in StandardCharsets (sollen unverändert bleiben) + Reader r6 = Channels.newReader(ch, "windows-1252"); // bleibt unverändert + Reader r7 = Channels.newReader(ch, "Shift_JIS"); // bleibt unverändert + + // Aufrufe, die bereits `StandardCharsets` verwenden (bleiben unverändert) + Reader r8 = Channels.newReader(ch, StandardCharsets.UTF_8); + Reader r9 = Channels.newReader(ch, decoder, 1024); // mit CharsetDecoder und Buffergröße, bleibt unverändert + } +} +""", + +""" +package test1; + +import java.io.Reader; +import java.nio.channels.ReadableByteChannel; +import java.nio.channels.Channels; +import java.nio.charset.StandardCharsets; +import java.nio.charset.Charset; +import java.nio.charset.CharsetDecoder; + +public class E1 { + private static final Charset UTF_16 = StandardCharsets.UTF_16; + private static final Charset US_ASCII = StandardCharsets.US_ASCII; + private static final Charset ISO_8859_1 = StandardCharsets.ISO_8859_1; + private static final Charset UTF_8 = StandardCharsets.UTF_8; + private static final String ENCODING_UTF8 = "UTF-8"; // Konstante für Encoding + + void method(ReadableByteChannel ch, CharsetDecoder decoder) { + // Fälle für StandardCharsets-Konstanten + Reader r1 = Channels.newReader(ch, E1.UTF_8); // soll StandardCharsets.UTF_8 werden + Reader r2 = Channels.newReader(ch, E1.ISO_8859_1); // soll StandardCharsets.ISO_8859_1 werden + Reader r3 = Channels.newReader(ch, E1.US_ASCII); // soll StandardCharsets.US_ASCII werden + Reader r4 = Channels.newReader(ch, E1.UTF_16); // soll StandardCharsets.UTF_16 werden + + // Aufruf mit einer String-Konstanten (soll unverändert bleiben) + Reader r5 = Channels.newReader(ch, ENCODING_UTF8); // bleibt unverändert + + // Fälle ohne Entsprechung in StandardCharsets (sollen unverändert bleiben) + Reader r6 = Channels.newReader(ch, "windows-1252"); // bleibt unverändert + Reader r7 = Channels.newReader(ch, "Shift_JIS"); // bleibt unverändert + + // Aufrufe, die bereits `StandardCharsets` verwenden (bleiben unverändert) + Reader r8 = Channels.newReader(ch, StandardCharsets.UTF_8); + Reader r9 = Channels.newReader(ch, decoder, 1024); // mit CharsetDecoder und Buffergröße, bleibt unverändert + } +} +"""), + CHANNELSNEWWRITER( +""" +package test1; + +import java.io.Writer; +import java.nio.channels.WritableByteChannel; +import java.nio.channels.Channels; +import java.nio.charset.StandardCharsets; +import java.nio.charset.Charset; + +public class E1 { + private static final String ENCODING_UTF8 = "UTF-8"; // Konstante für Encoding + + void method(WritableByteChannel ch, Charset charset) { + // Fälle für StandardCharsets-Konstanten + Writer w1 = Channels.newWriter(ch, "UTF-8"); // soll StandardCharsets.UTF_8 werden + Writer w2 = Channels.newWriter(ch, "ISO-8859-1"); // soll StandardCharsets.ISO_8859_1 werden + Writer w3 = Channels.newWriter(ch, "US-ASCII"); // soll StandardCharsets.US_ASCII werden + Writer w4 = Channels.newWriter(ch, "UTF-16"); // soll StandardCharsets.UTF_16 werden + + // Aufruf mit einer String-Konstanten (soll unverändert bleiben) + Writer w5 = Channels.newWriter(ch, ENCODING_UTF8); // bleibt unverändert + + // Fälle ohne Entsprechung in StandardCharsets (sollen unverändert bleiben) + Writer w6 = Channels.newWriter(ch, "windows-1252"); // bleibt unverändert + Writer w7 = Channels.newWriter(ch, "Shift_JIS"); // bleibt unverändert + + // Aufrufe, die bereits `StandardCharsets` verwenden (bleiben unverändert) + Writer w8 = Channels.newWriter(ch, StandardCharsets.UTF_8); + Writer w9 = Channels.newWriter(ch, charset); // unverändert, da `Charset` Instanz verwendet + } +} +""", + +""" +package test1; + +import java.io.Writer; +import java.nio.channels.WritableByteChannel; +import java.nio.channels.Channels; +import java.nio.charset.StandardCharsets; +import java.nio.charset.Charset; + +public class E1 { + private static final Charset UTF_16 = StandardCharsets.UTF_16; + private static final Charset US_ASCII = StandardCharsets.US_ASCII; + private static final Charset ISO_8859_1 = StandardCharsets.ISO_8859_1; + private static final Charset UTF_8 = StandardCharsets.UTF_8; + private static final String ENCODING_UTF8 = "UTF-8"; // Konstante für Encoding + + void method(WritableByteChannel ch, Charset charset) { + // Fälle für StandardCharsets-Konstanten + Writer w1 = Channels.newWriter(ch, E1.UTF_8); // soll StandardCharsets.UTF_8 werden + Writer w2 = Channels.newWriter(ch, E1.ISO_8859_1); // soll StandardCharsets.ISO_8859_1 werden + Writer w3 = Channels.newWriter(ch, E1.US_ASCII); // soll StandardCharsets.US_ASCII werden + Writer w4 = Channels.newWriter(ch, E1.UTF_16); // soll StandardCharsets.UTF_16 werden + + // Aufruf mit einer String-Konstanten (soll unverändert bleiben) + Writer w5 = Channels.newWriter(ch, ENCODING_UTF8); // bleibt unverändert + + // Fälle ohne Entsprechung in StandardCharsets (sollen unverändert bleiben) + Writer w6 = Channels.newWriter(ch, "windows-1252"); // bleibt unverändert + Writer w7 = Channels.newWriter(ch, "Shift_JIS"); // bleibt unverändert + + // Aufrufe, die bereits `StandardCharsets` verwenden (bleiben unverändert) + Writer w8 = Channels.newWriter(ch, StandardCharsets.UTF_8); + Writer w9 = Channels.newWriter(ch, charset); // unverändert, da `Charset` Instanz verwendet + } +} +"""), + PRINTWRITER(""" + package test1; + + import java.io.PrintWriter; + import java.io.Writer; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + try { + Writer w=new PrintWriter(filename); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } + } + """, + + """ +package test1; + +import java.io.PrintWriter; +import java.io.Writer; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.io.BufferedWriter; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.OutputStreamWriter; + +public class E1 { + private static final Charset UTF_8 = StandardCharsets.UTF_8; + + void method(String filename) { + try { + Writer w=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename), E1.UTF_8)); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } +} + """), + STRINGGETBYTES( +""" +package test1; + +import java.nio.charset.StandardCharsets; + +public class E1 { + + // Methode 1: Verwendung von StandardCharsets.UTF_8 statt "UTF-8" als String-Literal + void method(String filename) { + String s = "asdf"; //$NON-NLS-1$ + + // Vorher: getBytes ohne Angabe der Kodierung (verwendet die Plattform-spezifische Standard-Kodierung) + byte[] bytes = s.getBytes(); + + // Nachher: Umstellung auf StandardCharsets.UTF_8 + byte[] bytes2 = s.getBytes(StandardCharsets.UTF_8); + + System.out.println(bytes.length); + System.out.println(bytes2.length); + } + + // Methode 2: Behandlung von getBytes mit einer expliziten Kodierung + void method2(String filename) { + String s = "asdf"; //$NON-NLS-1$ + + // Vorher: getBytes mit expliziter Kodierung (UTF-8 als String-Literal) + byte[] bytes = s.getBytes("UTF-8"); + + // Nachher: Umstellung auf StandardCharsets.UTF_8 + byte[] bytes2 = s.getBytes(StandardCharsets.UTF_8); + + System.out.println(bytes.length); + System.out.println(bytes2.length); + } + + // Erweiterter Testfall: Verwendung von verschiedenen Kodierungen + void methodWithDifferentEncodings(String filename) { + String s = "asdf"; + + // Testen von gängigen Kodierungen + byte[] bytes1 = s.getBytes("ISO-8859-1"); // ISO-8859-1 + byte[] bytes2 = s.getBytes("US-ASCII"); // US-ASCII + byte[] bytes3 = s.getBytes(StandardCharsets.UTF_8); // UTF-8 mit StandardCharsets + byte[] bytes4 = s.getBytes("UTF-16"); // UTF-16 + + System.out.println(bytes1.length); // Ausgabe der Längen + System.out.println(bytes2.length); + System.out.println(bytes3.length); + System.out.println(bytes4.length); + } + + // Testfall: Verwendung von getBytes mit einer ungültigen Kodierung (sollte im Cleanup behandelt werden) + void methodWithInvalidEncoding(String filename) { + String s = "asdf"; + try { + // Ungültige Kodierung, die zu UnsupportedEncodingException führt + byte[] bytes = s.getBytes("non-existing-encoding"); + } catch (UnsupportedEncodingException e) { + // Diese Ausnahme sollte im Cleanup berücksichtigt werden + e.printStackTrace(); + } + } + + // Testfall: Verwendung von getBytes mit einer durch Variable angegebenen Kodierung + void methodWithVariableEncoding(String filename) { + String s = "asdf"; + String encoding = "UTF-8"; // Kodierung als Variable + try { + byte[] bytes = s.getBytes(encoding); // Kodierung aus der Variablen + System.out.println(bytes.length); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + } +} +""", + +""" +package test1; + +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; + +public class E1 { + + private static final Charset UTF_16 = StandardCharsets.UTF_16; + private static final Charset US_ASCII = StandardCharsets.US_ASCII; + private static final Charset ISO_8859_1 = StandardCharsets.ISO_8859_1; + private static final Charset UTF_8 = StandardCharsets.UTF_8; + + // Methode 1: Verwendung von StandardCharsets.UTF_8 statt "UTF-8" als String-Literal + void method(String filename) { + String s = "asdf"; //$NON-NLS-1$ + + // Vorher: getBytes ohne Angabe der Kodierung (verwendet die Plattform-spezifische Standard-Kodierung) + byte[] bytes = s.getBytes(E1.UTF_8); + + // Nachher: Umstellung auf StandardCharsets.UTF_8 + byte[] bytes2 = s.getBytes(StandardCharsets.UTF_8); + + System.out.println(bytes.length); + System.out.println(bytes2.length); + } + + // Methode 2: Behandlung von getBytes mit einer expliziten Kodierung + void method2(String filename) { + String s = "asdf"; //$NON-NLS-1$ + + // Vorher: getBytes mit expliziter Kodierung (UTF-8 als String-Literal) + byte[] bytes = s.getBytes(E1.UTF_8); + + // Nachher: Umstellung auf StandardCharsets.UTF_8 + byte[] bytes2 = s.getBytes(StandardCharsets.UTF_8); + + System.out.println(bytes.length); + System.out.println(bytes2.length); + } + + // Erweiterter Testfall: Verwendung von verschiedenen Kodierungen + void methodWithDifferentEncodings(String filename) { + String s = "asdf"; + + // Testen von gängigen Kodierungen + byte[] bytes1 = s.getBytes(E1.ISO_8859_1); // ISO-8859-1 + byte[] bytes2 = s.getBytes(E1.US_ASCII); // US-ASCII + byte[] bytes3 = s.getBytes(StandardCharsets.UTF_8); // UTF-8 mit StandardCharsets + byte[] bytes4 = s.getBytes(E1.UTF_16); // UTF-16 + + System.out.println(bytes1.length); // Ausgabe der Längen + System.out.println(bytes2.length); + System.out.println(bytes3.length); + System.out.println(bytes4.length); + } + + // Testfall: Verwendung von getBytes mit einer ungültigen Kodierung (sollte im Cleanup behandelt werden) + void methodWithInvalidEncoding(String filename) { + String s = "asdf"; + try { + // Ungültige Kodierung, die zu UnsupportedEncodingException führt + byte[] bytes = s.getBytes("non-existing-encoding"); + } catch (UnsupportedEncodingException e) { + // Diese Ausnahme sollte im Cleanup berücksichtigt werden + e.printStackTrace(); + } + } + + // Testfall: Verwendung von getBytes mit einer durch Variable angegebenen Kodierung + void methodWithVariableEncoding(String filename) { + String s = "asdf"; + String encoding = "UTF-8"; // Kodierung als Variable + try { + byte[] bytes = s.getBytes(encoding); // Kodierung aus der Variablen + System.out.println(bytes.length); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + } +} +"""), + STRING( +""" +package test1; + +import java.io.FileNotFoundException; +import java.io.UnsupportedEncodingException; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; + +public class E1 { + + static void bla(String filename) throws FileNotFoundException, UnsupportedEncodingException { + byte[] b = {(byte) 59}; + + // Fälle mit String Encoding als "UTF-8" (soll durch StandardCharsets.UTF_8 ersetzt werden) + String s1 = new String(b, "UTF-8"); // "UTF-8" als String-Literal + String s2 = new String(b, 0, 1, "UTF-8"); // "UTF-8" als String-Literal + + // Fall mit ISO-8859-1 Encoding (soll durch StandardCharsets.ISO_8859_1 ersetzt werden) + String s3 = new String(b, "ISO-8859-1"); // "ISO-8859-1" als String-Literal + String s4 = new String(b, 0, 1, "ISO-8859-1"); // "ISO-8859-1" als String-Literal + + // Fall mit US-ASCII Encoding (soll durch StandardCharsets.US_ASCII ersetzt werden) + String s5 = new String(b, "US-ASCII"); // "US-ASCII" als String-Literal + String s6 = new String(b, 0, 1, "US-ASCII"); // "US-ASCII" als String-Literal + + // Fall mit UTF-16 Encoding (soll durch StandardCharsets.UTF_16 ersetzt werden) + String s7 = new String(b, "UTF-16"); // "UTF-16" als String-Literal + String s8 = new String(b, 0, 1, "UTF-16"); // "UTF-16" als String-Literal + + // Fall mit einer benutzerdefinierten Konstante für Encoding, bleibt unverändert + String s9 = new String(b, "UTF-8"); // bleibt unverändert + String s10 = new String(b, 0, 1, "UTF-8"); // bleibt unverändert + + // Fälle ohne Entsprechung in StandardCharsets, bleiben unverändert + String s11 = new String(b, "windows-1252"); // bleibt unverändert + String s12 = new String(b, 0, 1, "windows-1252"); // bleibt unverändert + String s13 = new String(b, "Shift_JIS"); // bleibt unverändert + String s14 = new String(b, 0, 1, "Shift_JIS"); // bleibt unverändert + + // Fall mit Charset.forName() (wird unverändert bleiben, keine Ersetzung möglich) + Charset charset = Charset.forName("UTF-16"); + String s15 = new String(b, charset); // bleibt unverändert + String s16 = new String(b, 0, 1, charset); // bleibt unverändert + + // Fälle, die eine UnsupportedEncodingException werfen (werden im Cleanup angepasst) + try { + String s17 = new String(b, "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (UnsupportedEncodingException e) { + // UnsupportedEncodingException wird geworfen und abgefangen + e.printStackTrace(); + } + + try { + String s18 = new String(b, 0, 1, "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (UnsupportedEncodingException e) { + // UnsupportedEncodingException wird geworfen und abgefangen + e.printStackTrace(); + } + } + + // Methodendeklaration mit throws für UnsupportedEncodingException (wird im Cleanup angepasst) + static void methodWithThrows(String filename) throws UnsupportedEncodingException { + byte[] b = {(byte) 59}; + String s1 = new String(b, "non-existing-encoding"); // wirft UnsupportedEncodingException + } + + // Nach dem Cleanup sollte dies keine UnsupportedEncodingException mehr werfen + static void methodWithThrowsChange(String filename) throws FileNotFoundException { + byte[] b = {(byte) 59}; + String s1 = new String(b, "UTF-8"); // wirft keine UnsupportedEncodingException mehr + } + + // Methodendeklaration mit try-catch für UnsupportedEncodingException (wird im Cleanup angepasst) + static void methodWithCatch(String filename) { + byte[] b = {(byte) 59}; + try { + String s1 = new String(b, "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (UnsupportedEncodingException e) { + // UnsupportedEncodingException wird geworfen und abgefangen + e.printStackTrace(); + } + } + + // Nach dem Cleanup wird keine UnsupportedEncodingException mehr abgefangen + static void methodWithCatchChange(String filename) { + byte[] b = {(byte) 59}; + try { + String s1 = new String(b, "UTF-8"); // keine UnsupportedEncodingException + } catch (UnsupportedEncodingException e) { + // Dieser Block wird nicht mehr erreicht, da keine UnsupportedEncodingException mehr geworfen wird + e.printStackTrace(); + } + } +} +""", + +""" +package test1; + +import java.io.FileNotFoundException; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; + +public class E1 { + + private static final Charset UTF_16 = StandardCharsets.UTF_16; + private static final Charset US_ASCII = StandardCharsets.US_ASCII; + private static final Charset ISO_8859_1 = StandardCharsets.ISO_8859_1; + private static final Charset UTF_8 = StandardCharsets.UTF_8; + + static void bla(String filename) throws FileNotFoundException { + byte[] b = {(byte) 59}; + + // Fälle mit String Encoding als "UTF-8" (soll durch StandardCharsets.UTF_8 ersetzt werden) + String s1 = new String(b, E1.UTF_8); // "UTF-8" als String-Literal + String s2 = new String(b, 0, 1, E1.UTF_8); // "UTF-8" als String-Literal + + // Fall mit ISO-8859-1 Encoding (soll durch StandardCharsets.ISO_8859_1 ersetzt werden) + String s3 = new String(b, E1.ISO_8859_1); // "ISO-8859-1" als String-Literal + String s4 = new String(b, 0, 1, E1.ISO_8859_1); // "ISO-8859-1" als String-Literal + + // Fall mit US-ASCII Encoding (soll durch StandardCharsets.US_ASCII ersetzt werden) + String s5 = new String(b, E1.US_ASCII); // "US-ASCII" als String-Literal + String s6 = new String(b, 0, 1, E1.US_ASCII); // "US-ASCII" als String-Literal + + // Fall mit UTF-16 Encoding (soll durch StandardCharsets.UTF_16 ersetzt werden) + String s7 = new String(b, E1.UTF_16); // "UTF-16" als String-Literal + String s8 = new String(b, 0, 1, E1.UTF_16); // "UTF-16" als String-Literal + + // Fall mit einer benutzerdefinierten Konstante für Encoding, bleibt unverändert + String s9 = new String(b, E1.UTF_8); // bleibt unverändert + String s10 = new String(b, 0, 1, E1.UTF_8); // bleibt unverändert + + // Fälle ohne Entsprechung in StandardCharsets, bleiben unverändert + String s11 = new String(b, "windows-1252"); // bleibt unverändert + String s12 = new String(b, 0, 1, "windows-1252"); // bleibt unverändert + String s13 = new String(b, "Shift_JIS"); // bleibt unverändert + String s14 = new String(b, 0, 1, "Shift_JIS"); // bleibt unverändert + + // Fall mit Charset.forName() (wird unverändert bleiben, keine Ersetzung möglich) + Charset charset = Charset.forName("UTF-16"); + String s15 = new String(b, charset); // bleibt unverändert + String s16 = new String(b, 0, 1, charset); // bleibt unverändert + + // Fälle, die eine UnsupportedEncodingException werfen (werden im Cleanup angepasst) + try { + String s17 = new String(b, "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (UnsupportedEncodingException e) { + // UnsupportedEncodingException wird geworfen und abgefangen + e.printStackTrace(); + } + + try { + String s18 = new String(b, 0, 1, "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (UnsupportedEncodingException e) { + // UnsupportedEncodingException wird geworfen und abgefangen + e.printStackTrace(); + } + } + + // Methodendeklaration mit throws für UnsupportedEncodingException (wird im Cleanup angepasst) + static void methodWithThrows(String filename) throws UnsupportedEncodingException { + byte[] b = {(byte) 59}; + String s1 = new String(b, "non-existing-encoding"); // wirft UnsupportedEncodingException + } + + // Nach dem Cleanup sollte dies keine UnsupportedEncodingException mehr werfen + static void methodWithThrowsChange(String filename) throws FileNotFoundException { + byte[] b = {(byte) 59}; + String s1 = new String(b, E1.UTF_8); // wirft keine UnsupportedEncodingException mehr + } + + // Methodendeklaration mit try-catch für UnsupportedEncodingException (wird im Cleanup angepasst) + static void methodWithCatch(String filename) { + byte[] b = {(byte) 59}; + try { + String s1 = new String(b, "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (UnsupportedEncodingException e) { + // UnsupportedEncodingException wird geworfen und abgefangen + e.printStackTrace(); + } + } + + // Nach dem Cleanup wird keine UnsupportedEncodingException mehr abgefangen + static void methodWithCatchChange(String filename) { + byte[] b = {(byte) 59}; + try { + String s1 = new String(b, E1.UTF_8); // keine UnsupportedEncodingException + } + } +} +"""), + PROPERTIESSTORETOXML( +""" +package test1; + +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; +import java.util.Properties; + +public class E1 { + private static final String ENCODING_UTF8 = "UTF-8"; // Benutzerdefinierte Konstante für Encoding + private String encodingVar = "ISO-8859-1"; // Encoding-Variable + + // Fall 1: UTF-8 als String; Cleanup soll zu StandardCharsets.UTF_8 ändern + void storeWithTryWithResources() throws IOException { + Properties p = new Properties(); + try (FileOutputStream os = new FileOutputStream("out.xml")) { + p.storeToXML(os, "Kommentar", "UTF-8"); + } + } + + // Fall 2: Benutzerdefiniertes Encoding als Variable; Cleanup soll diesen Fall unverändert lassen + void storeWithTryWithResourcesAndCustomEncoding() throws IOException { + Properties p = new Properties(); + try (FileOutputStream os = new FileOutputStream("out.xml")) { + p.storeToXML(os, "Kommentar", encodingVar); + } + } + + // Fall 3: Ungültiges Encoding als String; Cleanup soll auf StandardCharsets.UTF_8 ändern und den catch-Block entfernen + void storeWithTryWithResourcesAndInvalidEncoding() { + Properties p = new Properties(); + try (FileOutputStream os = new FileOutputStream("out.xml")) { + p.storeToXML(os, "Kommentar", "non-existing-encoding"); + } catch (UnsupportedEncodingException e) { + System.err.println("Unsupported encoding caught!"); + } + } + + // Fall 4: FileOutputStream außerhalb des try-Blocks und UTF-8 als String; Cleanup soll auf StandardCharsets.UTF_8 ändern und den catch-Block entfernen + void storeWithoutTryWithResources(String filename) throws IOException { + Properties p = new Properties(); + FileOutputStream os = new FileOutputStream(filename); + try { + p.storeToXML(os, "Kommentar", "UTF-8"); + } catch (UnsupportedEncodingException e) { + System.err.println("Unexpected UnsupportedEncodingException"); + } finally { + os.close(); // Bleibt erhalten, um die Ressource korrekt zu schließen + } + } + + // Fall 5: Gültiges Encoding ohne Konstante in StandardCharsets (windows-1252); Cleanup soll diesen Fall unverändert lassen + void storeWithWindows1252Encoding() throws IOException { + Properties p = new Properties(); + try (FileOutputStream os = new FileOutputStream("out.xml")) { + p.storeToXML(os, "Kommentar", "windows-1252"); + } + } + + // Fall 6: Gültiges Encoding ohne Konstante in StandardCharsets (Shift_JIS); Cleanup soll diesen Fall unverändert lassen + void storeWithShiftJISEncoding() throws IOException { + Properties p = new Properties(); + try (FileOutputStream os = new FileOutputStream("out.xml")) { + p.storeToXML(os, "Kommentar", "Shift_JIS"); + } + } + + // Fall 7: Ungültiges Encoding außerhalb von try-with-resources; Cleanup soll auf StandardCharsets.UTF_8 ändern und den catch-Block entfernen + void storeWithInvalidEncodingOutsideTry(String filename) throws IOException { + Properties p = new Properties(); + FileOutputStream os = new FileOutputStream(filename); + try { + p.storeToXML(os, "Kommentar", "non-existing-encoding"); + } catch (UnsupportedEncodingException e) { + System.err.println("Unsupported encoding caught!"); + } finally { + os.close(); // Bleibt erhalten, um die Ressource korrekt zu schließen + } + } + + // Fall 8: StandardCharsets.UTF_8 ohne try-with-resources; Cleanup soll diesen Fall unverändert lassen + void storeWithoutTryWithResourcesStandardCharsets(String filename) throws IOException { + Properties p = new Properties(); + FileOutputStream os = new FileOutputStream(filename); + try { + p.storeToXML(os, "Kommentar", StandardCharsets.UTF_8); + } finally { + os.close(); // Bleibt erhalten, um die Ressource korrekt zu schließen + } + } +} +""", + +""" +package test1; + +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.Properties; + +public class E1 { + private static final Charset UTF_8 = StandardCharsets.UTF_8; + private static final String ENCODING_UTF8 = "UTF-8"; // Benutzerdefinierte Konstante für Encoding + private String encodingVar = "ISO-8859-1"; // Encoding-Variable + + // Fall 1: UTF-8 als String; Cleanup soll zu StandardCharsets.UTF_8 ändern + void storeWithTryWithResources() throws IOException { + Properties p = new Properties(); + try (FileOutputStream os = new FileOutputStream("out.xml")) { + p.storeToXML(os, "Kommentar", E1.UTF_8); + } + } + + // Fall 2: Benutzerdefiniertes Encoding als Variable; Cleanup soll diesen Fall unverändert lassen + void storeWithTryWithResourcesAndCustomEncoding() throws IOException { + Properties p = new Properties(); + try (FileOutputStream os = new FileOutputStream("out.xml")) { + p.storeToXML(os, "Kommentar", encodingVar); + } + } + + // Fall 3: Ungültiges Encoding als String; Cleanup soll auf StandardCharsets.UTF_8 ändern und den catch-Block entfernen + void storeWithTryWithResourcesAndInvalidEncoding() { + Properties p = new Properties(); + try (FileOutputStream os = new FileOutputStream("out.xml")) { + p.storeToXML(os, "Kommentar", "non-existing-encoding"); + } catch (UnsupportedEncodingException e) { + System.err.println("Unsupported encoding caught!"); + } + } + + // Fall 4: FileOutputStream außerhalb des try-Blocks und UTF-8 als String; Cleanup soll auf StandardCharsets.UTF_8 ändern und den catch-Block entfernen + void storeWithoutTryWithResources(String filename) throws IOException { + Properties p = new Properties(); + FileOutputStream os = new FileOutputStream(filename); + try { + p.storeToXML(os, "Kommentar", E1.UTF_8); + } finally { + os.close(); // Bleibt erhalten, um die Ressource korrekt zu schließen + } + } + + // Fall 5: Gültiges Encoding ohne Konstante in StandardCharsets (windows-1252); Cleanup soll diesen Fall unverändert lassen + void storeWithWindows1252Encoding() throws IOException { + Properties p = new Properties(); + try (FileOutputStream os = new FileOutputStream("out.xml")) { + p.storeToXML(os, "Kommentar", "windows-1252"); + } + } + + // Fall 6: Gültiges Encoding ohne Konstante in StandardCharsets (Shift_JIS); Cleanup soll diesen Fall unverändert lassen + void storeWithShiftJISEncoding() throws IOException { + Properties p = new Properties(); + try (FileOutputStream os = new FileOutputStream("out.xml")) { + p.storeToXML(os, "Kommentar", "Shift_JIS"); + } + } + + // Fall 7: Ungültiges Encoding außerhalb von try-with-resources; Cleanup soll auf StandardCharsets.UTF_8 ändern und den catch-Block entfernen + void storeWithInvalidEncodingOutsideTry(String filename) throws IOException { + Properties p = new Properties(); + FileOutputStream os = new FileOutputStream(filename); + try { + p.storeToXML(os, "Kommentar", "non-existing-encoding"); + } catch (UnsupportedEncodingException e) { + System.err.println("Unsupported encoding caught!"); + } finally { + os.close(); // Bleibt erhalten, um die Ressource korrekt zu schließen + } + } + + // Fall 8: StandardCharsets.UTF_8 ohne try-with-resources; Cleanup soll diesen Fall unverändert lassen + void storeWithoutTryWithResourcesStandardCharsets(String filename) throws IOException { + Properties p = new Properties(); + FileOutputStream os = new FileOutputStream(filename); + try { + p.storeToXML(os, "Kommentar", StandardCharsets.UTF_8); + } finally { + os.close(); // Bleibt erhalten, um die Ressource korrekt zu schließen + } + } +} +"""), + URLDECODER( +""" +package test1; + +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; + +public class E2 { + private static final String ENCODING_UTF8 = "UTF-8"; // Konstante für Encoding + private String encodingVar = "ISO-8859-1"; // Variable für Encoding + + // Methode ohne Encoding-Angabe, bleibt unverändert + static void decodeDefault() { + String url = URLDecoder.decode("example"); + } + + // Methode, die "UTF-8" als String verwendet und UnsupportedEncodingException wirft + static void decodeWithThrows() throws UnsupportedEncodingException { + String url = URLDecoder.decode("example", "UTF-8"); // sollte in StandardCharsets.UTF_8 geändert werden + } + + // Methode, die eine ungültige Kodierung verwendet und `UnsupportedEncodingException` wirft + static void decodeWithInvalidEncodingThrows() throws UnsupportedEncodingException { + String url = URLDecoder.decode("example", "non-existing-encoding"); + } + + // Methode, die eine benutzerdefinierte Konstante für Encoding verwendet, bleibt unverändert + void decodeWithCustomConstant() throws UnsupportedEncodingException { + String url = URLDecoder.decode("example", ENCODING_UTF8); + } + + // Methode, die Encoding als Variable übergibt, bleibt unverändert + void decodeWithVariableEncoding() throws UnsupportedEncodingException { + String url = URLDecoder.decode("example", encodingVar); + } + + // Methode mit `try-catch`-Block für ungültiges Encoding + static void decodeWithTryCatch() { + try { + String url = URLDecoder.decode("example", "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (UnsupportedEncodingException e) { + System.err.println("Caught UnsupportedEncodingException for invalid encoding!"); + } + } + + // Beispiel mit StandardCharsets-Konstanten, bleibt unverändert + static void decodeWithStandardCharset() { + String url = URLDecoder.decode("example", StandardCharsets.UTF_8); + } +} +""", +""" +package test1; + +import java.net.URLDecoder; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; + +public class E2 { + private static final Charset UTF_8 = StandardCharsets.UTF_8; + private static final String ENCODING_UTF8 = "UTF-8"; // Konstante für Encoding + private String encodingVar = "ISO-8859-1"; // Variable für Encoding + + // Methode ohne Encoding-Angabe, bleibt unverändert + static void decodeDefault() { + String url = URLDecoder.decode("example", E2.UTF_8); + } + + // Methode, die "UTF-8" als String verwendet und UnsupportedEncodingException wirft + static void decodeWithThrows() { + String url = URLDecoder.decode("example", E2.UTF_8); // sollte in StandardCharsets.UTF_8 geändert werden + } + + // Methode, die eine ungültige Kodierung verwendet und `UnsupportedEncodingException` wirft + static void decodeWithInvalidEncodingThrows() throws UnsupportedEncodingException { + String url = URLDecoder.decode("example", "non-existing-encoding"); + } + + // Methode, die eine benutzerdefinierte Konstante für Encoding verwendet, bleibt unverändert + void decodeWithCustomConstant() throws UnsupportedEncodingException { + String url = URLDecoder.decode("example", ENCODING_UTF8); + } + + // Methode, die Encoding als Variable übergibt, bleibt unverändert + void decodeWithVariableEncoding() throws UnsupportedEncodingException { + String url = URLDecoder.decode("example", encodingVar); + } + + // Methode mit `try-catch`-Block für ungültiges Encoding + static void decodeWithTryCatch() { + try { + String url = URLDecoder.decode("example", "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (UnsupportedEncodingException e) { + System.err.println("Caught UnsupportedEncodingException for invalid encoding!"); + } + } + + // Beispiel mit StandardCharsets-Konstanten, bleibt unverändert + static void decodeWithStandardCharset() { + String url = URLDecoder.decode("example", StandardCharsets.UTF_8); + } +} +"""), + URLENCODER( +""" +package test1; + +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; + +public class E1 { + private static final String ENCODING_UTF8 = "UTF-8"; // Benutzerdefinierte Kodierungskonstante + private String encodingVar = "ISO-8859-1"; // Variable für eine Kodierung + + // Methode ohne explizite Kodierung, bleibt unverändert + static void encodeDefault() { + String url = URLEncoder.encode("example"); + } + + // Methode, die "UTF-8" als String-Literal verwendet und `throws UnsupportedEncodingException` hat + static void encodeWithThrows() throws UnsupportedEncodingException { + String url = URLEncoder.encode("example", "UTF-8"); // sollte in StandardCharsets.UTF_8 geändert werden + } + + // Methode, die eine ungültige Kodierung verwendet und `UnsupportedEncodingException` wirft + static void encodeWithInvalidEncodingThrows() throws UnsupportedEncodingException { + String url = URLEncoder.encode("example", "non-existing-encoding"); + } + + // Methode, die eine benutzerdefinierte Kodierungskonstante verwendet, bleibt unverändert + void encodeWithCustomConstant() throws UnsupportedEncodingException { + String url = URLEncoder.encode("example", ENCODING_UTF8); + } + + // Methode, die eine Kodierungsvariable verwendet, bleibt unverändert + void encodeWithVariableEncoding() throws UnsupportedEncodingException { + String url = URLEncoder.encode("example", encodingVar); + } + + // Methode mit `try-catch`-Block für eine ungültige Kodierung + static void encodeWithTryCatch() { + try { + String url = URLEncoder.encode("example", "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (UnsupportedEncodingException e) { + System.err.println("Caught UnsupportedEncodingException for invalid encoding!"); + } + } + + // Beispiel mit StandardCharsets-Konstanten, bleibt unverändert + static void encodeWithStandardCharset() { + String url = URLEncoder.encode("example", StandardCharsets.UTF_8); + } +} +""", +""" +package test1; + +import java.net.URLEncoder; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; + +public class E1 { + private static final Charset UTF_8 = StandardCharsets.UTF_8; + private static final String ENCODING_UTF8 = "UTF-8"; // Benutzerdefinierte Kodierungskonstante + private String encodingVar = "ISO-8859-1"; // Variable für eine Kodierung + + // Methode ohne explizite Kodierung, bleibt unverändert + static void encodeDefault() { + String url = URLEncoder.encode("example", E1.UTF_8); + } + + // Methode, die "UTF-8" als String-Literal verwendet und `throws UnsupportedEncodingException` hat + static void encodeWithThrows() { + String url = URLEncoder.encode("example", E1.UTF_8); // sollte in StandardCharsets.UTF_8 geändert werden + } + + // Methode, die eine ungültige Kodierung verwendet und `UnsupportedEncodingException` wirft + static void encodeWithInvalidEncodingThrows() throws UnsupportedEncodingException { + String url = URLEncoder.encode("example", "non-existing-encoding"); + } + + // Methode, die eine benutzerdefinierte Kodierungskonstante verwendet, bleibt unverändert + void encodeWithCustomConstant() throws UnsupportedEncodingException { + String url = URLEncoder.encode("example", ENCODING_UTF8); + } + + // Methode, die eine Kodierungsvariable verwendet, bleibt unverändert + void encodeWithVariableEncoding() throws UnsupportedEncodingException { + String url = URLEncoder.encode("example", encodingVar); + } + + // Methode mit `try-catch`-Block für eine ungültige Kodierung + static void encodeWithTryCatch() { + try { + String url = URLEncoder.encode("example", "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (UnsupportedEncodingException e) { + System.err.println("Caught UnsupportedEncodingException for invalid encoding!"); + } + } + + // Beispiel mit StandardCharsets-Konstanten, bleibt unverändert + static void encodeWithStandardCharset() { + String url = URLEncoder.encode("example", StandardCharsets.UTF_8); + } +} +"""), + SCANNER( +""" +package test1; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.Scanner; + +public class E1 { + + // Methode mit File und explizitem "UTF-8" (wird durch StandardCharsets.UTF_8 ersetzt) + static void bla3(File file) throws FileNotFoundException { + // Konstruktor mit String-Encoding, sollte durch StandardCharsets.UTF_8 ersetzt werden + Scanner s = new Scanner(file, "UTF-8"); + } + + // Methode mit InputStream und explizitem "UTF-8" (wird durch StandardCharsets.UTF_8 ersetzt) + static void bla4(InputStream is) throws FileNotFoundException { + Scanner s2 = new Scanner(is, "UTF-8"); + } + + // Methode mit Scanner, aber ohne explizites Encoding, bleibt unverändert + static void bla5() { + Scanner s3 = new Scanner("asdf"); + } + + // Methode, die eine benutzerdefinierte Konstante für die Kodierung verwendet (bleibt unverändert) + private static final String ENCODING_UTF8 = "UTF-8"; + static void bla6(File file) throws FileNotFoundException { + Scanner s = new Scanner(file, ENCODING_UTF8); + } + + // Methode mit einer ungültigen Kodierung (muss UnsupportedEncodingException werfen) + static void bla7(File file) throws FileNotFoundException { + try { + Scanner s = new Scanner(file, "non-existing-encoding"); // wirft UnsupportedEncodingException + } catch (Exception e) { + e.printStackTrace(); // Catch block für UnsupportedEncodingException + } + } + + // Methode mit Scanner und ungültiger Kodierung, die `throws UnsupportedEncodingException` wirft + static void bla8(InputStream is) throws FileNotFoundException, UnsupportedEncodingException { + Scanner s = new Scanner(is, "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } + + // Methode, die eine ungültige Kodierung und ein try-catch verwendet (für FileNotFoundException) + static void bla9(File file) { + try { + Scanner s = new Scanner(file, "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (FileNotFoundException e) { + // Datei nicht gefunden, hier wird FileNotFoundException behandelt + e.printStackTrace(); + } catch (Exception e) { + // UnsupportedEncodingException wird hier abgefangen + e.printStackTrace(); + } + } + + // Beispiel mit StandardCharsets-Konstanten, die keine Änderung brauchen + static void bla10(File file) { + Scanner s = new Scanner(file, StandardCharsets.UTF_8); + } + + // Beispiel mit Scanner und InputStream, ohne explizite Kodierung (bleibt unverändert) + static void bla11(InputStream is) { + Scanner s = new Scanner(is); + } + + // Methode mit Scanner und einer benutzerdefinierten Kodierung als Variable (bleibt unverändert) + private String encodingVar = "ISO-8859-1"; + static void bla12(InputStream is) throws FileNotFoundException { + Scanner s = new Scanner(is, "ISO-8859-1"); + } +} +""", +""" +package test1; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.Scanner; + +public class E1 { + + private static final Charset ISO_8859_1 = StandardCharsets.ISO_8859_1; + private static final Charset UTF_8 = StandardCharsets.UTF_8; + // Methode mit File und explizitem "UTF-8" (wird durch StandardCharsets.UTF_8 ersetzt) + static void bla3(File file) throws FileNotFoundException { + // Konstruktor mit String-Encoding, sollte durch StandardCharsets.UTF_8 ersetzt werden + Scanner s = new Scanner(file, E1.UTF_8); + } + + // Methode mit InputStream und explizitem "UTF-8" (wird durch StandardCharsets.UTF_8 ersetzt) + static void bla4(InputStream is) throws FileNotFoundException { + Scanner s2 = new Scanner(is, E1.UTF_8); + } + + // Methode mit Scanner, aber ohne explizites Encoding, bleibt unverändert + static void bla5() { + Scanner s3 = new Scanner("asdf", E1.UTF_8); + } + + // Methode, die eine benutzerdefinierte Konstante für die Kodierung verwendet (bleibt unverändert) + private static final String ENCODING_UTF8 = "UTF-8"; + static void bla6(File file) throws FileNotFoundException { + Scanner s = new Scanner(file, ENCODING_UTF8); + } + + // Methode mit einer ungültigen Kodierung (muss UnsupportedEncodingException werfen) + static void bla7(File file) throws FileNotFoundException { + try { + Scanner s = new Scanner(file, "non-existing-encoding"); // wirft UnsupportedEncodingException + } catch (Exception e) { + e.printStackTrace(); // Catch block für UnsupportedEncodingException + } + } + + // Methode mit Scanner und ungültiger Kodierung, die `throws UnsupportedEncodingException` wirft + static void bla8(InputStream is) throws FileNotFoundException, UnsupportedEncodingException { + Scanner s = new Scanner(is, "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } + + // Methode, die eine ungültige Kodierung und ein try-catch verwendet (für FileNotFoundException) + static void bla9(File file) { + try { + Scanner s = new Scanner(file, "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (FileNotFoundException e) { + // Datei nicht gefunden, hier wird FileNotFoundException behandelt + e.printStackTrace(); + } catch (Exception e) { + // UnsupportedEncodingException wird hier abgefangen + e.printStackTrace(); + } + } + + // Beispiel mit StandardCharsets-Konstanten, die keine Änderung brauchen + static void bla10(File file) { + Scanner s = new Scanner(file, StandardCharsets.UTF_8); + } + + // Beispiel mit Scanner und InputStream, ohne explizite Kodierung (bleibt unverändert) + static void bla11(InputStream is) { + Scanner s = new Scanner(is, E1.UTF_8); + } + + // Methode mit Scanner und einer benutzerdefinierten Kodierung als Variable (bleibt unverändert) + private String encodingVar = "ISO-8859-1"; + static void bla12(InputStream is) throws FileNotFoundException { + Scanner s = new Scanner(is, E1.ISO_8859_1); + } +} +"""), + FORMATTER( +""" +package test1; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; +import java.util.Formatter; + +public class E1 { + + // Methode mit explizitem UTF-8, sollte durch StandardCharsets.UTF_8 ersetzt werden + static void bla() throws FileNotFoundException, UnsupportedEncodingException { + Formatter s = new Formatter(new File("asdf"), "UTF-8"); // 'UTF-8' wird zu StandardCharsets.UTF_8 + } + + // Methode mit try-catch, die eine Kodierung verwendet und Fehler wirft + static void bli() throws FileNotFoundException { + try { + Formatter s = new Formatter(new File("asdf"), "UTF-8"); // 'UTF-8' wird zu StandardCharsets.UTF_8 + } catch (FileNotFoundException | UnsupportedEncodingException e) { + // Der Catch-Block für UnsupportedEncodingException sollte im Cleanup entfernt werden + e.printStackTrace(); + } + } + + // Methode mit benutzerdefinierter Konstante für das Encoding + private static final String ENCODING_UTF8 = "UTF-8"; + + static void blc() throws FileNotFoundException, UnsupportedEncodingException { + Formatter s = new Formatter(new File("asdf"), ENCODING_UTF8); // 'UTF-8' als Konstante + } + + // Methode mit einer ungültigen Kodierung (z.B. 'non-existing-encoding') + static void bld() throws FileNotFoundException { + try { + Formatter s = new Formatter(new File("asdf"), "non-existing-encoding"); // wirft UnsupportedEncodingException + } catch (FileNotFoundException | UnsupportedEncodingException e) { + e.printStackTrace(); // UnsupportedEncodingException wird hier erwartet + } + } + + // Methode, die eine ungültige Kodierung und ein try-catch verwendet + static void ble() throws FileNotFoundException { + try { + Formatter s = new Formatter(new File("asdf"), "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (FileNotFoundException e) { + // Datei nicht gefunden, hier wird FileNotFoundException behandelt + e.printStackTrace(); + } catch (UnsupportedEncodingException e) { + // UnsupportedEncodingException wird hier behandelt + e.printStackTrace(); + } + } + + // Methode mit StandardCharsets.UTF_8 + static void blf() throws FileNotFoundException { + Formatter s = new Formatter(new File("asdf"), StandardCharsets.UTF_8); // Verwendung von StandardCharsets.UTF_8 + } + + // Beispiel, bei dem das Encoding in einer Variablen gespeichert ist + private String encodingVar = "UTF-8"; + + static void blg() throws FileNotFoundException { + String encoding = "UTF-8"; + Formatter s = new Formatter(new File("asdf"), encoding); // encoding als Variable + } +} +""", """ +package test1; + +import java.io.File; +import java.io.FileNotFoundException; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.Formatter; + +public class E1 { + + private static final Charset UTF_8 = StandardCharsets.UTF_8; + + // Methode mit explizitem UTF-8, sollte durch StandardCharsets.UTF_8 ersetzt werden + static void bla() throws FileNotFoundException { + Formatter s = new Formatter(new File("asdf"), E1.UTF_8); // 'UTF-8' wird zu StandardCharsets.UTF_8 + } + + // Methode mit try-catch, die eine Kodierung verwendet und Fehler wirft + static void bli() throws FileNotFoundException { + try { + Formatter s = new Formatter(new File("asdf"), E1.UTF_8); // 'UTF-8' wird zu StandardCharsets.UTF_8 + } catch (FileNotFoundException e) { + // Der Catch-Block für UnsupportedEncodingException sollte im Cleanup entfernt werden + e.printStackTrace(); + } + } + + // Methode mit benutzerdefinierter Konstante für das Encoding + private static final String ENCODING_UTF8 = "UTF-8"; + + static void blc() throws FileNotFoundException, UnsupportedEncodingException { + Formatter s = new Formatter(new File("asdf"), ENCODING_UTF8); // 'UTF-8' als Konstante + } + + // Methode mit einer ungültigen Kodierung (z.B. 'non-existing-encoding') + static void bld() throws FileNotFoundException { + try { + Formatter s = new Formatter(new File("asdf"), "non-existing-encoding"); // wirft UnsupportedEncodingException + } catch (FileNotFoundException | UnsupportedEncodingException e) { + e.printStackTrace(); // UnsupportedEncodingException wird hier erwartet + } + } + + // Methode, die eine ungültige Kodierung und ein try-catch verwendet + static void ble() throws FileNotFoundException { + try { + Formatter s = new Formatter(new File("asdf"), "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (FileNotFoundException e) { + // Datei nicht gefunden, hier wird FileNotFoundException behandelt + e.printStackTrace(); + } catch (UnsupportedEncodingException e) { + // UnsupportedEncodingException wird hier behandelt + e.printStackTrace(); + } + } + + // Methode mit StandardCharsets.UTF_8 + static void blf() throws FileNotFoundException { + Formatter s = new Formatter(new File("asdf"), StandardCharsets.UTF_8); // Verwendung von StandardCharsets.UTF_8 + } + + // Beispiel, bei dem das Encoding in einer Variablen gespeichert ist + private String encodingVar = "UTF-8"; + + static void blg() throws FileNotFoundException { + String encoding = "UTF-8"; + Formatter s = new Formatter(new File("asdf"), encoding); // encoding als Variable + } +} +"""), + THREE(""" + package test1; + + import java.io.ByteArrayOutputStream; + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Reader; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + String s="asdf"; //$NON-NLS-1$ + byte[] bytes= s.getBytes(); + System.out.println(bytes.length); + ByteArrayOutputStream ba=new ByteArrayOutputStream(); + String result=ba.toString(); + try { + InputStreamReader is=new InputStreamReader(new FileInputStream("")); //$NON-NLS-1$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + try { + OutputStreamWriter os=new OutputStreamWriter(new FileOutputStream("")); //$NON-NLS-1$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + try { + Reader is=new FileReader(filename); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } + } + """, + + """ +package test1; + +import java.io.ByteArrayOutputStream; +import java.io.InputStreamReader; +import java.io.FileInputStream; +import java.io.FileReader; +import java.io.Reader; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.io.FileNotFoundException; + +public class E1 { + private static final Charset UTF_8 = StandardCharsets.UTF_8; + + void method(String filename) { + String s="asdf"; //$NON-NLS-1$ + byte[] bytes= s.getBytes(E1.UTF_8); + System.out.println(bytes.length); + ByteArrayOutputStream ba=new ByteArrayOutputStream(); + String result=ba.toString(E1.UTF_8); + try { + InputStreamReader is=new InputStreamReader(new FileInputStream(""), E1.UTF_8); //$NON-NLS-1$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + try { + OutputStreamWriter os=new OutputStreamWriter(new FileOutputStream(""), E1.UTF_8); //$NON-NLS-1$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + try { + Reader is=new InputStreamReader(new FileInputStream(filename), E1.UTF_8); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } +} + """), + ENCODINGASSTRINGPARAMETER( + """ + package test1; + + import java.io.ByteArrayOutputStream; + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Reader; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + String s="asdf"; //$NON-NLS-1$ + //byte[] bytes= s.getBytes(StandardCharsets.UTF_8); + byte[] bytes= s.getBytes("Utf-8"); + System.out.println(bytes.length); + ByteArrayOutputStream ba=new ByteArrayOutputStream(); + String result=ba.toString(); + try { + InputStreamReader is=new InputStreamReader(new FileInputStream(""), "UTF-8"); //$NON-NLS-1$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + try { + OutputStreamWriter os=new OutputStreamWriter(new FileOutputStream(""), "UTF-8"); //$NON-NLS-1$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + try { + Reader is=new FileReader(filename); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } + } + """, + + """ +package test1; + +import java.io.ByteArrayOutputStream; +import java.io.InputStreamReader; +import java.io.FileInputStream; +import java.io.FileReader; +import java.io.Reader; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.io.FileNotFoundException; + +public class E1 { + private static final Charset UTF_8 = StandardCharsets.UTF_8; + + void method(String filename) { + String s="asdf"; //$NON-NLS-1$ + //byte[] bytes= s.getBytes(StandardCharsets.UTF_8); + byte[] bytes= s.getBytes(E1.UTF_8); + System.out.println(bytes.length); + ByteArrayOutputStream ba=new ByteArrayOutputStream(); + String result=ba.toString(E1.UTF_8); + try { + InputStreamReader is=new InputStreamReader(new FileInputStream(""), E1.UTF_8); //$NON-NLS-1$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + try { + OutputStreamWriter os=new OutputStreamWriter(new FileOutputStream(""), E1.UTF_8); //$NON-NLS-1$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + try { + Reader is=new InputStreamReader(new FileInputStream(filename), E1.UTF_8); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } +} + """); + + String given; + String expected; + + ExplicitEncodingPatternsAggregateUTF8(String given, String expected) { + this.given= given; + this.expected= expected; + } + } \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/Java10/ExplicitEncodingPatternsKeepBehavior.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/Java10/ExplicitEncodingPatternsKeepBehavior.java new file mode 100644 index 00000000000..d37cc2b8cf0 --- /dev/null +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/Java10/ExplicitEncodingPatternsKeepBehavior.java @@ -0,0 +1,1874 @@ +/******************************************************************************* + * Copyright (c) 2024 Carsten Hammer and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.quickfix.Java10; + +public enum ExplicitEncodingPatternsKeepBehavior { + + CHARSET(""" +package test1; + +import java.nio.charset.Charset; + +public class E1 { + @SuppressWarnings("unused") + void method(String filename) { + Charset cs1= Charset.forName("UTF-8"); //$NON-NLS-1$ + Charset cs1b= Charset.forName("Utf-8"); //$NON-NLS-1$ + Charset cs2= Charset.forName("UTF-16"); //$NON-NLS-1$ + Charset cs3= Charset.forName("UTF-16BE"); //$NON-NLS-1$ + Charset cs4= Charset.forName("UTF-16LE"); //$NON-NLS-1$ + Charset cs5= Charset.forName("ISO-8859-1"); //$NON-NLS-1$ + Charset cs6= Charset.forName("US-ASCII"); //$NON-NLS-1$ + String result= cs1.toString(); + } +} + """, + """ +package test1; + +import java.nio.charset.Charset; + +public class E1 { + @SuppressWarnings("unused") + void method(String filename) { + Charset cs1= Charset.forName("UTF-8"); //$NON-NLS-1$ + Charset cs1b= Charset.forName("Utf-8"); //$NON-NLS-1$ + Charset cs2= Charset.forName("UTF-16"); //$NON-NLS-1$ + Charset cs3= Charset.forName("UTF-16BE"); //$NON-NLS-1$ + Charset cs4= Charset.forName("UTF-16LE"); //$NON-NLS-1$ + Charset cs5= Charset.forName("ISO-8859-1"); //$NON-NLS-1$ + Charset cs6= Charset.forName("US-ASCII"); //$NON-NLS-1$ + String result= cs1.toString(); + } +} + """), + BYTEARRAYOUTSTREAM(""" + package test1; + + import java.io.ByteArrayOutputStream; + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Reader; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + ByteArrayOutputStream ba=new ByteArrayOutputStream(); + String result=ba.toString(); + ByteArrayOutputStream ba2=new ByteArrayOutputStream(); + String result2=ba2.toString("UTF-8"); + } + } + } + """, + + """ + package test1; + + import java.io.ByteArrayOutputStream; + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Reader; + import java.nio.charset.Charset; + import java.nio.charset.StandardCharsets; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + ByteArrayOutputStream ba=new ByteArrayOutputStream(); + String result=ba.toString(Charset.defaultCharset()); + ByteArrayOutputStream ba2=new ByteArrayOutputStream(); + String result2=ba2.toString(StandardCharsets.UTF_8); + } + } + } + """), + FILEREADER(""" + package test1; + + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Reader; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + try { + Reader is=new FileReader(filename); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } + } + """, + + """ + package test1; + + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Reader; + import java.nio.charset.Charset; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + try { + Reader is=new InputStreamReader(new FileInputStream(filename), Charset.defaultCharset()); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } + } + """), + FILEWRITER(""" + package test1; + + import java.io.FileWriter; + import java.io.Writer; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + try { + Writer fw=new FileWriter(filename); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } + } + """, + + """ + package test1; + + import java.io.FileWriter; + import java.io.OutputStreamWriter; + import java.io.Writer; + import java.nio.charset.Charset; + import java.io.FileNotFoundException; + import java.io.FileOutputStream; + + public class E1 { + void method(String filename) { + try { + Writer fw=new OutputStreamWriter(new FileOutputStream(filename), Charset.defaultCharset()); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } + } + """), + INPUTSTREAMREADER( +""" +package test1; + +import java.io.InputStreamReader; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.UnsupportedEncodingException; + +public class E1 { + + void method(String filename) { + try { + // Standardkonstruktor ohne Encoding + InputStreamReader is1 = new InputStreamReader(new FileInputStream("file1.txt")); //$NON-NLS-1$ + + // String Literal Encodings, die nach StandardCharsets umgeschrieben werden sollten + InputStreamReader is2 = new InputStreamReader(new FileInputStream("file2.txt"), "UTF-8"); //$NON-NLS-1$ //$NON-NLS-2$ + InputStreamReader is3 = new InputStreamReader(new FileInputStream("file3.txt"), "ISO-8859-1"); //$NON-NLS-1$ //$NON-NLS-2$ + InputStreamReader is4 = new InputStreamReader(new FileInputStream("file4.txt"), "US-ASCII"); //$NON-NLS-1$ //$NON-NLS-2$ + + // String-basiertes Encoding, das in Charset umgeschrieben werden kann, jedoch ohne vordefinierte Konstante + InputStreamReader is5 = new InputStreamReader(new FileInputStream("file5.txt"), "UTF-16"); //$NON-NLS-1$ //$NON-NLS-2$ + + // String-basierte Encodings mit Groß-/Kleinschreibungsvarianten + InputStreamReader is6 = new InputStreamReader(new FileInputStream("file6.txt"), "utf-8"); //$NON-NLS-1$ //$NON-NLS-2$ + InputStreamReader is7 = new InputStreamReader(new FileInputStream("file7.txt"), "Utf-8"); //$NON-NLS-1$ //$NON-NLS-2$ + + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); // Sollte nach Cleanup entfernt werden + } + } + + void methodWithTryCatch(String filename) { + try { + // Variante, bei der UnsupportedEncodingException behandelt wird + InputStreamReader is8 = new InputStreamReader(new FileInputStream("file8.txt"), "UTF-8"); //$NON-NLS-1$ //$NON-NLS-2$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); // Sollte nach Cleanup entfernt werden + } + } + + void methodWithoutException(String filename) throws UnsupportedEncodingException, FileNotFoundException { + // Case ohne Try-Catch-Block, sollte Charset-Konstanten direkt ersetzen + InputStreamReader is9 = new InputStreamReader(new FileInputStream("file9.txt"), "UTF-8"); //$NON-NLS-1$ //$NON-NLS-2$ + } + + void methodWithVariableEncoding(String filename) throws UnsupportedEncodingException, FileNotFoundException { + // Case, bei dem das Encoding aus einer Variablen kommt, Cleanup sollte hier keine Änderungen machen + String encoding = "UTF-8"; //$NON-NLS-1$ + InputStreamReader is10 = new InputStreamReader(new FileInputStream("file10.txt"), encoding); //$NON-NLS-1$ + } + + void methodWithNonStandardEncoding(String filename) { + try { + // Case mit nicht vordefiniertem Charset, sollte keine Umwandlung in StandardCharsets erfolgen + InputStreamReader is11 = new InputStreamReader(new FileInputStream("file11.txt"), "windows-1252"); //$NON-NLS-1$ //$NON-NLS-2$ + } catch (FileNotFoundException | UnsupportedEncodingException e) { + e.printStackTrace(); + } + } + + // Methode mit "throws UnsupportedEncodingException" zur Prüfung des Cleanups + void methodWithThrows(String filename) throws FileNotFoundException, UnsupportedEncodingException { + InputStreamReader is3 = new InputStreamReader(new FileInputStream(filename), "UTF-8"); //$NON-NLS-1$ + } +} +""", + +""" +package test1; + +import java.io.InputStreamReader; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.io.FileInputStream; +import java.io.FileNotFoundException; + +public class E1 { + + void method(String filename) { + try { + // Standardkonstruktor ohne Encoding + InputStreamReader is1 = new InputStreamReader(new FileInputStream("file1.txt"), Charset.defaultCharset()); //$NON-NLS-1$ + + // String Literal Encodings, die nach StandardCharsets umgeschrieben werden sollten + InputStreamReader is2 = new InputStreamReader(new FileInputStream("file2.txt"), StandardCharsets.UTF_8); //$NON-NLS-1$ //$NON-NLS-2$ + InputStreamReader is3 = new InputStreamReader(new FileInputStream("file3.txt"), StandardCharsets.ISO_8859_1); //$NON-NLS-1$ //$NON-NLS-2$ + InputStreamReader is4 = new InputStreamReader(new FileInputStream("file4.txt"), StandardCharsets.US_ASCII); //$NON-NLS-1$ //$NON-NLS-2$ + + // String-basiertes Encoding, das in Charset umgeschrieben werden kann, jedoch ohne vordefinierte Konstante + InputStreamReader is5 = new InputStreamReader(new FileInputStream("file5.txt"), StandardCharsets.UTF_16); //$NON-NLS-1$ //$NON-NLS-2$ + + // String-basierte Encodings mit Groß-/Kleinschreibungsvarianten + InputStreamReader is6 = new InputStreamReader(new FileInputStream("file6.txt"), StandardCharsets.UTF_8); //$NON-NLS-1$ //$NON-NLS-2$ + InputStreamReader is7 = new InputStreamReader(new FileInputStream("file7.txt"), StandardCharsets.UTF_8); //$NON-NLS-1$ //$NON-NLS-2$ + + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + + void methodWithTryCatch(String filename) { + try { + // Variante, bei der UnsupportedEncodingException behandelt wird + InputStreamReader is8 = new InputStreamReader(new FileInputStream("file8.txt"), StandardCharsets.UTF_8); //$NON-NLS-1$ //$NON-NLS-2$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + + void methodWithoutException(String filename) throws FileNotFoundException { + // Case ohne Try-Catch-Block, sollte Charset-Konstanten direkt ersetzen + InputStreamReader is9 = new InputStreamReader(new FileInputStream("file9.txt"), StandardCharsets.UTF_8); //$NON-NLS-1$ //$NON-NLS-2$ + } + + void methodWithVariableEncoding(String filename) throws UnsupportedEncodingException, FileNotFoundException { + // Case, bei dem das Encoding aus einer Variablen kommt, Cleanup sollte hier keine Änderungen machen + String encoding = "UTF-8"; //$NON-NLS-1$ + InputStreamReader is10 = new InputStreamReader(new FileInputStream("file10.txt"), encoding); //$NON-NLS-1$ + } + + void methodWithNonStandardEncoding(String filename) { + try { + // Case mit nicht vordefiniertem Charset, sollte keine Umwandlung in StandardCharsets erfolgen + InputStreamReader is11 = new InputStreamReader(new FileInputStream("file11.txt"), "windows-1252"); //$NON-NLS-1$ //$NON-NLS-2$ + } catch (FileNotFoundException | UnsupportedEncodingException e) { + e.printStackTrace(); + } + } + + // Methode mit "throws UnsupportedEncodingException" zur Prüfung des Cleanups + void methodWithThrows(String filename) throws FileNotFoundException { + InputStreamReader is3 = new InputStreamReader(new FileInputStream(filename), StandardCharsets.UTF_8); //$NON-NLS-1$ + } +} +"""), + OUTPUTSTREAMWRITER( +""" +package test1; + +import java.io.FileOutputStream; +import java.io.OutputStreamWriter; +import java.io.FileNotFoundException; +import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; + +public class E1 { + private static final String ENCODING_UTF8 = "UTF-8"; // Konstante für Encoding + + void method(String filename) { + try { + // Standard-Konstruktor ohne Encoding + OutputStreamWriter os1 = new OutputStreamWriter(new FileOutputStream(filename)); + + // Konstruktor mit String-Encoding (UTF-8) -> muss durch StandardCharsets.UTF_8 ersetzt werden + OutputStreamWriter os2 = new OutputStreamWriter(new FileOutputStream(filename), "UTF-8"); // "UTF-8" als String-Literal + + // Konstruktor mit String-Encoding (ISO-8859-1) -> muss durch StandardCharsets.ISO_8859_1 ersetzt werden + OutputStreamWriter os3 = new OutputStreamWriter(new FileOutputStream(filename), "ISO-8859-1"); // "ISO-8859-1" als String-Literal + + // Konstruktor mit String-Encoding (US-ASCII) -> muss durch StandardCharsets.US_ASCII ersetzt werden + OutputStreamWriter os4 = new OutputStreamWriter(new FileOutputStream(filename), "US-ASCII"); // "US-ASCII" als String-Literal + + // Konstruktor mit String-Encoding (UTF-16) -> muss durch StandardCharsets.UTF_16 ersetzt werden + OutputStreamWriter os5 = new OutputStreamWriter(new FileOutputStream(filename), "UTF-16"); // "UTF-16" als String-Literal + + // Der Konstruktor mit einer benutzerdefinierten Konstante bleibt unverändert + OutputStreamWriter os6 = new OutputStreamWriter(new FileOutputStream(filename), ENCODING_UTF8); // bleibt unverändert + + // Fälle ohne Entsprechung in StandardCharsets (bleiben unverändert) + OutputStreamWriter os7 = new OutputStreamWriter(new FileOutputStream(filename), "windows-1252"); // bleibt unverändert + OutputStreamWriter os8 = new OutputStreamWriter(new FileOutputStream(filename), "Shift_JIS"); // bleibt unverändert + + // Hier wird `UnsupportedEncodingException` geworfen (vor dem Cleanup) + OutputStreamWriter os9 = new OutputStreamWriter(new FileOutputStream(filename), "non-existing-encoding"); // wirft UnsupportedEncodingException + + // Aufruf mit einer ungültigen Zeichenkodierung und catch für UnsupportedEncodingException + try { + OutputStreamWriter os10 = new OutputStreamWriter(new FileOutputStream(filename), "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (UnsupportedEncodingException e) { + // Hier wird die UnsupportedEncodingException abgefangen + e.printStackTrace(); + } + + // Beispiele mit StandardCharsets-Konstanten, die unverändert bleiben + OutputStreamWriter os11 = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.UTF_8); // bleibt unverändert + OutputStreamWriter os12 = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.ISO_8859_1); // bleibt unverändert + OutputStreamWriter os13 = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.US_ASCII); // bleibt unverändert + OutputStreamWriter os14 = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.UTF_16); // bleibt unverändert + + // Beispiel mit Charset.forName und einer Konstanten, die als Parameter übergeben wird (bleibt unverändert) + OutputStreamWriter os15 = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.UTF_16); + } catch (FileNotFoundException e) { + // Datei nicht gefunden + e.printStackTrace(); + } catch (UnsupportedEncodingException e) { + // Hier wird die UnsupportedEncodingException abgefangen + e.printStackTrace(); + } + } + + // Methodendeklaration, die `UnsupportedEncodingException` wirft (und durch den Cleanup angepasst wird) + void methodWithThrows(String filename) throws UnsupportedEncodingException { + OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(filename), "non-existing-encoding"); // wirft UnsupportedEncodingException + } + + // Neue Methode: methodWithThrowsChange() - nach dem Cleanup wird keine UnsupportedEncodingException mehr geworfen + void methodWithThrowsChange(String filename) throws FileNotFoundException { + // Nach dem Cleanup, der String "UTF-8" wird zu einer StandardCharset-Konstanten geändert + OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(filename), "UTF-8"); // wirft keine UnsupportedEncodingException mehr + } + + // Methode mit einem try-catch, um die UnsupportedEncodingException zu behandeln (und durch den Cleanup angepasst wird) + void methodWithCatch(String filename) { + try { + OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(filename), "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (UnsupportedEncodingException e) { + // Hier wird die UnsupportedEncodingException abgefangen + e.printStackTrace(); + } + } + + // Neue Methode: methodWithCatchChange() - nach dem Cleanup wird keine UnsupportedEncodingException mehr abgefangen + void methodWithCatchChange(String filename) { + try { + // Nach dem Cleanup wird "UTF-8" ersetzt + OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(filename), "UTF-8"); // keine UnsupportedEncodingException + } catch (UnsupportedEncodingException e) { + // Dieser Block wird nicht mehr erreicht, da keine UnsupportedEncodingException mehr geworfen wird + e.printStackTrace(); + } + } +} +""", + +""" +package test1; + +import java.io.FileOutputStream; +import java.io.OutputStreamWriter; +import java.io.FileNotFoundException; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; + +public class E1 { + private static final String ENCODING_UTF8 = "UTF-8"; // Konstante für Encoding + + void method(String filename) { + try { + // Standard-Konstruktor ohne Encoding + OutputStreamWriter os1 = new OutputStreamWriter(new FileOutputStream(filename), Charset.defaultCharset()); + + // Konstruktor mit String-Encoding (UTF-8) -> muss durch StandardCharsets.UTF_8 ersetzt werden + OutputStreamWriter os2 = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.UTF_8); // "UTF-8" als String-Literal + + // Konstruktor mit String-Encoding (ISO-8859-1) -> muss durch StandardCharsets.ISO_8859_1 ersetzt werden + OutputStreamWriter os3 = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.ISO_8859_1); // "ISO-8859-1" als String-Literal + + // Konstruktor mit String-Encoding (US-ASCII) -> muss durch StandardCharsets.US_ASCII ersetzt werden + OutputStreamWriter os4 = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.US_ASCII); // "US-ASCII" als String-Literal + + // Konstruktor mit String-Encoding (UTF-16) -> muss durch StandardCharsets.UTF_16 ersetzt werden + OutputStreamWriter os5 = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.UTF_16); // "UTF-16" als String-Literal + + // Der Konstruktor mit einer benutzerdefinierten Konstante bleibt unverändert + OutputStreamWriter os6 = new OutputStreamWriter(new FileOutputStream(filename), ENCODING_UTF8); // bleibt unverändert + + // Fälle ohne Entsprechung in StandardCharsets (bleiben unverändert) + OutputStreamWriter os7 = new OutputStreamWriter(new FileOutputStream(filename), "windows-1252"); // bleibt unverändert + OutputStreamWriter os8 = new OutputStreamWriter(new FileOutputStream(filename), "Shift_JIS"); // bleibt unverändert + + // Hier wird `UnsupportedEncodingException` geworfen (vor dem Cleanup) + OutputStreamWriter os9 = new OutputStreamWriter(new FileOutputStream(filename), "non-existing-encoding"); // wirft UnsupportedEncodingException + + // Aufruf mit einer ungültigen Zeichenkodierung und catch für UnsupportedEncodingException + try { + OutputStreamWriter os10 = new OutputStreamWriter(new FileOutputStream(filename), "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (UnsupportedEncodingException e) { + // Hier wird die UnsupportedEncodingException abgefangen + e.printStackTrace(); + } + + // Beispiele mit StandardCharsets-Konstanten, die unverändert bleiben + OutputStreamWriter os11 = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.UTF_8); // bleibt unverändert + OutputStreamWriter os12 = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.ISO_8859_1); // bleibt unverändert + OutputStreamWriter os13 = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.US_ASCII); // bleibt unverändert + OutputStreamWriter os14 = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.UTF_16); // bleibt unverändert + + // Beispiel mit Charset.forName und einer Konstanten, die als Parameter übergeben wird (bleibt unverändert) + OutputStreamWriter os15 = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.UTF_16); + } catch (FileNotFoundException e) { + // Datei nicht gefunden + e.printStackTrace(); + } + } + + // Methodendeklaration, die `UnsupportedEncodingException` wirft (und durch den Cleanup angepasst wird) + void methodWithThrows(String filename) throws UnsupportedEncodingException { + OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(filename), "non-existing-encoding"); // wirft UnsupportedEncodingException + } + + // Neue Methode: methodWithThrowsChange() - nach dem Cleanup wird keine UnsupportedEncodingException mehr geworfen + void methodWithThrowsChange(String filename) throws FileNotFoundException { + // Nach dem Cleanup, der String "UTF-8" wird zu einer StandardCharset-Konstanten geändert + OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.UTF_8); // wirft keine UnsupportedEncodingException mehr + } + + // Methode mit einem try-catch, um die UnsupportedEncodingException zu behandeln (und durch den Cleanup angepasst wird) + void methodWithCatch(String filename) { + try { + OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(filename), "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (UnsupportedEncodingException e) { + // Hier wird die UnsupportedEncodingException abgefangen + e.printStackTrace(); + } + } + + // Neue Methode: methodWithCatchChange() - nach dem Cleanup wird keine UnsupportedEncodingException mehr abgefangen + void methodWithCatchChange(String filename) { + try { + // Nach dem Cleanup wird "UTF-8" ersetzt + OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.UTF_8); // keine UnsupportedEncodingException + } + } +} +"""), + CHANNELSNEWREADER( +""" +package test1; + +import java.io.Reader; +import java.nio.channels.ReadableByteChannel; +import java.nio.channels.Channels; +import java.nio.charset.StandardCharsets; +import java.nio.charset.CharsetDecoder; + +public class E1 { + private static final String ENCODING_UTF8 = "UTF-8"; // Konstante für Encoding + + void method(ReadableByteChannel ch, CharsetDecoder decoder) { + // Fälle für StandardCharsets-Konstanten + Reader r1 = Channels.newReader(ch, "UTF-8"); // soll StandardCharsets.UTF_8 werden + Reader r2 = Channels.newReader(ch, "ISO-8859-1"); // soll StandardCharsets.ISO_8859_1 werden + Reader r3 = Channels.newReader(ch, "US-ASCII"); // soll StandardCharsets.US_ASCII werden + Reader r4 = Channels.newReader(ch, "UTF-16"); // soll StandardCharsets.UTF_16 werden + + // Aufruf mit einer String-Konstanten (soll unverändert bleiben) + Reader r5 = Channels.newReader(ch, ENCODING_UTF8); // bleibt unverändert + + // Fälle ohne Entsprechung in StandardCharsets (sollen unverändert bleiben) + Reader r6 = Channels.newReader(ch, "windows-1252"); // bleibt unverändert + Reader r7 = Channels.newReader(ch, "Shift_JIS"); // bleibt unverändert + + // Aufrufe, die bereits `StandardCharsets` verwenden (bleiben unverändert) + Reader r8 = Channels.newReader(ch, StandardCharsets.UTF_8); + Reader r9 = Channels.newReader(ch, decoder, 1024); // mit CharsetDecoder und Buffergröße, bleibt unverändert + } +} +""", + +""" +package test1; + +import java.io.Reader; +import java.nio.channels.ReadableByteChannel; +import java.nio.channels.Channels; +import java.nio.charset.StandardCharsets; +import java.nio.charset.CharsetDecoder; + +public class E1 { + private static final String ENCODING_UTF8 = "UTF-8"; // Konstante für Encoding + + void method(ReadableByteChannel ch, CharsetDecoder decoder) { + // Fälle für StandardCharsets-Konstanten + Reader r1 = Channels.newReader(ch, StandardCharsets.UTF_8); // soll StandardCharsets.UTF_8 werden + Reader r2 = Channels.newReader(ch, StandardCharsets.ISO_8859_1); // soll StandardCharsets.ISO_8859_1 werden + Reader r3 = Channels.newReader(ch, StandardCharsets.US_ASCII); // soll StandardCharsets.US_ASCII werden + Reader r4 = Channels.newReader(ch, StandardCharsets.UTF_16); // soll StandardCharsets.UTF_16 werden + + // Aufruf mit einer String-Konstanten (soll unverändert bleiben) + Reader r5 = Channels.newReader(ch, ENCODING_UTF8); // bleibt unverändert + + // Fälle ohne Entsprechung in StandardCharsets (sollen unverändert bleiben) + Reader r6 = Channels.newReader(ch, "windows-1252"); // bleibt unverändert + Reader r7 = Channels.newReader(ch, "Shift_JIS"); // bleibt unverändert + + // Aufrufe, die bereits `StandardCharsets` verwenden (bleiben unverändert) + Reader r8 = Channels.newReader(ch, StandardCharsets.UTF_8); + Reader r9 = Channels.newReader(ch, decoder, 1024); // mit CharsetDecoder und Buffergröße, bleibt unverändert + } +} +"""), + CHANNELSNEWWRITER( +""" +package test1; + +import java.io.Writer; +import java.nio.channels.WritableByteChannel; +import java.nio.channels.Channels; +import java.nio.charset.StandardCharsets; +import java.nio.charset.Charset; + +public class E1 { + private static final String ENCODING_UTF8 = "UTF-8"; // Konstante für Encoding + + void method(WritableByteChannel ch, Charset charset) { + // Fälle für StandardCharsets-Konstanten + Writer w1 = Channels.newWriter(ch, "UTF-8"); // soll StandardCharsets.UTF_8 werden + Writer w2 = Channels.newWriter(ch, "ISO-8859-1"); // soll StandardCharsets.ISO_8859_1 werden + Writer w3 = Channels.newWriter(ch, "US-ASCII"); // soll StandardCharsets.US_ASCII werden + Writer w4 = Channels.newWriter(ch, "UTF-16"); // soll StandardCharsets.UTF_16 werden + + // Aufruf mit einer String-Konstanten (soll unverändert bleiben) + Writer w5 = Channels.newWriter(ch, ENCODING_UTF8); // bleibt unverändert + + // Fälle ohne Entsprechung in StandardCharsets (sollen unverändert bleiben) + Writer w6 = Channels.newWriter(ch, "windows-1252"); // bleibt unverändert + Writer w7 = Channels.newWriter(ch, "Shift_JIS"); // bleibt unverändert + + // Aufrufe, die bereits `StandardCharsets` verwenden (bleiben unverändert) + Writer w8 = Channels.newWriter(ch, StandardCharsets.UTF_8); + Writer w9 = Channels.newWriter(ch, charset); // unverändert, da `Charset` Instanz verwendet + } +} +""", + +""" +package test1; + +import java.io.Writer; +import java.nio.channels.WritableByteChannel; +import java.nio.channels.Channels; +import java.nio.charset.StandardCharsets; +import java.nio.charset.Charset; + +public class E1 { + private static final String ENCODING_UTF8 = "UTF-8"; // Konstante für Encoding + + void method(WritableByteChannel ch, Charset charset) { + // Fälle für StandardCharsets-Konstanten + Writer w1 = Channels.newWriter(ch, StandardCharsets.UTF_8); // soll StandardCharsets.UTF_8 werden + Writer w2 = Channels.newWriter(ch, StandardCharsets.ISO_8859_1); // soll StandardCharsets.ISO_8859_1 werden + Writer w3 = Channels.newWriter(ch, StandardCharsets.US_ASCII); // soll StandardCharsets.US_ASCII werden + Writer w4 = Channels.newWriter(ch, StandardCharsets.UTF_16); // soll StandardCharsets.UTF_16 werden + + // Aufruf mit einer String-Konstanten (soll unverändert bleiben) + Writer w5 = Channels.newWriter(ch, ENCODING_UTF8); // bleibt unverändert + + // Fälle ohne Entsprechung in StandardCharsets (sollen unverändert bleiben) + Writer w6 = Channels.newWriter(ch, "windows-1252"); // bleibt unverändert + Writer w7 = Channels.newWriter(ch, "Shift_JIS"); // bleibt unverändert + + // Aufrufe, die bereits `StandardCharsets` verwenden (bleiben unverändert) + Writer w8 = Channels.newWriter(ch, StandardCharsets.UTF_8); + Writer w9 = Channels.newWriter(ch, charset); // unverändert, da `Charset` Instanz verwendet + } +} +"""), + PRINTWRITER(""" + package test1; + + import java.io.PrintWriter; + import java.io.Writer; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + try { + Writer w=new PrintWriter(filename); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } + } + """, + + """ + package test1; + + import java.io.PrintWriter; + import java.io.Writer; + import java.nio.charset.Charset; + import java.io.BufferedWriter; + import java.io.FileNotFoundException; + import java.io.FileOutputStream; + import java.io.OutputStreamWriter; + + public class E1 { + void method(String filename) { + try { + Writer w=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename), Charset.defaultCharset())); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } + } + """), + STRINGGETBYTES( +""" +package test1; + +import java.nio.charset.StandardCharsets; + +public class E1 { + + // Methode 1: Verwendung von StandardCharsets.UTF_8 statt "UTF-8" als String-Literal + void method(String filename) { + String s = "asdf"; //$NON-NLS-1$ + + // Vorher: getBytes ohne Angabe der Kodierung (verwendet die Plattform-spezifische Standard-Kodierung) + byte[] bytes = s.getBytes(); + + // Nachher: Umstellung auf StandardCharsets.UTF_8 + byte[] bytes2 = s.getBytes(StandardCharsets.UTF_8); + + System.out.println(bytes.length); + System.out.println(bytes2.length); + } + + // Methode 2: Behandlung von getBytes mit einer expliziten Kodierung + void method2(String filename) { + String s = "asdf"; //$NON-NLS-1$ + + // Vorher: getBytes mit expliziter Kodierung (UTF-8 als String-Literal) + byte[] bytes = s.getBytes("UTF-8"); + + // Nachher: Umstellung auf StandardCharsets.UTF_8 + byte[] bytes2 = s.getBytes(StandardCharsets.UTF_8); + + System.out.println(bytes.length); + System.out.println(bytes2.length); + } + + // Erweiterter Testfall: Verwendung von verschiedenen Kodierungen + void methodWithDifferentEncodings(String filename) { + String s = "asdf"; + + // Testen von gängigen Kodierungen + byte[] bytes1 = s.getBytes("ISO-8859-1"); // ISO-8859-1 + byte[] bytes2 = s.getBytes("US-ASCII"); // US-ASCII + byte[] bytes3 = s.getBytes(StandardCharsets.UTF_8); // UTF-8 mit StandardCharsets + byte[] bytes4 = s.getBytes("UTF-16"); // UTF-16 + + System.out.println(bytes1.length); // Ausgabe der Längen + System.out.println(bytes2.length); + System.out.println(bytes3.length); + System.out.println(bytes4.length); + } + + // Testfall: Verwendung von getBytes mit einer ungültigen Kodierung (sollte im Cleanup behandelt werden) + void methodWithInvalidEncoding(String filename) { + String s = "asdf"; + try { + // Ungültige Kodierung, die zu UnsupportedEncodingException führt + byte[] bytes = s.getBytes("non-existing-encoding"); + } catch (UnsupportedEncodingException e) { + // Diese Ausnahme sollte im Cleanup berücksichtigt werden + e.printStackTrace(); + } + } + + // Testfall: Verwendung von getBytes mit einer durch Variable angegebenen Kodierung + void methodWithVariableEncoding(String filename) { + String s = "asdf"; + String encoding = "UTF-8"; // Kodierung als Variable + try { + byte[] bytes = s.getBytes(encoding); // Kodierung aus der Variablen + System.out.println(bytes.length); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + } +} +""", + +""" +package test1; + +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; + +public class E1 { + + // Methode 1: Verwendung von StandardCharsets.UTF_8 statt "UTF-8" als String-Literal + void method(String filename) { + String s = "asdf"; //$NON-NLS-1$ + + // Vorher: getBytes ohne Angabe der Kodierung (verwendet die Plattform-spezifische Standard-Kodierung) + byte[] bytes = s.getBytes(Charset.defaultCharset()); + + // Nachher: Umstellung auf StandardCharsets.UTF_8 + byte[] bytes2 = s.getBytes(StandardCharsets.UTF_8); + + System.out.println(bytes.length); + System.out.println(bytes2.length); + } + + // Methode 2: Behandlung von getBytes mit einer expliziten Kodierung + void method2(String filename) { + String s = "asdf"; //$NON-NLS-1$ + + // Vorher: getBytes mit expliziter Kodierung (UTF-8 als String-Literal) + byte[] bytes = s.getBytes(StandardCharsets.UTF_8); + + // Nachher: Umstellung auf StandardCharsets.UTF_8 + byte[] bytes2 = s.getBytes(StandardCharsets.UTF_8); + + System.out.println(bytes.length); + System.out.println(bytes2.length); + } + + // Erweiterter Testfall: Verwendung von verschiedenen Kodierungen + void methodWithDifferentEncodings(String filename) { + String s = "asdf"; + + // Testen von gängigen Kodierungen + byte[] bytes1 = s.getBytes(StandardCharsets.ISO_8859_1); // ISO-8859-1 + byte[] bytes2 = s.getBytes(StandardCharsets.US_ASCII); // US-ASCII + byte[] bytes3 = s.getBytes(StandardCharsets.UTF_8); // UTF-8 mit StandardCharsets + byte[] bytes4 = s.getBytes(StandardCharsets.UTF_16); // UTF-16 + + System.out.println(bytes1.length); // Ausgabe der Längen + System.out.println(bytes2.length); + System.out.println(bytes3.length); + System.out.println(bytes4.length); + } + + // Testfall: Verwendung von getBytes mit einer ungültigen Kodierung (sollte im Cleanup behandelt werden) + void methodWithInvalidEncoding(String filename) { + String s = "asdf"; + try { + // Ungültige Kodierung, die zu UnsupportedEncodingException führt + byte[] bytes = s.getBytes("non-existing-encoding"); + } catch (UnsupportedEncodingException e) { + // Diese Ausnahme sollte im Cleanup berücksichtigt werden + e.printStackTrace(); + } + } + + // Testfall: Verwendung von getBytes mit einer durch Variable angegebenen Kodierung + void methodWithVariableEncoding(String filename) { + String s = "asdf"; + String encoding = "UTF-8"; // Kodierung als Variable + try { + byte[] bytes = s.getBytes(encoding); // Kodierung aus der Variablen + System.out.println(bytes.length); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + } +} +"""), + STRING( +""" +package test1; + +import java.io.FileNotFoundException; +import java.io.UnsupportedEncodingException; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; + +public class E1 { + + static void bla(String filename) throws FileNotFoundException, UnsupportedEncodingException { + byte[] b = {(byte) 59}; + + // Fälle mit String Encoding als "UTF-8" (soll durch StandardCharsets.UTF_8 ersetzt werden) + String s1 = new String(b, "UTF-8"); // "UTF-8" als String-Literal + String s2 = new String(b, 0, 1, "UTF-8"); // "UTF-8" als String-Literal + + // Fall mit ISO-8859-1 Encoding (soll durch StandardCharsets.ISO_8859_1 ersetzt werden) + String s3 = new String(b, "ISO-8859-1"); // "ISO-8859-1" als String-Literal + String s4 = new String(b, 0, 1, "ISO-8859-1"); // "ISO-8859-1" als String-Literal + + // Fall mit US-ASCII Encoding (soll durch StandardCharsets.US_ASCII ersetzt werden) + String s5 = new String(b, "US-ASCII"); // "US-ASCII" als String-Literal + String s6 = new String(b, 0, 1, "US-ASCII"); // "US-ASCII" als String-Literal + + // Fall mit UTF-16 Encoding (soll durch StandardCharsets.UTF_16 ersetzt werden) + String s7 = new String(b, "UTF-16"); // "UTF-16" als String-Literal + String s8 = new String(b, 0, 1, "UTF-16"); // "UTF-16" als String-Literal + + // Fall mit einer benutzerdefinierten Konstante für Encoding, bleibt unverändert + String s9 = new String(b, "UTF-8"); // bleibt unverändert + String s10 = new String(b, 0, 1, "UTF-8"); // bleibt unverändert + + // Fälle ohne Entsprechung in StandardCharsets, bleiben unverändert + String s11 = new String(b, "windows-1252"); // bleibt unverändert + String s12 = new String(b, 0, 1, "windows-1252"); // bleibt unverändert + String s13 = new String(b, "Shift_JIS"); // bleibt unverändert + String s14 = new String(b, 0, 1, "Shift_JIS"); // bleibt unverändert + + // Fall mit Charset.forName() (wird unverändert bleiben, keine Ersetzung möglich) + Charset charset = Charset.forName("UTF-16"); + String s15 = new String(b, charset); // bleibt unverändert + String s16 = new String(b, 0, 1, charset); // bleibt unverändert + + // Fälle, die eine UnsupportedEncodingException werfen (werden im Cleanup angepasst) + try { + String s17 = new String(b, "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (UnsupportedEncodingException e) { + // UnsupportedEncodingException wird geworfen und abgefangen + e.printStackTrace(); + } + + try { + String s18 = new String(b, 0, 1, "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (UnsupportedEncodingException e) { + // UnsupportedEncodingException wird geworfen und abgefangen + e.printStackTrace(); + } + } + + // Methodendeklaration mit throws für UnsupportedEncodingException (wird im Cleanup angepasst) + static void methodWithThrows(String filename) throws UnsupportedEncodingException { + byte[] b = {(byte) 59}; + String s1 = new String(b, "non-existing-encoding"); // wirft UnsupportedEncodingException + } + + // Nach dem Cleanup sollte dies keine UnsupportedEncodingException mehr werfen + static void methodWithThrowsChange(String filename) throws FileNotFoundException { + byte[] b = {(byte) 59}; + String s1 = new String(b, "UTF-8"); // wirft keine UnsupportedEncodingException mehr + } + + // Methodendeklaration mit try-catch für UnsupportedEncodingException (wird im Cleanup angepasst) + static void methodWithCatch(String filename) { + byte[] b = {(byte) 59}; + try { + String s1 = new String(b, "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (UnsupportedEncodingException e) { + // UnsupportedEncodingException wird geworfen und abgefangen + e.printStackTrace(); + } + } + + // Nach dem Cleanup wird keine UnsupportedEncodingException mehr abgefangen + static void methodWithCatchChange(String filename) { + byte[] b = {(byte) 59}; + try { + String s1 = new String(b, "UTF-8"); // keine UnsupportedEncodingException + } catch (UnsupportedEncodingException e) { + // Dieser Block wird nicht mehr erreicht, da keine UnsupportedEncodingException mehr geworfen wird + e.printStackTrace(); + } + } +} +""", + +""" +package test1; + +import java.io.FileNotFoundException; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; + +public class E1 { + + static void bla(String filename) throws FileNotFoundException { + byte[] b = {(byte) 59}; + + // Fälle mit String Encoding als "UTF-8" (soll durch StandardCharsets.UTF_8 ersetzt werden) + String s1 = new String(b, StandardCharsets.UTF_8); // "UTF-8" als String-Literal + String s2 = new String(b, 0, 1, StandardCharsets.UTF_8); // "UTF-8" als String-Literal + + // Fall mit ISO-8859-1 Encoding (soll durch StandardCharsets.ISO_8859_1 ersetzt werden) + String s3 = new String(b, StandardCharsets.ISO_8859_1); // "ISO-8859-1" als String-Literal + String s4 = new String(b, 0, 1, StandardCharsets.ISO_8859_1); // "ISO-8859-1" als String-Literal + + // Fall mit US-ASCII Encoding (soll durch StandardCharsets.US_ASCII ersetzt werden) + String s5 = new String(b, StandardCharsets.US_ASCII); // "US-ASCII" als String-Literal + String s6 = new String(b, 0, 1, StandardCharsets.US_ASCII); // "US-ASCII" als String-Literal + + // Fall mit UTF-16 Encoding (soll durch StandardCharsets.UTF_16 ersetzt werden) + String s7 = new String(b, StandardCharsets.UTF_16); // "UTF-16" als String-Literal + String s8 = new String(b, 0, 1, StandardCharsets.UTF_16); // "UTF-16" als String-Literal + + // Fall mit einer benutzerdefinierten Konstante für Encoding, bleibt unverändert + String s9 = new String(b, StandardCharsets.UTF_8); // bleibt unverändert + String s10 = new String(b, 0, 1, StandardCharsets.UTF_8); // bleibt unverändert + + // Fälle ohne Entsprechung in StandardCharsets, bleiben unverändert + String s11 = new String(b, "windows-1252"); // bleibt unverändert + String s12 = new String(b, 0, 1, "windows-1252"); // bleibt unverändert + String s13 = new String(b, "Shift_JIS"); // bleibt unverändert + String s14 = new String(b, 0, 1, "Shift_JIS"); // bleibt unverändert + + // Fall mit Charset.forName() (wird unverändert bleiben, keine Ersetzung möglich) + Charset charset = Charset.forName("UTF-16"); + String s15 = new String(b, charset); // bleibt unverändert + String s16 = new String(b, 0, 1, charset); // bleibt unverändert + + // Fälle, die eine UnsupportedEncodingException werfen (werden im Cleanup angepasst) + try { + String s17 = new String(b, "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (UnsupportedEncodingException e) { + // UnsupportedEncodingException wird geworfen und abgefangen + e.printStackTrace(); + } + + try { + String s18 = new String(b, 0, 1, "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (UnsupportedEncodingException e) { + // UnsupportedEncodingException wird geworfen und abgefangen + e.printStackTrace(); + } + } + + // Methodendeklaration mit throws für UnsupportedEncodingException (wird im Cleanup angepasst) + static void methodWithThrows(String filename) throws UnsupportedEncodingException { + byte[] b = {(byte) 59}; + String s1 = new String(b, "non-existing-encoding"); // wirft UnsupportedEncodingException + } + + // Nach dem Cleanup sollte dies keine UnsupportedEncodingException mehr werfen + static void methodWithThrowsChange(String filename) throws FileNotFoundException { + byte[] b = {(byte) 59}; + String s1 = new String(b, StandardCharsets.UTF_8); // wirft keine UnsupportedEncodingException mehr + } + + // Methodendeklaration mit try-catch für UnsupportedEncodingException (wird im Cleanup angepasst) + static void methodWithCatch(String filename) { + byte[] b = {(byte) 59}; + try { + String s1 = new String(b, "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (UnsupportedEncodingException e) { + // UnsupportedEncodingException wird geworfen und abgefangen + e.printStackTrace(); + } + } + + // Nach dem Cleanup wird keine UnsupportedEncodingException mehr abgefangen + static void methodWithCatchChange(String filename) { + byte[] b = {(byte) 59}; + try { + String s1 = new String(b, StandardCharsets.UTF_8); // keine UnsupportedEncodingException + } + } +} +"""), + PROPERTIESSTORETOXML( +""" +package test1; + +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; +import java.util.Properties; + +public class E1 { + private static final String ENCODING_UTF8 = "UTF-8"; // Benutzerdefinierte Konstante für Encoding + private String encodingVar = "ISO-8859-1"; // Encoding-Variable + + // Fall 1: UTF-8 als String; Cleanup soll zu StandardCharsets.UTF_8 ändern + void storeWithTryWithResources() throws IOException { + Properties p = new Properties(); + try (FileOutputStream os = new FileOutputStream("out.xml")) { + p.storeToXML(os, "Kommentar", "UTF-8"); + } + } + + // Fall 2: Benutzerdefiniertes Encoding als Variable; Cleanup soll diesen Fall unverändert lassen + void storeWithTryWithResourcesAndCustomEncoding() throws IOException { + Properties p = new Properties(); + try (FileOutputStream os = new FileOutputStream("out.xml")) { + p.storeToXML(os, "Kommentar", encodingVar); + } + } + + // Fall 3: Ungültiges Encoding als String; Cleanup soll auf StandardCharsets.UTF_8 ändern und den catch-Block entfernen + void storeWithTryWithResourcesAndInvalidEncoding() { + Properties p = new Properties(); + try (FileOutputStream os = new FileOutputStream("out.xml")) { + p.storeToXML(os, "Kommentar", "non-existing-encoding"); + } catch (UnsupportedEncodingException e) { + System.err.println("Unsupported encoding caught!"); + } + } + + // Fall 4: FileOutputStream außerhalb des try-Blocks und UTF-8 als String; Cleanup soll auf StandardCharsets.UTF_8 ändern und den catch-Block entfernen + void storeWithoutTryWithResources(String filename) throws IOException { + Properties p = new Properties(); + FileOutputStream os = new FileOutputStream(filename); + try { + p.storeToXML(os, "Kommentar", "UTF-8"); + } catch (UnsupportedEncodingException e) { + System.err.println("Unexpected UnsupportedEncodingException"); + } finally { + os.close(); // Bleibt erhalten, um die Ressource korrekt zu schließen + } + } + + // Fall 5: Gültiges Encoding ohne Konstante in StandardCharsets (windows-1252); Cleanup soll diesen Fall unverändert lassen + void storeWithWindows1252Encoding() throws IOException { + Properties p = new Properties(); + try (FileOutputStream os = new FileOutputStream("out.xml")) { + p.storeToXML(os, "Kommentar", "windows-1252"); + } + } + + // Fall 6: Gültiges Encoding ohne Konstante in StandardCharsets (Shift_JIS); Cleanup soll diesen Fall unverändert lassen + void storeWithShiftJISEncoding() throws IOException { + Properties p = new Properties(); + try (FileOutputStream os = new FileOutputStream("out.xml")) { + p.storeToXML(os, "Kommentar", "Shift_JIS"); + } + } + + // Fall 7: Ungültiges Encoding außerhalb von try-with-resources; Cleanup soll auf StandardCharsets.UTF_8 ändern und den catch-Block entfernen + void storeWithInvalidEncodingOutsideTry(String filename) throws IOException { + Properties p = new Properties(); + FileOutputStream os = new FileOutputStream(filename); + try { + p.storeToXML(os, "Kommentar", "non-existing-encoding"); + } catch (UnsupportedEncodingException e) { + System.err.println("Unsupported encoding caught!"); + } finally { + os.close(); // Bleibt erhalten, um die Ressource korrekt zu schließen + } + } + + // Fall 8: StandardCharsets.UTF_8 ohne try-with-resources; Cleanup soll diesen Fall unverändert lassen + void storeWithoutTryWithResourcesStandardCharsets(String filename) throws IOException { + Properties p = new Properties(); + FileOutputStream os = new FileOutputStream(filename); + try { + p.storeToXML(os, "Kommentar", StandardCharsets.UTF_8); + } finally { + os.close(); // Bleibt erhalten, um die Ressource korrekt zu schließen + } + } +} +""", + +""" +package test1; + +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.nio.charset.StandardCharsets; +import java.util.Properties; + +public class E1 { + private static final String ENCODING_UTF8 = "UTF-8"; // Benutzerdefinierte Konstante für Encoding + private String encodingVar = "ISO-8859-1"; // Encoding-Variable + + // Fall 1: UTF-8 als String; Cleanup soll zu StandardCharsets.UTF_8 ändern + void storeWithTryWithResources() throws IOException { + Properties p = new Properties(); + try (FileOutputStream os = new FileOutputStream("out.xml")) { + p.storeToXML(os, "Kommentar", StandardCharsets.UTF_8); + } + } + + // Fall 2: Benutzerdefiniertes Encoding als Variable; Cleanup soll diesen Fall unverändert lassen + void storeWithTryWithResourcesAndCustomEncoding() throws IOException { + Properties p = new Properties(); + try (FileOutputStream os = new FileOutputStream("out.xml")) { + p.storeToXML(os, "Kommentar", encodingVar); + } + } + + // Fall 3: Ungültiges Encoding als String; Cleanup soll auf StandardCharsets.UTF_8 ändern und den catch-Block entfernen + void storeWithTryWithResourcesAndInvalidEncoding() { + Properties p = new Properties(); + try (FileOutputStream os = new FileOutputStream("out.xml")) { + p.storeToXML(os, "Kommentar", "non-existing-encoding"); + } catch (UnsupportedEncodingException e) { + System.err.println("Unsupported encoding caught!"); + } + } + + // Fall 4: FileOutputStream außerhalb des try-Blocks und UTF-8 als String; Cleanup soll auf StandardCharsets.UTF_8 ändern und den catch-Block entfernen + void storeWithoutTryWithResources(String filename) throws IOException { + Properties p = new Properties(); + FileOutputStream os = new FileOutputStream(filename); + try { + p.storeToXML(os, "Kommentar", StandardCharsets.UTF_8); + } finally { + os.close(); // Bleibt erhalten, um die Ressource korrekt zu schließen + } + } + + // Fall 5: Gültiges Encoding ohne Konstante in StandardCharsets (windows-1252); Cleanup soll diesen Fall unverändert lassen + void storeWithWindows1252Encoding() throws IOException { + Properties p = new Properties(); + try (FileOutputStream os = new FileOutputStream("out.xml")) { + p.storeToXML(os, "Kommentar", "windows-1252"); + } + } + + // Fall 6: Gültiges Encoding ohne Konstante in StandardCharsets (Shift_JIS); Cleanup soll diesen Fall unverändert lassen + void storeWithShiftJISEncoding() throws IOException { + Properties p = new Properties(); + try (FileOutputStream os = new FileOutputStream("out.xml")) { + p.storeToXML(os, "Kommentar", "Shift_JIS"); + } + } + + // Fall 7: Ungültiges Encoding außerhalb von try-with-resources; Cleanup soll auf StandardCharsets.UTF_8 ändern und den catch-Block entfernen + void storeWithInvalidEncodingOutsideTry(String filename) throws IOException { + Properties p = new Properties(); + FileOutputStream os = new FileOutputStream(filename); + try { + p.storeToXML(os, "Kommentar", "non-existing-encoding"); + } catch (UnsupportedEncodingException e) { + System.err.println("Unsupported encoding caught!"); + } finally { + os.close(); // Bleibt erhalten, um die Ressource korrekt zu schließen + } + } + + // Fall 8: StandardCharsets.UTF_8 ohne try-with-resources; Cleanup soll diesen Fall unverändert lassen + void storeWithoutTryWithResourcesStandardCharsets(String filename) throws IOException { + Properties p = new Properties(); + FileOutputStream os = new FileOutputStream(filename); + try { + p.storeToXML(os, "Kommentar", StandardCharsets.UTF_8); + } finally { + os.close(); // Bleibt erhalten, um die Ressource korrekt zu schließen + } + } +} +"""), + URLDECODER( +""" +package test1; + +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; + +public class E2 { + private static final String ENCODING_UTF8 = "UTF-8"; // Konstante für Encoding + private String encodingVar = "ISO-8859-1"; // Variable für Encoding + + // Methode ohne Encoding-Angabe, bleibt unverändert + static void decodeDefault() { + String url = URLDecoder.decode("example"); + } + + // Methode, die "UTF-8" als String verwendet und UnsupportedEncodingException wirft + static void decodeWithThrows() throws UnsupportedEncodingException { + String url = URLDecoder.decode("example", "UTF-8"); // sollte in StandardCharsets.UTF_8 geändert werden + } + + // Methode, die eine ungültige Kodierung verwendet und `UnsupportedEncodingException` wirft + static void decodeWithInvalidEncodingThrows() throws UnsupportedEncodingException { + String url = URLDecoder.decode("example", "non-existing-encoding"); + } + + // Methode, die eine benutzerdefinierte Konstante für Encoding verwendet, bleibt unverändert + void decodeWithCustomConstant() throws UnsupportedEncodingException { + String url = URLDecoder.decode("example", ENCODING_UTF8); + } + + // Methode, die Encoding als Variable übergibt, bleibt unverändert + void decodeWithVariableEncoding() throws UnsupportedEncodingException { + String url = URLDecoder.decode("example", encodingVar); + } + + // Methode mit `try-catch`-Block für ungültiges Encoding + static void decodeWithTryCatch() { + try { + String url = URLDecoder.decode("example", "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (UnsupportedEncodingException e) { + System.err.println("Caught UnsupportedEncodingException for invalid encoding!"); + } + } + + // Beispiel mit StandardCharsets-Konstanten, bleibt unverändert + static void decodeWithStandardCharset() { + String url = URLDecoder.decode("example", StandardCharsets.UTF_8); + } +} +""", +""" +package test1; + +import java.net.URLDecoder; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; + +public class E2 { + private static final String ENCODING_UTF8 = "UTF-8"; // Konstante für Encoding + private String encodingVar = "ISO-8859-1"; // Variable für Encoding + + // Methode ohne Encoding-Angabe, bleibt unverändert + static void decodeDefault() { + String url = URLDecoder.decode("example", Charset.defaultCharset()); + } + + // Methode, die "UTF-8" als String verwendet und UnsupportedEncodingException wirft + static void decodeWithThrows() { + String url = URLDecoder.decode("example", StandardCharsets.UTF_8); // sollte in StandardCharsets.UTF_8 geändert werden + } + + // Methode, die eine ungültige Kodierung verwendet und `UnsupportedEncodingException` wirft + static void decodeWithInvalidEncodingThrows() throws UnsupportedEncodingException { + String url = URLDecoder.decode("example", "non-existing-encoding"); + } + + // Methode, die eine benutzerdefinierte Konstante für Encoding verwendet, bleibt unverändert + void decodeWithCustomConstant() throws UnsupportedEncodingException { + String url = URLDecoder.decode("example", ENCODING_UTF8); + } + + // Methode, die Encoding als Variable übergibt, bleibt unverändert + void decodeWithVariableEncoding() throws UnsupportedEncodingException { + String url = URLDecoder.decode("example", encodingVar); + } + + // Methode mit `try-catch`-Block für ungültiges Encoding + static void decodeWithTryCatch() { + try { + String url = URLDecoder.decode("example", "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (UnsupportedEncodingException e) { + System.err.println("Caught UnsupportedEncodingException for invalid encoding!"); + } + } + + // Beispiel mit StandardCharsets-Konstanten, bleibt unverändert + static void decodeWithStandardCharset() { + String url = URLDecoder.decode("example", StandardCharsets.UTF_8); + } +} +"""), + URLENCODER( +""" +package test1; + +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; + +public class E1 { + private static final String ENCODING_UTF8 = "UTF-8"; // Benutzerdefinierte Kodierungskonstante + private String encodingVar = "ISO-8859-1"; // Variable für eine Kodierung + + // Methode ohne explizite Kodierung, bleibt unverändert + static void encodeDefault() { + String url = URLEncoder.encode("example"); + } + + // Methode, die "UTF-8" als String-Literal verwendet und `throws UnsupportedEncodingException` hat + static void encodeWithThrows() throws UnsupportedEncodingException { + String url = URLEncoder.encode("example", "UTF-8"); // sollte in StandardCharsets.UTF_8 geändert werden + } + + // Methode, die eine ungültige Kodierung verwendet und `UnsupportedEncodingException` wirft + static void encodeWithInvalidEncodingThrows() throws UnsupportedEncodingException { + String url = URLEncoder.encode("example", "non-existing-encoding"); + } + + // Methode, die eine benutzerdefinierte Kodierungskonstante verwendet, bleibt unverändert + void encodeWithCustomConstant() throws UnsupportedEncodingException { + String url = URLEncoder.encode("example", ENCODING_UTF8); + } + + // Methode, die eine Kodierungsvariable verwendet, bleibt unverändert + void encodeWithVariableEncoding() throws UnsupportedEncodingException { + String url = URLEncoder.encode("example", encodingVar); + } + + // Methode mit `try-catch`-Block für eine ungültige Kodierung + static void encodeWithTryCatch() { + try { + String url = URLEncoder.encode("example", "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (UnsupportedEncodingException e) { + System.err.println("Caught UnsupportedEncodingException for invalid encoding!"); + } + } + + // Beispiel mit StandardCharsets-Konstanten, bleibt unverändert + static void encodeWithStandardCharset() { + String url = URLEncoder.encode("example", StandardCharsets.UTF_8); + } +} +""", +""" +package test1; + +import java.net.URLEncoder; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; + +public class E1 { + private static final String ENCODING_UTF8 = "UTF-8"; // Benutzerdefinierte Kodierungskonstante + private String encodingVar = "ISO-8859-1"; // Variable für eine Kodierung + + // Methode ohne explizite Kodierung, bleibt unverändert + static void encodeDefault() { + String url = URLEncoder.encode("example", Charset.defaultCharset()); + } + + // Methode, die "UTF-8" als String-Literal verwendet und `throws UnsupportedEncodingException` hat + static void encodeWithThrows() { + String url = URLEncoder.encode("example", StandardCharsets.UTF_8); // sollte in StandardCharsets.UTF_8 geändert werden + } + + // Methode, die eine ungültige Kodierung verwendet und `UnsupportedEncodingException` wirft + static void encodeWithInvalidEncodingThrows() throws UnsupportedEncodingException { + String url = URLEncoder.encode("example", "non-existing-encoding"); + } + + // Methode, die eine benutzerdefinierte Kodierungskonstante verwendet, bleibt unverändert + void encodeWithCustomConstant() throws UnsupportedEncodingException { + String url = URLEncoder.encode("example", ENCODING_UTF8); + } + + // Methode, die eine Kodierungsvariable verwendet, bleibt unverändert + void encodeWithVariableEncoding() throws UnsupportedEncodingException { + String url = URLEncoder.encode("example", encodingVar); + } + + // Methode mit `try-catch`-Block für eine ungültige Kodierung + static void encodeWithTryCatch() { + try { + String url = URLEncoder.encode("example", "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (UnsupportedEncodingException e) { + System.err.println("Caught UnsupportedEncodingException for invalid encoding!"); + } + } + + // Beispiel mit StandardCharsets-Konstanten, bleibt unverändert + static void encodeWithStandardCharset() { + String url = URLEncoder.encode("example", StandardCharsets.UTF_8); + } +} +"""), + SCANNER( +""" +package test1; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.Scanner; + +public class E1 { + + // Methode mit File und explizitem "UTF-8" (wird durch StandardCharsets.UTF_8 ersetzt) + static void bla3(File file) throws FileNotFoundException { + // Konstruktor mit String-Encoding, sollte durch StandardCharsets.UTF_8 ersetzt werden + Scanner s = new Scanner(file, "UTF-8"); + } + + // Methode mit InputStream und explizitem "UTF-8" (wird durch StandardCharsets.UTF_8 ersetzt) + static void bla4(InputStream is) throws FileNotFoundException { + Scanner s2 = new Scanner(is, "UTF-8"); + } + + // Methode mit Scanner, aber ohne explizites Encoding, bleibt unverändert + static void bla5() { + Scanner s3 = new Scanner("asdf"); + } + + // Methode, die eine benutzerdefinierte Konstante für die Kodierung verwendet (bleibt unverändert) + private static final String ENCODING_UTF8 = "UTF-8"; + static void bla6(File file) throws FileNotFoundException { + Scanner s = new Scanner(file, ENCODING_UTF8); + } + + // Methode mit einer ungültigen Kodierung (muss UnsupportedEncodingException werfen) + static void bla7(File file) throws FileNotFoundException { + try { + Scanner s = new Scanner(file, "non-existing-encoding"); // wirft UnsupportedEncodingException + } catch (Exception e) { + e.printStackTrace(); // Catch block für UnsupportedEncodingException + } + } + + // Methode mit Scanner und ungültiger Kodierung, die `throws UnsupportedEncodingException` wirft + static void bla8(InputStream is) throws FileNotFoundException, UnsupportedEncodingException { + Scanner s = new Scanner(is, "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } + + // Methode, die eine ungültige Kodierung und ein try-catch verwendet (für FileNotFoundException) + static void bla9(File file) { + try { + Scanner s = new Scanner(file, "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (FileNotFoundException e) { + // Datei nicht gefunden, hier wird FileNotFoundException behandelt + e.printStackTrace(); + } catch (Exception e) { + // UnsupportedEncodingException wird hier abgefangen + e.printStackTrace(); + } + } + + // Beispiel mit StandardCharsets-Konstanten, die keine Änderung brauchen + static void bla10(File file) { + Scanner s = new Scanner(file, StandardCharsets.UTF_8); + } + + // Beispiel mit Scanner und InputStream, ohne explizite Kodierung (bleibt unverändert) + static void bla11(InputStream is) { + Scanner s = new Scanner(is); + } + + // Methode mit Scanner und einer benutzerdefinierten Kodierung als Variable (bleibt unverändert) + private String encodingVar = "ISO-8859-1"; + static void bla12(InputStream is) throws FileNotFoundException { + Scanner s = new Scanner(is, "ISO-8859-1"); + } +} +""", +""" +package test1; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.Scanner; + +public class E1 { + + // Methode mit File und explizitem "UTF-8" (wird durch StandardCharsets.UTF_8 ersetzt) + static void bla3(File file) throws FileNotFoundException { + // Konstruktor mit String-Encoding, sollte durch StandardCharsets.UTF_8 ersetzt werden + Scanner s = new Scanner(file, StandardCharsets.UTF_8); + } + + // Methode mit InputStream und explizitem "UTF-8" (wird durch StandardCharsets.UTF_8 ersetzt) + static void bla4(InputStream is) throws FileNotFoundException { + Scanner s2 = new Scanner(is, StandardCharsets.UTF_8); + } + + // Methode mit Scanner, aber ohne explizites Encoding, bleibt unverändert + static void bla5() { + Scanner s3 = new Scanner("asdf", Charset.defaultCharset()); + } + + // Methode, die eine benutzerdefinierte Konstante für die Kodierung verwendet (bleibt unverändert) + private static final String ENCODING_UTF8 = "UTF-8"; + static void bla6(File file) throws FileNotFoundException { + Scanner s = new Scanner(file, ENCODING_UTF8); + } + + // Methode mit einer ungültigen Kodierung (muss UnsupportedEncodingException werfen) + static void bla7(File file) throws FileNotFoundException { + try { + Scanner s = new Scanner(file, "non-existing-encoding"); // wirft UnsupportedEncodingException + } catch (Exception e) { + e.printStackTrace(); // Catch block für UnsupportedEncodingException + } + } + + // Methode mit Scanner und ungültiger Kodierung, die `throws UnsupportedEncodingException` wirft + static void bla8(InputStream is) throws FileNotFoundException, UnsupportedEncodingException { + Scanner s = new Scanner(is, "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } + + // Methode, die eine ungültige Kodierung und ein try-catch verwendet (für FileNotFoundException) + static void bla9(File file) { + try { + Scanner s = new Scanner(file, "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (FileNotFoundException e) { + // Datei nicht gefunden, hier wird FileNotFoundException behandelt + e.printStackTrace(); + } catch (Exception e) { + // UnsupportedEncodingException wird hier abgefangen + e.printStackTrace(); + } + } + + // Beispiel mit StandardCharsets-Konstanten, die keine Änderung brauchen + static void bla10(File file) { + Scanner s = new Scanner(file, StandardCharsets.UTF_8); + } + + // Beispiel mit Scanner und InputStream, ohne explizite Kodierung (bleibt unverändert) + static void bla11(InputStream is) { + Scanner s = new Scanner(is, Charset.defaultCharset()); + } + + // Methode mit Scanner und einer benutzerdefinierten Kodierung als Variable (bleibt unverändert) + private String encodingVar = "ISO-8859-1"; + static void bla12(InputStream is) throws FileNotFoundException { + Scanner s = new Scanner(is, StandardCharsets.ISO_8859_1); + } +} +"""), + FORMATTER( +""" +package test1; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; +import java.util.Formatter; + +public class E1 { + + // Methode mit explizitem UTF-8, sollte durch StandardCharsets.UTF_8 ersetzt werden + static void bla() throws FileNotFoundException, UnsupportedEncodingException { + Formatter s = new Formatter(new File("asdf"), "UTF-8"); // 'UTF-8' wird zu StandardCharsets.UTF_8 + } + + // Methode mit try-catch, die eine Kodierung verwendet und Fehler wirft + static void bli() throws FileNotFoundException { + try { + Formatter s = new Formatter(new File("asdf"), "UTF-8"); // 'UTF-8' wird zu StandardCharsets.UTF_8 + } catch (FileNotFoundException | UnsupportedEncodingException e) { + // Der Catch-Block für UnsupportedEncodingException sollte im Cleanup entfernt werden + e.printStackTrace(); + } + } + + // Methode mit benutzerdefinierter Konstante für das Encoding + private static final String ENCODING_UTF8 = "UTF-8"; + + static void blc() throws FileNotFoundException, UnsupportedEncodingException { + Formatter s = new Formatter(new File("asdf"), ENCODING_UTF8); // 'UTF-8' als Konstante + } + + // Methode mit einer ungültigen Kodierung (z.B. 'non-existing-encoding') + static void bld() throws FileNotFoundException { + try { + Formatter s = new Formatter(new File("asdf"), "non-existing-encoding"); // wirft UnsupportedEncodingException + } catch (FileNotFoundException | UnsupportedEncodingException e) { + e.printStackTrace(); // UnsupportedEncodingException wird hier erwartet + } + } + + // Methode, die eine ungültige Kodierung und ein try-catch verwendet + static void ble() throws FileNotFoundException { + try { + Formatter s = new Formatter(new File("asdf"), "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (FileNotFoundException e) { + // Datei nicht gefunden, hier wird FileNotFoundException behandelt + e.printStackTrace(); + } catch (UnsupportedEncodingException e) { + // UnsupportedEncodingException wird hier behandelt + e.printStackTrace(); + } + } + + // Methode mit StandardCharsets.UTF_8 + static void blf() throws FileNotFoundException { + Formatter s = new Formatter(new File("asdf"), StandardCharsets.UTF_8); // Verwendung von StandardCharsets.UTF_8 + } + + // Beispiel, bei dem das Encoding in einer Variablen gespeichert ist + private String encodingVar = "UTF-8"; + + static void blg() throws FileNotFoundException { + String encoding = "UTF-8"; + Formatter s = new Formatter(new File("asdf"), encoding); // encoding als Variable + } +} +""", """ +package test1; + +import java.io.File; +import java.io.FileNotFoundException; +import java.nio.charset.StandardCharsets; +import java.util.Formatter; + +public class E1 { + + // Methode mit explizitem UTF-8, sollte durch StandardCharsets.UTF_8 ersetzt werden + static void bla() throws FileNotFoundException { + Formatter s = new Formatter(new File("asdf"), StandardCharsets.UTF_8); // 'UTF-8' wird zu StandardCharsets.UTF_8 + } + + // Methode mit try-catch, die eine Kodierung verwendet und Fehler wirft + static void bli() throws FileNotFoundException { + try { + Formatter s = new Formatter(new File("asdf"), StandardCharsets.UTF_8); // 'UTF-8' wird zu StandardCharsets.UTF_8 + } catch (FileNotFoundException e) { + // Der Catch-Block für UnsupportedEncodingException sollte im Cleanup entfernt werden + e.printStackTrace(); + } + } + + // Methode mit benutzerdefinierter Konstante für das Encoding + private static final String ENCODING_UTF8 = "UTF-8"; + + static void blc() throws FileNotFoundException, UnsupportedEncodingException { + Formatter s = new Formatter(new File("asdf"), ENCODING_UTF8); // 'UTF-8' als Konstante + } + + // Methode mit einer ungültigen Kodierung (z.B. 'non-existing-encoding') + static void bld() throws FileNotFoundException { + try { + Formatter s = new Formatter(new File("asdf"), "non-existing-encoding"); // wirft UnsupportedEncodingException + } catch (FileNotFoundException | UnsupportedEncodingException e) { + e.printStackTrace(); // UnsupportedEncodingException wird hier erwartet + } + } + + // Methode, die eine ungültige Kodierung und ein try-catch verwendet + static void ble() throws FileNotFoundException { + try { + Formatter s = new Formatter(new File("asdf"), "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (FileNotFoundException e) { + // Datei nicht gefunden, hier wird FileNotFoundException behandelt + e.printStackTrace(); + } catch (UnsupportedEncodingException e) { + // UnsupportedEncodingException wird hier behandelt + e.printStackTrace(); + } + } + + // Methode mit StandardCharsets.UTF_8 + static void blf() throws FileNotFoundException { + Formatter s = new Formatter(new File("asdf"), StandardCharsets.UTF_8); // Verwendung von StandardCharsets.UTF_8 + } + + // Beispiel, bei dem das Encoding in einer Variablen gespeichert ist + private String encodingVar = "UTF-8"; + + static void blg() throws FileNotFoundException { + String encoding = "UTF-8"; + Formatter s = new Formatter(new File("asdf"), encoding); // encoding als Variable + } +} +"""), + THREE(""" + package test1; + + import java.io.ByteArrayOutputStream; + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Reader; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + String s="asdf"; //$NON-NLS-1$ + byte[] bytes= s.getBytes(); + System.out.println(bytes.length); + ByteArrayOutputStream ba=new ByteArrayOutputStream(); + String result=ba.toString(); + try { + InputStreamReader is=new InputStreamReader(new FileInputStream("")); //$NON-NLS-1$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + try { + OutputStreamWriter os=new OutputStreamWriter(new FileOutputStream("")); //$NON-NLS-1$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + try { + Reader is=new FileReader(filename); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } + } + """, + + """ + package test1; + + import java.io.ByteArrayOutputStream; + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Reader; + import java.nio.charset.Charset; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + String s="asdf"; //$NON-NLS-1$ + byte[] bytes= s.getBytes(Charset.defaultCharset()); + System.out.println(bytes.length); + ByteArrayOutputStream ba=new ByteArrayOutputStream(); + String result=ba.toString(Charset.defaultCharset()); + try { + InputStreamReader is=new InputStreamReader(new FileInputStream(""), Charset.defaultCharset()); //$NON-NLS-1$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + try { + OutputStreamWriter os=new OutputStreamWriter(new FileOutputStream(""), Charset.defaultCharset()); //$NON-NLS-1$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + try { + Reader is=new InputStreamReader(new FileInputStream(filename), Charset.defaultCharset()); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } + } + """), + ENCODINGASSTRINGPARAMETER( + """ + package test1; + + import java.io.ByteArrayOutputStream; + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Reader; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + String s="asdf"; //$NON-NLS-1$ + //byte[] bytes= s.getBytes(StandardCharsets.UTF_8); + byte[] bytes= s.getBytes("Utf-8"); + System.out.println(bytes.length); + ByteArrayOutputStream ba=new ByteArrayOutputStream(); + String result=ba.toString(); + try { + InputStreamReader is=new InputStreamReader(new FileInputStream(""), "UTF-8"); //$NON-NLS-1$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + try { + OutputStreamWriter os=new OutputStreamWriter(new FileOutputStream(""), "UTF-8"); //$NON-NLS-1$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + try { + Reader is=new FileReader(filename); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } + } + """, + + """ + package test1; + + import java.io.ByteArrayOutputStream; + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Reader; + import java.nio.charset.Charset; + import java.nio.charset.StandardCharsets; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + String s="asdf"; //$NON-NLS-1$ + //byte[] bytes= s.getBytes(StandardCharsets.UTF_8); + byte[] bytes= s.getBytes(StandardCharsets.UTF_8); + System.out.println(bytes.length); + ByteArrayOutputStream ba=new ByteArrayOutputStream(); + String result=ba.toString(Charset.defaultCharset()); + try { + InputStreamReader is=new InputStreamReader(new FileInputStream(""), StandardCharsets.UTF_8); //$NON-NLS-1$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + try { + OutputStreamWriter os=new OutputStreamWriter(new FileOutputStream(""), StandardCharsets.UTF_8); //$NON-NLS-1$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + try { + Reader is=new InputStreamReader(new FileInputStream(filename), Charset.defaultCharset()); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } + } + """); + + String given; + String expected; + + ExplicitEncodingPatternsKeepBehavior(String given, String expected) { + this.given= given; + this.expected= expected; + } + } \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/Java10/ExplicitEncodingPatternsPreferUTF8.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/Java10/ExplicitEncodingPatternsPreferUTF8.java new file mode 100644 index 00000000000..cfec11ef7f4 --- /dev/null +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/Java10/ExplicitEncodingPatternsPreferUTF8.java @@ -0,0 +1,1878 @@ +/******************************************************************************* + * Copyright (c) 2024 Carsten Hammer and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.quickfix.Java10; + +public enum ExplicitEncodingPatternsPreferUTF8 { + + CHARSET(""" + package test1; + + import java.io.ByteArrayOutputStream; + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Reader; + import java.nio.charset.Charset; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + Charset cs1= Charset.forName("UTF-8"); + Charset cs1b= Charset.forName("Utf-8"); + Charset cs2= Charset.forName("UTF-16"); + Charset cs3= Charset.forName("UTF-16BE"); + Charset cs4= Charset.forName("UTF-16LE"); + Charset cs5= Charset.forName("ISO-8859-1"); + Charset cs6= Charset.forName("US-ASCII"); + String result= cs1.toString(); + } + } + } + """, + """ + package test1; + + import java.io.ByteArrayOutputStream; + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Reader; + import java.nio.charset.Charset; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + Charset cs1= Charset.forName("UTF-8"); + Charset cs1b= Charset.forName("Utf-8"); + Charset cs2= Charset.forName("UTF-16"); + Charset cs3= Charset.forName("UTF-16BE"); + Charset cs4= Charset.forName("UTF-16LE"); + Charset cs5= Charset.forName("ISO-8859-1"); + Charset cs6= Charset.forName("US-ASCII"); + String result= cs1.toString(); + } + } + } + """), + BYTEARRAYOUTSTREAM(""" + package test1; + + import java.io.ByteArrayOutputStream; + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Reader; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + ByteArrayOutputStream ba=new ByteArrayOutputStream(); + String result=ba.toString(); + ByteArrayOutputStream ba2=new ByteArrayOutputStream(); + String result2=ba2.toString("UTF-8"); + } + } + } + """, + + """ +package test1; + +import java.io.ByteArrayOutputStream; +import java.io.InputStreamReader; +import java.io.FileInputStream; +import java.io.FileReader; +import java.io.Reader; +import java.nio.charset.StandardCharsets; +import java.io.FileNotFoundException; + +public class E1 { + void method(String filename) { + ByteArrayOutputStream ba=new ByteArrayOutputStream(); + String result=ba.toString(StandardCharsets.UTF_8); + ByteArrayOutputStream ba2=new ByteArrayOutputStream(); + String result2=ba2.toString(StandardCharsets.UTF_8); + } + } +} + """), + FILEREADER(""" + package test1; + + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Reader; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + try { + Reader is=new FileReader(filename); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } + } + """, + + """ +package test1; + +import java.io.InputStreamReader; +import java.io.FileInputStream; +import java.io.FileReader; +import java.io.Reader; +import java.nio.charset.StandardCharsets; +import java.io.FileNotFoundException; + +public class E1 { + void method(String filename) { + try { + Reader is=new InputStreamReader(new FileInputStream(filename), StandardCharsets.UTF_8); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } +} + """), + FILEWRITER(""" + package test1; + + import java.io.FileWriter; + import java.io.Writer; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + try { + Writer fw=new FileWriter(filename); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } + } + """, + + """ +package test1; + +import java.io.FileWriter; +import java.io.OutputStreamWriter; +import java.io.Writer; +import java.nio.charset.StandardCharsets; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; + +public class E1 { + void method(String filename) { + try { + Writer fw=new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.UTF_8); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } +} + """), + INPUTSTREAMREADER( +""" +package test1; + +import java.io.InputStreamReader; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.UnsupportedEncodingException; + +public class E1 { + + void method(String filename) { + try { + // Standardkonstruktor ohne Encoding + InputStreamReader is1 = new InputStreamReader(new FileInputStream("file1.txt")); //$NON-NLS-1$ + + // String Literal Encodings, die nach StandardCharsets umgeschrieben werden sollten + InputStreamReader is2 = new InputStreamReader(new FileInputStream("file2.txt"), "UTF-8"); //$NON-NLS-1$ //$NON-NLS-2$ + InputStreamReader is3 = new InputStreamReader(new FileInputStream("file3.txt"), "ISO-8859-1"); //$NON-NLS-1$ //$NON-NLS-2$ + InputStreamReader is4 = new InputStreamReader(new FileInputStream("file4.txt"), "US-ASCII"); //$NON-NLS-1$ //$NON-NLS-2$ + + // String-basiertes Encoding, das in Charset umgeschrieben werden kann, jedoch ohne vordefinierte Konstante + InputStreamReader is5 = new InputStreamReader(new FileInputStream("file5.txt"), "UTF-16"); //$NON-NLS-1$ //$NON-NLS-2$ + + // String-basierte Encodings mit Groß-/Kleinschreibungsvarianten + InputStreamReader is6 = new InputStreamReader(new FileInputStream("file6.txt"), "utf-8"); //$NON-NLS-1$ //$NON-NLS-2$ + InputStreamReader is7 = new InputStreamReader(new FileInputStream("file7.txt"), "Utf-8"); //$NON-NLS-1$ //$NON-NLS-2$ + + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); // Sollte nach Cleanup entfernt werden + } + } + + void methodWithTryCatch(String filename) { + try { + // Variante, bei der UnsupportedEncodingException behandelt wird + InputStreamReader is8 = new InputStreamReader(new FileInputStream("file8.txt"), "UTF-8"); //$NON-NLS-1$ //$NON-NLS-2$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); // Sollte nach Cleanup entfernt werden + } + } + + void methodWithoutException(String filename) throws UnsupportedEncodingException, FileNotFoundException { + // Case ohne Try-Catch-Block, sollte Charset-Konstanten direkt ersetzen + InputStreamReader is9 = new InputStreamReader(new FileInputStream("file9.txt"), "UTF-8"); //$NON-NLS-1$ //$NON-NLS-2$ + } + + void methodWithVariableEncoding(String filename) throws UnsupportedEncodingException, FileNotFoundException { + // Case, bei dem das Encoding aus einer Variablen kommt, Cleanup sollte hier keine Änderungen machen + String encoding = "UTF-8"; //$NON-NLS-1$ + InputStreamReader is10 = new InputStreamReader(new FileInputStream("file10.txt"), encoding); //$NON-NLS-1$ + } + + void methodWithNonStandardEncoding(String filename) { + try { + // Case mit nicht vordefiniertem Charset, sollte keine Umwandlung in StandardCharsets erfolgen + InputStreamReader is11 = new InputStreamReader(new FileInputStream("file11.txt"), "windows-1252"); //$NON-NLS-1$ //$NON-NLS-2$ + } catch (FileNotFoundException | UnsupportedEncodingException e) { + e.printStackTrace(); + } + } + + // Methode mit "throws UnsupportedEncodingException" zur Prüfung des Cleanups + void methodWithThrows(String filename) throws FileNotFoundException, UnsupportedEncodingException { + InputStreamReader is3 = new InputStreamReader(new FileInputStream(filename), "UTF-8"); //$NON-NLS-1$ + } +} +""", + +""" +package test1; + +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; +import java.io.FileInputStream; +import java.io.FileNotFoundException; + +public class E1 { + + void method(String filename) { + try { + // Standardkonstruktor ohne Encoding + InputStreamReader is1 = new InputStreamReader(new FileInputStream("file1.txt"), StandardCharsets.UTF_8); //$NON-NLS-1$ + + // String Literal Encodings, die nach StandardCharsets umgeschrieben werden sollten + InputStreamReader is2 = new InputStreamReader(new FileInputStream("file2.txt"), StandardCharsets.UTF_8); //$NON-NLS-1$ //$NON-NLS-2$ + InputStreamReader is3 = new InputStreamReader(new FileInputStream("file3.txt"), StandardCharsets.ISO_8859_1); //$NON-NLS-1$ //$NON-NLS-2$ + InputStreamReader is4 = new InputStreamReader(new FileInputStream("file4.txt"), StandardCharsets.US_ASCII); //$NON-NLS-1$ //$NON-NLS-2$ + + // String-basiertes Encoding, das in Charset umgeschrieben werden kann, jedoch ohne vordefinierte Konstante + InputStreamReader is5 = new InputStreamReader(new FileInputStream("file5.txt"), StandardCharsets.UTF_16); //$NON-NLS-1$ //$NON-NLS-2$ + + // String-basierte Encodings mit Groß-/Kleinschreibungsvarianten + InputStreamReader is6 = new InputStreamReader(new FileInputStream("file6.txt"), StandardCharsets.UTF_8); //$NON-NLS-1$ //$NON-NLS-2$ + InputStreamReader is7 = new InputStreamReader(new FileInputStream("file7.txt"), StandardCharsets.UTF_8); //$NON-NLS-1$ //$NON-NLS-2$ + + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + + void methodWithTryCatch(String filename) { + try { + // Variante, bei der UnsupportedEncodingException behandelt wird + InputStreamReader is8 = new InputStreamReader(new FileInputStream("file8.txt"), StandardCharsets.UTF_8); //$NON-NLS-1$ //$NON-NLS-2$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + + void methodWithoutException(String filename) throws FileNotFoundException { + // Case ohne Try-Catch-Block, sollte Charset-Konstanten direkt ersetzen + InputStreamReader is9 = new InputStreamReader(new FileInputStream("file9.txt"), StandardCharsets.UTF_8); //$NON-NLS-1$ //$NON-NLS-2$ + } + + void methodWithVariableEncoding(String filename) throws UnsupportedEncodingException, FileNotFoundException { + // Case, bei dem das Encoding aus einer Variablen kommt, Cleanup sollte hier keine Änderungen machen + String encoding = "UTF-8"; //$NON-NLS-1$ + InputStreamReader is10 = new InputStreamReader(new FileInputStream("file10.txt"), encoding); //$NON-NLS-1$ + } + + void methodWithNonStandardEncoding(String filename) { + try { + // Case mit nicht vordefiniertem Charset, sollte keine Umwandlung in StandardCharsets erfolgen + InputStreamReader is11 = new InputStreamReader(new FileInputStream("file11.txt"), "windows-1252"); //$NON-NLS-1$ //$NON-NLS-2$ + } catch (FileNotFoundException | UnsupportedEncodingException e) { + e.printStackTrace(); + } + } + + // Methode mit "throws UnsupportedEncodingException" zur Prüfung des Cleanups + void methodWithThrows(String filename) throws FileNotFoundException { + InputStreamReader is3 = new InputStreamReader(new FileInputStream(filename), StandardCharsets.UTF_8); //$NON-NLS-1$ + } +} +"""), + OUTPUTSTREAMWRITER( +""" +package test1; + +import java.io.FileOutputStream; +import java.io.OutputStreamWriter; +import java.io.FileNotFoundException; +import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; + +public class E1 { + private static final String ENCODING_UTF8 = "UTF-8"; // Konstante für Encoding + + void method(String filename) { + try { + // Standard-Konstruktor ohne Encoding + OutputStreamWriter os1 = new OutputStreamWriter(new FileOutputStream(filename)); + + // Konstruktor mit String-Encoding (UTF-8) -> muss durch StandardCharsets.UTF_8 ersetzt werden + OutputStreamWriter os2 = new OutputStreamWriter(new FileOutputStream(filename), "UTF-8"); // "UTF-8" als String-Literal + + // Konstruktor mit String-Encoding (ISO-8859-1) -> muss durch StandardCharsets.ISO_8859_1 ersetzt werden + OutputStreamWriter os3 = new OutputStreamWriter(new FileOutputStream(filename), "ISO-8859-1"); // "ISO-8859-1" als String-Literal + + // Konstruktor mit String-Encoding (US-ASCII) -> muss durch StandardCharsets.US_ASCII ersetzt werden + OutputStreamWriter os4 = new OutputStreamWriter(new FileOutputStream(filename), "US-ASCII"); // "US-ASCII" als String-Literal + + // Konstruktor mit String-Encoding (UTF-16) -> muss durch StandardCharsets.UTF_16 ersetzt werden + OutputStreamWriter os5 = new OutputStreamWriter(new FileOutputStream(filename), "UTF-16"); // "UTF-16" als String-Literal + + // Der Konstruktor mit einer benutzerdefinierten Konstante bleibt unverändert + OutputStreamWriter os6 = new OutputStreamWriter(new FileOutputStream(filename), ENCODING_UTF8); // bleibt unverändert + + // Fälle ohne Entsprechung in StandardCharsets (bleiben unverändert) + OutputStreamWriter os7 = new OutputStreamWriter(new FileOutputStream(filename), "windows-1252"); // bleibt unverändert + OutputStreamWriter os8 = new OutputStreamWriter(new FileOutputStream(filename), "Shift_JIS"); // bleibt unverändert + + // Hier wird `UnsupportedEncodingException` geworfen (vor dem Cleanup) + OutputStreamWriter os9 = new OutputStreamWriter(new FileOutputStream(filename), "non-existing-encoding"); // wirft UnsupportedEncodingException + + // Aufruf mit einer ungültigen Zeichenkodierung und catch für UnsupportedEncodingException + try { + OutputStreamWriter os10 = new OutputStreamWriter(new FileOutputStream(filename), "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (UnsupportedEncodingException e) { + // Hier wird die UnsupportedEncodingException abgefangen + e.printStackTrace(); + } + + // Beispiele mit StandardCharsets-Konstanten, die unverändert bleiben + OutputStreamWriter os11 = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.UTF_8); // bleibt unverändert + OutputStreamWriter os12 = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.ISO_8859_1); // bleibt unverändert + OutputStreamWriter os13 = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.US_ASCII); // bleibt unverändert + OutputStreamWriter os14 = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.UTF_16); // bleibt unverändert + + // Beispiel mit Charset.forName und einer Konstanten, die als Parameter übergeben wird (bleibt unverändert) + OutputStreamWriter os15 = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.UTF_16); + } catch (FileNotFoundException e) { + // Datei nicht gefunden + e.printStackTrace(); + } catch (UnsupportedEncodingException e) { + // Hier wird die UnsupportedEncodingException abgefangen + e.printStackTrace(); + } + } + + // Methodendeklaration, die `UnsupportedEncodingException` wirft (und durch den Cleanup angepasst wird) + void methodWithThrows(String filename) throws UnsupportedEncodingException { + OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(filename), "non-existing-encoding"); // wirft UnsupportedEncodingException + } + + // Neue Methode: methodWithThrowsChange() - nach dem Cleanup wird keine UnsupportedEncodingException mehr geworfen + void methodWithThrowsChange(String filename) throws FileNotFoundException { + // Nach dem Cleanup, der String "UTF-8" wird zu einer StandardCharset-Konstanten geändert + OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(filename), "UTF-8"); // wirft keine UnsupportedEncodingException mehr + } + + // Methode mit einem try-catch, um die UnsupportedEncodingException zu behandeln (und durch den Cleanup angepasst wird) + void methodWithCatch(String filename) { + try { + OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(filename), "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (UnsupportedEncodingException e) { + // Hier wird die UnsupportedEncodingException abgefangen + e.printStackTrace(); + } + } + + // Neue Methode: methodWithCatchChange() - nach dem Cleanup wird keine UnsupportedEncodingException mehr abgefangen + void methodWithCatchChange(String filename) { + try { + // Nach dem Cleanup wird "UTF-8" ersetzt + OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(filename), "UTF-8"); // keine UnsupportedEncodingException + } catch (UnsupportedEncodingException e) { + // Dieser Block wird nicht mehr erreicht, da keine UnsupportedEncodingException mehr geworfen wird + e.printStackTrace(); + } + } +} +""", + +""" +package test1; + +import java.io.FileOutputStream; +import java.io.OutputStreamWriter; +import java.io.FileNotFoundException; +import java.nio.charset.StandardCharsets; + +public class E1 { + private static final String ENCODING_UTF8 = "UTF-8"; // Konstante für Encoding + + void method(String filename) { + try { + // Standard-Konstruktor ohne Encoding + OutputStreamWriter os1 = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.UTF_8); + + // Konstruktor mit String-Encoding (UTF-8) -> muss durch StandardCharsets.UTF_8 ersetzt werden + OutputStreamWriter os2 = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.UTF_8); // "UTF-8" als String-Literal + + // Konstruktor mit String-Encoding (ISO-8859-1) -> muss durch StandardCharsets.ISO_8859_1 ersetzt werden + OutputStreamWriter os3 = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.ISO_8859_1); // "ISO-8859-1" als String-Literal + + // Konstruktor mit String-Encoding (US-ASCII) -> muss durch StandardCharsets.US_ASCII ersetzt werden + OutputStreamWriter os4 = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.US_ASCII); // "US-ASCII" als String-Literal + + // Konstruktor mit String-Encoding (UTF-16) -> muss durch StandardCharsets.UTF_16 ersetzt werden + OutputStreamWriter os5 = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.UTF_16); // "UTF-16" als String-Literal + + // Der Konstruktor mit einer benutzerdefinierten Konstante bleibt unverändert + OutputStreamWriter os6 = new OutputStreamWriter(new FileOutputStream(filename), ENCODING_UTF8); // bleibt unverändert + + // Fälle ohne Entsprechung in StandardCharsets (bleiben unverändert) + OutputStreamWriter os7 = new OutputStreamWriter(new FileOutputStream(filename), "windows-1252"); // bleibt unverändert + OutputStreamWriter os8 = new OutputStreamWriter(new FileOutputStream(filename), "Shift_JIS"); // bleibt unverändert + + // Hier wird `UnsupportedEncodingException` geworfen (vor dem Cleanup) + OutputStreamWriter os9 = new OutputStreamWriter(new FileOutputStream(filename), "non-existing-encoding"); // wirft UnsupportedEncodingException + + // Aufruf mit einer ungültigen Zeichenkodierung und catch für UnsupportedEncodingException + try { + OutputStreamWriter os10 = new OutputStreamWriter(new FileOutputStream(filename), "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (UnsupportedEncodingException e) { + // Hier wird die UnsupportedEncodingException abgefangen + e.printStackTrace(); + } + + // Beispiele mit StandardCharsets-Konstanten, die unverändert bleiben + OutputStreamWriter os11 = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.UTF_8); // bleibt unverändert + OutputStreamWriter os12 = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.ISO_8859_1); // bleibt unverändert + OutputStreamWriter os13 = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.US_ASCII); // bleibt unverändert + OutputStreamWriter os14 = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.UTF_16); // bleibt unverändert + + // Beispiel mit Charset.forName und einer Konstanten, die als Parameter übergeben wird (bleibt unverändert) + OutputStreamWriter os15 = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.UTF_16); + } catch (FileNotFoundException e) { + // Datei nicht gefunden + e.printStackTrace(); + } + } + + // Methodendeklaration, die `UnsupportedEncodingException` wirft (und durch den Cleanup angepasst wird) + void methodWithThrows(String filename) throws UnsupportedEncodingException { + OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(filename), "non-existing-encoding"); // wirft UnsupportedEncodingException + } + + // Neue Methode: methodWithThrowsChange() - nach dem Cleanup wird keine UnsupportedEncodingException mehr geworfen + void methodWithThrowsChange(String filename) throws FileNotFoundException { + // Nach dem Cleanup, der String "UTF-8" wird zu einer StandardCharset-Konstanten geändert + OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.UTF_8); // wirft keine UnsupportedEncodingException mehr + } + + // Methode mit einem try-catch, um die UnsupportedEncodingException zu behandeln (und durch den Cleanup angepasst wird) + void methodWithCatch(String filename) { + try { + OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(filename), "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (UnsupportedEncodingException e) { + // Hier wird die UnsupportedEncodingException abgefangen + e.printStackTrace(); + } + } + + // Neue Methode: methodWithCatchChange() - nach dem Cleanup wird keine UnsupportedEncodingException mehr abgefangen + void methodWithCatchChange(String filename) { + try { + // Nach dem Cleanup wird "UTF-8" ersetzt + OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.UTF_8); // keine UnsupportedEncodingException + } + } +} +"""), + CHANNELSNEWREADER( +""" +package test1; + +import java.io.Reader; +import java.nio.channels.ReadableByteChannel; +import java.nio.channels.Channels; +import java.nio.charset.StandardCharsets; +import java.nio.charset.CharsetDecoder; + +public class E1 { + private static final String ENCODING_UTF8 = "UTF-8"; // Konstante für Encoding + + void method(ReadableByteChannel ch, CharsetDecoder decoder) { + // Fälle für StandardCharsets-Konstanten + Reader r1 = Channels.newReader(ch, "UTF-8"); // soll StandardCharsets.UTF_8 werden + Reader r2 = Channels.newReader(ch, "ISO-8859-1"); // soll StandardCharsets.ISO_8859_1 werden + Reader r3 = Channels.newReader(ch, "US-ASCII"); // soll StandardCharsets.US_ASCII werden + Reader r4 = Channels.newReader(ch, "UTF-16"); // soll StandardCharsets.UTF_16 werden + + // Aufruf mit einer String-Konstanten (soll unverändert bleiben) + Reader r5 = Channels.newReader(ch, ENCODING_UTF8); // bleibt unverändert + + // Fälle ohne Entsprechung in StandardCharsets (sollen unverändert bleiben) + Reader r6 = Channels.newReader(ch, "windows-1252"); // bleibt unverändert + Reader r7 = Channels.newReader(ch, "Shift_JIS"); // bleibt unverändert + + // Aufrufe, die bereits `StandardCharsets` verwenden (bleiben unverändert) + Reader r8 = Channels.newReader(ch, StandardCharsets.UTF_8); + Reader r9 = Channels.newReader(ch, decoder, 1024); // mit CharsetDecoder und Buffergröße, bleibt unverändert + } +} +""", + +""" +package test1; + +import java.io.Reader; +import java.nio.channels.ReadableByteChannel; +import java.nio.channels.Channels; +import java.nio.charset.StandardCharsets; +import java.nio.charset.CharsetDecoder; + +public class E1 { + private static final String ENCODING_UTF8 = "UTF-8"; // Konstante für Encoding + + void method(ReadableByteChannel ch, CharsetDecoder decoder) { + // Fälle für StandardCharsets-Konstanten + Reader r1 = Channels.newReader(ch, StandardCharsets.UTF_8); // soll StandardCharsets.UTF_8 werden + Reader r2 = Channels.newReader(ch, StandardCharsets.ISO_8859_1); // soll StandardCharsets.ISO_8859_1 werden + Reader r3 = Channels.newReader(ch, StandardCharsets.US_ASCII); // soll StandardCharsets.US_ASCII werden + Reader r4 = Channels.newReader(ch, StandardCharsets.UTF_16); // soll StandardCharsets.UTF_16 werden + + // Aufruf mit einer String-Konstanten (soll unverändert bleiben) + Reader r5 = Channels.newReader(ch, ENCODING_UTF8); // bleibt unverändert + + // Fälle ohne Entsprechung in StandardCharsets (sollen unverändert bleiben) + Reader r6 = Channels.newReader(ch, "windows-1252"); // bleibt unverändert + Reader r7 = Channels.newReader(ch, "Shift_JIS"); // bleibt unverändert + + // Aufrufe, die bereits `StandardCharsets` verwenden (bleiben unverändert) + Reader r8 = Channels.newReader(ch, StandardCharsets.UTF_8); + Reader r9 = Channels.newReader(ch, decoder, 1024); // mit CharsetDecoder und Buffergröße, bleibt unverändert + } +} +"""), + CHANNELSNEWWRITER( +""" +package test1; + +import java.io.Writer; +import java.nio.channels.WritableByteChannel; +import java.nio.channels.Channels; +import java.nio.charset.StandardCharsets; +import java.nio.charset.Charset; + +public class E1 { + private static final String ENCODING_UTF8 = "UTF-8"; // Konstante für Encoding + + void method(WritableByteChannel ch, Charset charset) { + // Fälle für StandardCharsets-Konstanten + Writer w1 = Channels.newWriter(ch, "UTF-8"); // soll StandardCharsets.UTF_8 werden + Writer w2 = Channels.newWriter(ch, "ISO-8859-1"); // soll StandardCharsets.ISO_8859_1 werden + Writer w3 = Channels.newWriter(ch, "US-ASCII"); // soll StandardCharsets.US_ASCII werden + Writer w4 = Channels.newWriter(ch, "UTF-16"); // soll StandardCharsets.UTF_16 werden + + // Aufruf mit einer String-Konstanten (soll unverändert bleiben) + Writer w5 = Channels.newWriter(ch, ENCODING_UTF8); // bleibt unverändert + + // Fälle ohne Entsprechung in StandardCharsets (sollen unverändert bleiben) + Writer w6 = Channels.newWriter(ch, "windows-1252"); // bleibt unverändert + Writer w7 = Channels.newWriter(ch, "Shift_JIS"); // bleibt unverändert + + // Aufrufe, die bereits `StandardCharsets` verwenden (bleiben unverändert) + Writer w8 = Channels.newWriter(ch, StandardCharsets.UTF_8); + Writer w9 = Channels.newWriter(ch, charset); // unverändert, da `Charset` Instanz verwendet + } +} +""", + +""" +package test1; + +import java.io.Writer; +import java.nio.channels.WritableByteChannel; +import java.nio.channels.Channels; +import java.nio.charset.StandardCharsets; +import java.nio.charset.Charset; + +public class E1 { + private static final String ENCODING_UTF8 = "UTF-8"; // Konstante für Encoding + + void method(WritableByteChannel ch, Charset charset) { + // Fälle für StandardCharsets-Konstanten + Writer w1 = Channels.newWriter(ch, StandardCharsets.UTF_8); // soll StandardCharsets.UTF_8 werden + Writer w2 = Channels.newWriter(ch, StandardCharsets.ISO_8859_1); // soll StandardCharsets.ISO_8859_1 werden + Writer w3 = Channels.newWriter(ch, StandardCharsets.US_ASCII); // soll StandardCharsets.US_ASCII werden + Writer w4 = Channels.newWriter(ch, StandardCharsets.UTF_16); // soll StandardCharsets.UTF_16 werden + + // Aufruf mit einer String-Konstanten (soll unverändert bleiben) + Writer w5 = Channels.newWriter(ch, ENCODING_UTF8); // bleibt unverändert + + // Fälle ohne Entsprechung in StandardCharsets (sollen unverändert bleiben) + Writer w6 = Channels.newWriter(ch, "windows-1252"); // bleibt unverändert + Writer w7 = Channels.newWriter(ch, "Shift_JIS"); // bleibt unverändert + + // Aufrufe, die bereits `StandardCharsets` verwenden (bleiben unverändert) + Writer w8 = Channels.newWriter(ch, StandardCharsets.UTF_8); + Writer w9 = Channels.newWriter(ch, charset); // unverändert, da `Charset` Instanz verwendet + } +} +"""), + PRINTWRITER(""" + package test1; + + import java.io.PrintWriter; + import java.io.Writer; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + try { + Writer w=new PrintWriter(filename); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } + } + """, + + """ +package test1; + +import java.io.PrintWriter; +import java.io.Writer; +import java.nio.charset.StandardCharsets; +import java.io.BufferedWriter; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.OutputStreamWriter; + +public class E1 { + void method(String filename) { + try { + Writer w=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.UTF_8)); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } +} + """), + STRINGGETBYTES( +""" +package test1; + +import java.nio.charset.StandardCharsets; + +public class E1 { + + // Methode 1: Verwendung von StandardCharsets.UTF_8 statt "UTF-8" als String-Literal + void method(String filename) { + String s = "asdf"; //$NON-NLS-1$ + + // Vorher: getBytes ohne Angabe der Kodierung (verwendet die Plattform-spezifische Standard-Kodierung) + byte[] bytes = s.getBytes(); + + // Nachher: Umstellung auf StandardCharsets.UTF_8 + byte[] bytes2 = s.getBytes(StandardCharsets.UTF_8); + + System.out.println(bytes.length); + System.out.println(bytes2.length); + } + + // Methode 2: Behandlung von getBytes mit einer expliziten Kodierung + void method2(String filename) { + String s = "asdf"; //$NON-NLS-1$ + + // Vorher: getBytes mit expliziter Kodierung (UTF-8 als String-Literal) + byte[] bytes = s.getBytes("UTF-8"); + + // Nachher: Umstellung auf StandardCharsets.UTF_8 + byte[] bytes2 = s.getBytes(StandardCharsets.UTF_8); + + System.out.println(bytes.length); + System.out.println(bytes2.length); + } + + // Erweiterter Testfall: Verwendung von verschiedenen Kodierungen + void methodWithDifferentEncodings(String filename) { + String s = "asdf"; + + // Testen von gängigen Kodierungen + byte[] bytes1 = s.getBytes("ISO-8859-1"); // ISO-8859-1 + byte[] bytes2 = s.getBytes("US-ASCII"); // US-ASCII + byte[] bytes3 = s.getBytes(StandardCharsets.UTF_8); // UTF-8 mit StandardCharsets + byte[] bytes4 = s.getBytes("UTF-16"); // UTF-16 + + System.out.println(bytes1.length); // Ausgabe der Längen + System.out.println(bytes2.length); + System.out.println(bytes3.length); + System.out.println(bytes4.length); + } + + // Testfall: Verwendung von getBytes mit einer ungültigen Kodierung (sollte im Cleanup behandelt werden) + void methodWithInvalidEncoding(String filename) { + String s = "asdf"; + try { + // Ungültige Kodierung, die zu UnsupportedEncodingException führt + byte[] bytes = s.getBytes("non-existing-encoding"); + } catch (UnsupportedEncodingException e) { + // Diese Ausnahme sollte im Cleanup berücksichtigt werden + e.printStackTrace(); + } + } + + // Testfall: Verwendung von getBytes mit einer durch Variable angegebenen Kodierung + void methodWithVariableEncoding(String filename) { + String s = "asdf"; + String encoding = "UTF-8"; // Kodierung als Variable + try { + byte[] bytes = s.getBytes(encoding); // Kodierung aus der Variablen + System.out.println(bytes.length); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + } +} +""", + +""" +package test1; + +import java.nio.charset.StandardCharsets; + +public class E1 { + + // Methode 1: Verwendung von StandardCharsets.UTF_8 statt "UTF-8" als String-Literal + void method(String filename) { + String s = "asdf"; //$NON-NLS-1$ + + // Vorher: getBytes ohne Angabe der Kodierung (verwendet die Plattform-spezifische Standard-Kodierung) + byte[] bytes = s.getBytes(StandardCharsets.UTF_8); + + // Nachher: Umstellung auf StandardCharsets.UTF_8 + byte[] bytes2 = s.getBytes(StandardCharsets.UTF_8); + + System.out.println(bytes.length); + System.out.println(bytes2.length); + } + + // Methode 2: Behandlung von getBytes mit einer expliziten Kodierung + void method2(String filename) { + String s = "asdf"; //$NON-NLS-1$ + + // Vorher: getBytes mit expliziter Kodierung (UTF-8 als String-Literal) + byte[] bytes = s.getBytes(StandardCharsets.UTF_8); + + // Nachher: Umstellung auf StandardCharsets.UTF_8 + byte[] bytes2 = s.getBytes(StandardCharsets.UTF_8); + + System.out.println(bytes.length); + System.out.println(bytes2.length); + } + + // Erweiterter Testfall: Verwendung von verschiedenen Kodierungen + void methodWithDifferentEncodings(String filename) { + String s = "asdf"; + + // Testen von gängigen Kodierungen + byte[] bytes1 = s.getBytes(StandardCharsets.ISO_8859_1); // ISO-8859-1 + byte[] bytes2 = s.getBytes(StandardCharsets.US_ASCII); // US-ASCII + byte[] bytes3 = s.getBytes(StandardCharsets.UTF_8); // UTF-8 mit StandardCharsets + byte[] bytes4 = s.getBytes(StandardCharsets.UTF_16); // UTF-16 + + System.out.println(bytes1.length); // Ausgabe der Längen + System.out.println(bytes2.length); + System.out.println(bytes3.length); + System.out.println(bytes4.length); + } + + // Testfall: Verwendung von getBytes mit einer ungültigen Kodierung (sollte im Cleanup behandelt werden) + void methodWithInvalidEncoding(String filename) { + String s = "asdf"; + try { + // Ungültige Kodierung, die zu UnsupportedEncodingException führt + byte[] bytes = s.getBytes("non-existing-encoding"); + } catch (UnsupportedEncodingException e) { + // Diese Ausnahme sollte im Cleanup berücksichtigt werden + e.printStackTrace(); + } + } + + // Testfall: Verwendung von getBytes mit einer durch Variable angegebenen Kodierung + void methodWithVariableEncoding(String filename) { + String s = "asdf"; + String encoding = "UTF-8"; // Kodierung als Variable + try { + byte[] bytes = s.getBytes(encoding); // Kodierung aus der Variablen + System.out.println(bytes.length); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + } +} +"""), + STRING( +""" +package test1; + +import java.io.FileNotFoundException; +import java.io.UnsupportedEncodingException; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; + +public class E1 { + + static void bla(String filename) throws FileNotFoundException, UnsupportedEncodingException { + byte[] b = {(byte) 59}; + + // Fälle mit String Encoding als "UTF-8" (soll durch StandardCharsets.UTF_8 ersetzt werden) + String s1 = new String(b, "UTF-8"); // "UTF-8" als String-Literal + String s2 = new String(b, 0, 1, "UTF-8"); // "UTF-8" als String-Literal + + // Fall mit ISO-8859-1 Encoding (soll durch StandardCharsets.ISO_8859_1 ersetzt werden) + String s3 = new String(b, "ISO-8859-1"); // "ISO-8859-1" als String-Literal + String s4 = new String(b, 0, 1, "ISO-8859-1"); // "ISO-8859-1" als String-Literal + + // Fall mit US-ASCII Encoding (soll durch StandardCharsets.US_ASCII ersetzt werden) + String s5 = new String(b, "US-ASCII"); // "US-ASCII" als String-Literal + String s6 = new String(b, 0, 1, "US-ASCII"); // "US-ASCII" als String-Literal + + // Fall mit UTF-16 Encoding (soll durch StandardCharsets.UTF_16 ersetzt werden) + String s7 = new String(b, "UTF-16"); // "UTF-16" als String-Literal + String s8 = new String(b, 0, 1, "UTF-16"); // "UTF-16" als String-Literal + + // Fall mit einer benutzerdefinierten Konstante für Encoding, bleibt unverändert + String s9 = new String(b, "UTF-8"); // bleibt unverändert + String s10 = new String(b, 0, 1, "UTF-8"); // bleibt unverändert + + // Fälle ohne Entsprechung in StandardCharsets, bleiben unverändert + String s11 = new String(b, "windows-1252"); // bleibt unverändert + String s12 = new String(b, 0, 1, "windows-1252"); // bleibt unverändert + String s13 = new String(b, "Shift_JIS"); // bleibt unverändert + String s14 = new String(b, 0, 1, "Shift_JIS"); // bleibt unverändert + + // Fall mit Charset.forName() (wird unverändert bleiben, keine Ersetzung möglich) + Charset charset = Charset.forName("UTF-16"); + String s15 = new String(b, charset); // bleibt unverändert + String s16 = new String(b, 0, 1, charset); // bleibt unverändert + + // Fälle, die eine UnsupportedEncodingException werfen (werden im Cleanup angepasst) + try { + String s17 = new String(b, "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (UnsupportedEncodingException e) { + // UnsupportedEncodingException wird geworfen und abgefangen + e.printStackTrace(); + } + + try { + String s18 = new String(b, 0, 1, "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (UnsupportedEncodingException e) { + // UnsupportedEncodingException wird geworfen und abgefangen + e.printStackTrace(); + } + } + + // Methodendeklaration mit throws für UnsupportedEncodingException (wird im Cleanup angepasst) + static void methodWithThrows(String filename) throws UnsupportedEncodingException { + byte[] b = {(byte) 59}; + String s1 = new String(b, "non-existing-encoding"); // wirft UnsupportedEncodingException + } + + // Nach dem Cleanup sollte dies keine UnsupportedEncodingException mehr werfen + static void methodWithThrowsChange(String filename) throws FileNotFoundException { + byte[] b = {(byte) 59}; + String s1 = new String(b, "UTF-8"); // wirft keine UnsupportedEncodingException mehr + } + + // Methodendeklaration mit try-catch für UnsupportedEncodingException (wird im Cleanup angepasst) + static void methodWithCatch(String filename) { + byte[] b = {(byte) 59}; + try { + String s1 = new String(b, "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (UnsupportedEncodingException e) { + // UnsupportedEncodingException wird geworfen und abgefangen + e.printStackTrace(); + } + } + + // Nach dem Cleanup wird keine UnsupportedEncodingException mehr abgefangen + static void methodWithCatchChange(String filename) { + byte[] b = {(byte) 59}; + try { + String s1 = new String(b, "UTF-8"); // keine UnsupportedEncodingException + } catch (UnsupportedEncodingException e) { + // Dieser Block wird nicht mehr erreicht, da keine UnsupportedEncodingException mehr geworfen wird + e.printStackTrace(); + } + } +} +""", + +""" +package test1; + +import java.io.FileNotFoundException; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; + +public class E1 { + + static void bla(String filename) throws FileNotFoundException { + byte[] b = {(byte) 59}; + + // Fälle mit String Encoding als "UTF-8" (soll durch StandardCharsets.UTF_8 ersetzt werden) + String s1 = new String(b, StandardCharsets.UTF_8); // "UTF-8" als String-Literal + String s2 = new String(b, 0, 1, StandardCharsets.UTF_8); // "UTF-8" als String-Literal + + // Fall mit ISO-8859-1 Encoding (soll durch StandardCharsets.ISO_8859_1 ersetzt werden) + String s3 = new String(b, StandardCharsets.ISO_8859_1); // "ISO-8859-1" als String-Literal + String s4 = new String(b, 0, 1, StandardCharsets.ISO_8859_1); // "ISO-8859-1" als String-Literal + + // Fall mit US-ASCII Encoding (soll durch StandardCharsets.US_ASCII ersetzt werden) + String s5 = new String(b, StandardCharsets.US_ASCII); // "US-ASCII" als String-Literal + String s6 = new String(b, 0, 1, StandardCharsets.US_ASCII); // "US-ASCII" als String-Literal + + // Fall mit UTF-16 Encoding (soll durch StandardCharsets.UTF_16 ersetzt werden) + String s7 = new String(b, StandardCharsets.UTF_16); // "UTF-16" als String-Literal + String s8 = new String(b, 0, 1, StandardCharsets.UTF_16); // "UTF-16" als String-Literal + + // Fall mit einer benutzerdefinierten Konstante für Encoding, bleibt unverändert + String s9 = new String(b, StandardCharsets.UTF_8); // bleibt unverändert + String s10 = new String(b, 0, 1, StandardCharsets.UTF_8); // bleibt unverändert + + // Fälle ohne Entsprechung in StandardCharsets, bleiben unverändert + String s11 = new String(b, "windows-1252"); // bleibt unverändert + String s12 = new String(b, 0, 1, "windows-1252"); // bleibt unverändert + String s13 = new String(b, "Shift_JIS"); // bleibt unverändert + String s14 = new String(b, 0, 1, "Shift_JIS"); // bleibt unverändert + + // Fall mit Charset.forName() (wird unverändert bleiben, keine Ersetzung möglich) + Charset charset = Charset.forName("UTF-16"); + String s15 = new String(b, charset); // bleibt unverändert + String s16 = new String(b, 0, 1, charset); // bleibt unverändert + + // Fälle, die eine UnsupportedEncodingException werfen (werden im Cleanup angepasst) + try { + String s17 = new String(b, "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (UnsupportedEncodingException e) { + // UnsupportedEncodingException wird geworfen und abgefangen + e.printStackTrace(); + } + + try { + String s18 = new String(b, 0, 1, "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (UnsupportedEncodingException e) { + // UnsupportedEncodingException wird geworfen und abgefangen + e.printStackTrace(); + } + } + + // Methodendeklaration mit throws für UnsupportedEncodingException (wird im Cleanup angepasst) + static void methodWithThrows(String filename) throws UnsupportedEncodingException { + byte[] b = {(byte) 59}; + String s1 = new String(b, "non-existing-encoding"); // wirft UnsupportedEncodingException + } + + // Nach dem Cleanup sollte dies keine UnsupportedEncodingException mehr werfen + static void methodWithThrowsChange(String filename) throws FileNotFoundException { + byte[] b = {(byte) 59}; + String s1 = new String(b, StandardCharsets.UTF_8); // wirft keine UnsupportedEncodingException mehr + } + + // Methodendeklaration mit try-catch für UnsupportedEncodingException (wird im Cleanup angepasst) + static void methodWithCatch(String filename) { + byte[] b = {(byte) 59}; + try { + String s1 = new String(b, "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (UnsupportedEncodingException e) { + // UnsupportedEncodingException wird geworfen und abgefangen + e.printStackTrace(); + } + } + + // Nach dem Cleanup wird keine UnsupportedEncodingException mehr abgefangen + static void methodWithCatchChange(String filename) { + byte[] b = {(byte) 59}; + try { + String s1 = new String(b, StandardCharsets.UTF_8); // keine UnsupportedEncodingException + } + } +} +"""), + PROPERTIESSTORETOXML( +""" +package test1; + +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; +import java.util.Properties; + +public class E1 { + private static final String ENCODING_UTF8 = "UTF-8"; // Benutzerdefinierte Konstante für Encoding + private String encodingVar = "ISO-8859-1"; // Encoding-Variable + + // Fall 1: UTF-8 als String; Cleanup soll zu StandardCharsets.UTF_8 ändern + void storeWithTryWithResources() throws IOException { + Properties p = new Properties(); + try (FileOutputStream os = new FileOutputStream("out.xml")) { + p.storeToXML(os, "Kommentar", "UTF-8"); + } + } + + // Fall 2: Benutzerdefiniertes Encoding als Variable; Cleanup soll diesen Fall unverändert lassen + void storeWithTryWithResourcesAndCustomEncoding() throws IOException { + Properties p = new Properties(); + try (FileOutputStream os = new FileOutputStream("out.xml")) { + p.storeToXML(os, "Kommentar", encodingVar); + } + } + + // Fall 3: Ungültiges Encoding als String; Cleanup soll auf StandardCharsets.UTF_8 ändern und den catch-Block entfernen + void storeWithTryWithResourcesAndInvalidEncoding() { + Properties p = new Properties(); + try (FileOutputStream os = new FileOutputStream("out.xml")) { + p.storeToXML(os, "Kommentar", "non-existing-encoding"); + } catch (UnsupportedEncodingException e) { + System.err.println("Unsupported encoding caught!"); + } + } + + // Fall 4: FileOutputStream außerhalb des try-Blocks und UTF-8 als String; Cleanup soll auf StandardCharsets.UTF_8 ändern und den catch-Block entfernen + void storeWithoutTryWithResources(String filename) throws IOException { + Properties p = new Properties(); + FileOutputStream os = new FileOutputStream(filename); + try { + p.storeToXML(os, "Kommentar", "UTF-8"); + } catch (UnsupportedEncodingException e) { + System.err.println("Unexpected UnsupportedEncodingException"); + } finally { + os.close(); // Bleibt erhalten, um die Ressource korrekt zu schließen + } + } + + // Fall 5: Gültiges Encoding ohne Konstante in StandardCharsets (windows-1252); Cleanup soll diesen Fall unverändert lassen + void storeWithWindows1252Encoding() throws IOException { + Properties p = new Properties(); + try (FileOutputStream os = new FileOutputStream("out.xml")) { + p.storeToXML(os, "Kommentar", "windows-1252"); + } + } + + // Fall 6: Gültiges Encoding ohne Konstante in StandardCharsets (Shift_JIS); Cleanup soll diesen Fall unverändert lassen + void storeWithShiftJISEncoding() throws IOException { + Properties p = new Properties(); + try (FileOutputStream os = new FileOutputStream("out.xml")) { + p.storeToXML(os, "Kommentar", "Shift_JIS"); + } + } + + // Fall 7: Ungültiges Encoding außerhalb von try-with-resources; Cleanup soll auf StandardCharsets.UTF_8 ändern und den catch-Block entfernen + void storeWithInvalidEncodingOutsideTry(String filename) throws IOException { + Properties p = new Properties(); + FileOutputStream os = new FileOutputStream(filename); + try { + p.storeToXML(os, "Kommentar", "non-existing-encoding"); + } catch (UnsupportedEncodingException e) { + System.err.println("Unsupported encoding caught!"); + } finally { + os.close(); // Bleibt erhalten, um die Ressource korrekt zu schließen + } + } + + // Fall 8: StandardCharsets.UTF_8 ohne try-with-resources; Cleanup soll diesen Fall unverändert lassen + void storeWithoutTryWithResourcesStandardCharsets(String filename) throws IOException { + Properties p = new Properties(); + FileOutputStream os = new FileOutputStream(filename); + try { + p.storeToXML(os, "Kommentar", StandardCharsets.UTF_8); + } finally { + os.close(); // Bleibt erhalten, um die Ressource korrekt zu schließen + } + } +} +""", + +""" +package test1; + +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.nio.charset.StandardCharsets; +import java.util.Properties; + +public class E1 { + private static final String ENCODING_UTF8 = "UTF-8"; // Benutzerdefinierte Konstante für Encoding + private String encodingVar = "ISO-8859-1"; // Encoding-Variable + + // Fall 1: UTF-8 als String; Cleanup soll zu StandardCharsets.UTF_8 ändern + void storeWithTryWithResources() throws IOException { + Properties p = new Properties(); + try (FileOutputStream os = new FileOutputStream("out.xml")) { + p.storeToXML(os, "Kommentar", StandardCharsets.UTF_8); + } + } + + // Fall 2: Benutzerdefiniertes Encoding als Variable; Cleanup soll diesen Fall unverändert lassen + void storeWithTryWithResourcesAndCustomEncoding() throws IOException { + Properties p = new Properties(); + try (FileOutputStream os = new FileOutputStream("out.xml")) { + p.storeToXML(os, "Kommentar", encodingVar); + } + } + + // Fall 3: Ungültiges Encoding als String; Cleanup soll auf StandardCharsets.UTF_8 ändern und den catch-Block entfernen + void storeWithTryWithResourcesAndInvalidEncoding() { + Properties p = new Properties(); + try (FileOutputStream os = new FileOutputStream("out.xml")) { + p.storeToXML(os, "Kommentar", "non-existing-encoding"); + } catch (UnsupportedEncodingException e) { + System.err.println("Unsupported encoding caught!"); + } + } + + // Fall 4: FileOutputStream außerhalb des try-Blocks und UTF-8 als String; Cleanup soll auf StandardCharsets.UTF_8 ändern und den catch-Block entfernen + void storeWithoutTryWithResources(String filename) throws IOException { + Properties p = new Properties(); + FileOutputStream os = new FileOutputStream(filename); + try { + p.storeToXML(os, "Kommentar", StandardCharsets.UTF_8); + } finally { + os.close(); // Bleibt erhalten, um die Ressource korrekt zu schließen + } + } + + // Fall 5: Gültiges Encoding ohne Konstante in StandardCharsets (windows-1252); Cleanup soll diesen Fall unverändert lassen + void storeWithWindows1252Encoding() throws IOException { + Properties p = new Properties(); + try (FileOutputStream os = new FileOutputStream("out.xml")) { + p.storeToXML(os, "Kommentar", "windows-1252"); + } + } + + // Fall 6: Gültiges Encoding ohne Konstante in StandardCharsets (Shift_JIS); Cleanup soll diesen Fall unverändert lassen + void storeWithShiftJISEncoding() throws IOException { + Properties p = new Properties(); + try (FileOutputStream os = new FileOutputStream("out.xml")) { + p.storeToXML(os, "Kommentar", "Shift_JIS"); + } + } + + // Fall 7: Ungültiges Encoding außerhalb von try-with-resources; Cleanup soll auf StandardCharsets.UTF_8 ändern und den catch-Block entfernen + void storeWithInvalidEncodingOutsideTry(String filename) throws IOException { + Properties p = new Properties(); + FileOutputStream os = new FileOutputStream(filename); + try { + p.storeToXML(os, "Kommentar", "non-existing-encoding"); + } catch (UnsupportedEncodingException e) { + System.err.println("Unsupported encoding caught!"); + } finally { + os.close(); // Bleibt erhalten, um die Ressource korrekt zu schließen + } + } + + // Fall 8: StandardCharsets.UTF_8 ohne try-with-resources; Cleanup soll diesen Fall unverändert lassen + void storeWithoutTryWithResourcesStandardCharsets(String filename) throws IOException { + Properties p = new Properties(); + FileOutputStream os = new FileOutputStream(filename); + try { + p.storeToXML(os, "Kommentar", StandardCharsets.UTF_8); + } finally { + os.close(); // Bleibt erhalten, um die Ressource korrekt zu schließen + } + } +} +"""), + URLDECODER( +""" +package test1; + +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; + +public class E2 { + private static final String ENCODING_UTF8 = "UTF-8"; // Konstante für Encoding + private String encodingVar = "ISO-8859-1"; // Variable für Encoding + + // Methode ohne Encoding-Angabe, bleibt unverändert + static void decodeDefault() { + String url = URLDecoder.decode("example"); + } + + // Methode, die "UTF-8" als String verwendet und UnsupportedEncodingException wirft + static void decodeWithThrows() throws UnsupportedEncodingException { + String url = URLDecoder.decode("example", "UTF-8"); // sollte in StandardCharsets.UTF_8 geändert werden + } + + // Methode, die eine ungültige Kodierung verwendet und `UnsupportedEncodingException` wirft + static void decodeWithInvalidEncodingThrows() throws UnsupportedEncodingException { + String url = URLDecoder.decode("example", "non-existing-encoding"); + } + + // Methode, die eine benutzerdefinierte Konstante für Encoding verwendet, bleibt unverändert + void decodeWithCustomConstant() throws UnsupportedEncodingException { + String url = URLDecoder.decode("example", ENCODING_UTF8); + } + + // Methode, die Encoding als Variable übergibt, bleibt unverändert + void decodeWithVariableEncoding() throws UnsupportedEncodingException { + String url = URLDecoder.decode("example", encodingVar); + } + + // Methode mit `try-catch`-Block für ungültiges Encoding + static void decodeWithTryCatch() { + try { + String url = URLDecoder.decode("example", "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (UnsupportedEncodingException e) { + System.err.println("Caught UnsupportedEncodingException for invalid encoding!"); + } + } + + // Beispiel mit StandardCharsets-Konstanten, bleibt unverändert + static void decodeWithStandardCharset() { + String url = URLDecoder.decode("example", StandardCharsets.UTF_8); + } +} +""", +""" +package test1; + +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; + +public class E2 { + private static final String ENCODING_UTF8 = "UTF-8"; // Konstante für Encoding + private String encodingVar = "ISO-8859-1"; // Variable für Encoding + + // Methode ohne Encoding-Angabe, bleibt unverändert + static void decodeDefault() { + String url = URLDecoder.decode("example", StandardCharsets.UTF_8); + } + + // Methode, die "UTF-8" als String verwendet und UnsupportedEncodingException wirft + static void decodeWithThrows() { + String url = URLDecoder.decode("example", StandardCharsets.UTF_8); // sollte in StandardCharsets.UTF_8 geändert werden + } + + // Methode, die eine ungültige Kodierung verwendet und `UnsupportedEncodingException` wirft + static void decodeWithInvalidEncodingThrows() throws UnsupportedEncodingException { + String url = URLDecoder.decode("example", "non-existing-encoding"); + } + + // Methode, die eine benutzerdefinierte Konstante für Encoding verwendet, bleibt unverändert + void decodeWithCustomConstant() throws UnsupportedEncodingException { + String url = URLDecoder.decode("example", ENCODING_UTF8); + } + + // Methode, die Encoding als Variable übergibt, bleibt unverändert + void decodeWithVariableEncoding() throws UnsupportedEncodingException { + String url = URLDecoder.decode("example", encodingVar); + } + + // Methode mit `try-catch`-Block für ungültiges Encoding + static void decodeWithTryCatch() { + try { + String url = URLDecoder.decode("example", "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (UnsupportedEncodingException e) { + System.err.println("Caught UnsupportedEncodingException for invalid encoding!"); + } + } + + // Beispiel mit StandardCharsets-Konstanten, bleibt unverändert + static void decodeWithStandardCharset() { + String url = URLDecoder.decode("example", StandardCharsets.UTF_8); + } +} +"""), + URLENCODER( +""" +package test1; + +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; + +public class E1 { + private static final String ENCODING_UTF8 = "UTF-8"; // Benutzerdefinierte Kodierungskonstante + private String encodingVar = "ISO-8859-1"; // Variable für eine Kodierung + + // Methode ohne explizite Kodierung, bleibt unverändert + static void encodeDefault() { + String url = URLEncoder.encode("example"); + } + + // Methode, die "UTF-8" als String-Literal verwendet und `throws UnsupportedEncodingException` hat + static void encodeWithThrows() throws UnsupportedEncodingException { + String url = URLEncoder.encode("example", "UTF-8"); // sollte in StandardCharsets.UTF_8 geändert werden + } + + // Methode, die eine ungültige Kodierung verwendet und `UnsupportedEncodingException` wirft + static void encodeWithInvalidEncodingThrows() throws UnsupportedEncodingException { + String url = URLEncoder.encode("example", "non-existing-encoding"); + } + + // Methode, die eine benutzerdefinierte Kodierungskonstante verwendet, bleibt unverändert + void encodeWithCustomConstant() throws UnsupportedEncodingException { + String url = URLEncoder.encode("example", ENCODING_UTF8); + } + + // Methode, die eine Kodierungsvariable verwendet, bleibt unverändert + void encodeWithVariableEncoding() throws UnsupportedEncodingException { + String url = URLEncoder.encode("example", encodingVar); + } + + // Methode mit `try-catch`-Block für eine ungültige Kodierung + static void encodeWithTryCatch() { + try { + String url = URLEncoder.encode("example", "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (UnsupportedEncodingException e) { + System.err.println("Caught UnsupportedEncodingException for invalid encoding!"); + } + } + + // Beispiel mit StandardCharsets-Konstanten, bleibt unverändert + static void encodeWithStandardCharset() { + String url = URLEncoder.encode("example", StandardCharsets.UTF_8); + } +} +""", +""" +package test1; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; + +public class E1 { + private static final String ENCODING_UTF8 = "UTF-8"; // Benutzerdefinierte Kodierungskonstante + private String encodingVar = "ISO-8859-1"; // Variable für eine Kodierung + + // Methode ohne explizite Kodierung, bleibt unverändert + static void encodeDefault() { + String url = URLEncoder.encode("example", StandardCharsets.UTF_8); + } + + // Methode, die "UTF-8" als String-Literal verwendet und `throws UnsupportedEncodingException` hat + static void encodeWithThrows() { + String url = URLEncoder.encode("example", StandardCharsets.UTF_8); // sollte in StandardCharsets.UTF_8 geändert werden + } + + // Methode, die eine ungültige Kodierung verwendet und `UnsupportedEncodingException` wirft + static void encodeWithInvalidEncodingThrows() throws UnsupportedEncodingException { + String url = URLEncoder.encode("example", "non-existing-encoding"); + } + + // Methode, die eine benutzerdefinierte Kodierungskonstante verwendet, bleibt unverändert + void encodeWithCustomConstant() throws UnsupportedEncodingException { + String url = URLEncoder.encode("example", ENCODING_UTF8); + } + + // Methode, die eine Kodierungsvariable verwendet, bleibt unverändert + void encodeWithVariableEncoding() throws UnsupportedEncodingException { + String url = URLEncoder.encode("example", encodingVar); + } + + // Methode mit `try-catch`-Block für eine ungültige Kodierung + static void encodeWithTryCatch() { + try { + String url = URLEncoder.encode("example", "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (UnsupportedEncodingException e) { + System.err.println("Caught UnsupportedEncodingException for invalid encoding!"); + } + } + + // Beispiel mit StandardCharsets-Konstanten, bleibt unverändert + static void encodeWithStandardCharset() { + String url = URLEncoder.encode("example", StandardCharsets.UTF_8); + } +} +"""), + SCANNER( +""" +package test1; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.Scanner; + +public class E1 { + + // Methode mit File und explizitem "UTF-8" (wird durch StandardCharsets.UTF_8 ersetzt) + static void bla3(File file) throws FileNotFoundException { + // Konstruktor mit String-Encoding, sollte durch StandardCharsets.UTF_8 ersetzt werden + Scanner s = new Scanner(file, "UTF-8"); + } + + // Methode mit InputStream und explizitem "UTF-8" (wird durch StandardCharsets.UTF_8 ersetzt) + static void bla4(InputStream is) throws FileNotFoundException { + Scanner s2 = new Scanner(is, "UTF-8"); + } + + // Methode mit Scanner, aber ohne explizites Encoding, bleibt unverändert + static void bla5() { + Scanner s3 = new Scanner("asdf"); + } + + // Methode, die eine benutzerdefinierte Konstante für die Kodierung verwendet (bleibt unverändert) + private static final String ENCODING_UTF8 = "UTF-8"; + static void bla6(File file) throws FileNotFoundException { + Scanner s = new Scanner(file, ENCODING_UTF8); + } + + // Methode mit einer ungültigen Kodierung (muss UnsupportedEncodingException werfen) + static void bla7(File file) throws FileNotFoundException { + try { + Scanner s = new Scanner(file, "non-existing-encoding"); // wirft UnsupportedEncodingException + } catch (Exception e) { + e.printStackTrace(); // Catch block für UnsupportedEncodingException + } + } + + // Methode mit Scanner und ungültiger Kodierung, die `throws UnsupportedEncodingException` wirft + static void bla8(InputStream is) throws FileNotFoundException, UnsupportedEncodingException { + Scanner s = new Scanner(is, "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } + + // Methode, die eine ungültige Kodierung und ein try-catch verwendet (für FileNotFoundException) + static void bla9(File file) { + try { + Scanner s = new Scanner(file, "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (FileNotFoundException e) { + // Datei nicht gefunden, hier wird FileNotFoundException behandelt + e.printStackTrace(); + } catch (Exception e) { + // UnsupportedEncodingException wird hier abgefangen + e.printStackTrace(); + } + } + + // Beispiel mit StandardCharsets-Konstanten, die keine Änderung brauchen + static void bla10(File file) { + Scanner s = new Scanner(file, StandardCharsets.UTF_8); + } + + // Beispiel mit Scanner und InputStream, ohne explizite Kodierung (bleibt unverändert) + static void bla11(InputStream is) { + Scanner s = new Scanner(is); + } + + // Methode mit Scanner und einer benutzerdefinierten Kodierung als Variable (bleibt unverändert) + private String encodingVar = "ISO-8859-1"; + static void bla12(InputStream is) throws FileNotFoundException { + Scanner s = new Scanner(is, "ISO-8859-1"); + } +} +""", +""" +package test1; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.Scanner; + +public class E1 { + + // Methode mit File und explizitem "UTF-8" (wird durch StandardCharsets.UTF_8 ersetzt) + static void bla3(File file) throws FileNotFoundException { + // Konstruktor mit String-Encoding, sollte durch StandardCharsets.UTF_8 ersetzt werden + Scanner s = new Scanner(file, StandardCharsets.UTF_8); + } + + // Methode mit InputStream und explizitem "UTF-8" (wird durch StandardCharsets.UTF_8 ersetzt) + static void bla4(InputStream is) throws FileNotFoundException { + Scanner s2 = new Scanner(is, StandardCharsets.UTF_8); + } + + // Methode mit Scanner, aber ohne explizites Encoding, bleibt unverändert + static void bla5() { + Scanner s3 = new Scanner("asdf", StandardCharsets.UTF_8); + } + + // Methode, die eine benutzerdefinierte Konstante für die Kodierung verwendet (bleibt unverändert) + private static final String ENCODING_UTF8 = "UTF-8"; + static void bla6(File file) throws FileNotFoundException { + Scanner s = new Scanner(file, ENCODING_UTF8); + } + + // Methode mit einer ungültigen Kodierung (muss UnsupportedEncodingException werfen) + static void bla7(File file) throws FileNotFoundException { + try { + Scanner s = new Scanner(file, "non-existing-encoding"); // wirft UnsupportedEncodingException + } catch (Exception e) { + e.printStackTrace(); // Catch block für UnsupportedEncodingException + } + } + + // Methode mit Scanner und ungültiger Kodierung, die `throws UnsupportedEncodingException` wirft + static void bla8(InputStream is) throws FileNotFoundException, UnsupportedEncodingException { + Scanner s = new Scanner(is, "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } + + // Methode, die eine ungültige Kodierung und ein try-catch verwendet (für FileNotFoundException) + static void bla9(File file) { + try { + Scanner s = new Scanner(file, "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (FileNotFoundException e) { + // Datei nicht gefunden, hier wird FileNotFoundException behandelt + e.printStackTrace(); + } catch (Exception e) { + // UnsupportedEncodingException wird hier abgefangen + e.printStackTrace(); + } + } + + // Beispiel mit StandardCharsets-Konstanten, die keine Änderung brauchen + static void bla10(File file) { + Scanner s = new Scanner(file, StandardCharsets.UTF_8); + } + + // Beispiel mit Scanner und InputStream, ohne explizite Kodierung (bleibt unverändert) + static void bla11(InputStream is) { + Scanner s = new Scanner(is, StandardCharsets.UTF_8); + } + + // Methode mit Scanner und einer benutzerdefinierten Kodierung als Variable (bleibt unverändert) + private String encodingVar = "ISO-8859-1"; + static void bla12(InputStream is) throws FileNotFoundException { + Scanner s = new Scanner(is, StandardCharsets.ISO_8859_1); + } +} +"""), + FORMATTER( +""" +package test1; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; +import java.util.Formatter; + +public class E1 { + + // Methode mit explizitem UTF-8, sollte durch StandardCharsets.UTF_8 ersetzt werden + static void bla() throws FileNotFoundException, UnsupportedEncodingException { + Formatter s = new Formatter(new File("asdf"), "UTF-8"); // 'UTF-8' wird zu StandardCharsets.UTF_8 + } + + // Methode mit try-catch, die eine Kodierung verwendet und Fehler wirft + static void bli() throws FileNotFoundException { + try { + Formatter s = new Formatter(new File("asdf"), "UTF-8"); // 'UTF-8' wird zu StandardCharsets.UTF_8 + } catch (FileNotFoundException | UnsupportedEncodingException e) { + // Der Catch-Block für UnsupportedEncodingException sollte im Cleanup entfernt werden + e.printStackTrace(); + } + } + + // Methode mit benutzerdefinierter Konstante für das Encoding + private static final String ENCODING_UTF8 = "UTF-8"; + + static void blc() throws FileNotFoundException, UnsupportedEncodingException { + Formatter s = new Formatter(new File("asdf"), ENCODING_UTF8); // 'UTF-8' als Konstante + } + + // Methode mit einer ungültigen Kodierung (z.B. 'non-existing-encoding') + static void bld() throws FileNotFoundException { + try { + Formatter s = new Formatter(new File("asdf"), "non-existing-encoding"); // wirft UnsupportedEncodingException + } catch (FileNotFoundException | UnsupportedEncodingException e) { + e.printStackTrace(); // UnsupportedEncodingException wird hier erwartet + } + } + + // Methode, die eine ungültige Kodierung und ein try-catch verwendet + static void ble() throws FileNotFoundException { + try { + Formatter s = new Formatter(new File("asdf"), "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (FileNotFoundException e) { + // Datei nicht gefunden, hier wird FileNotFoundException behandelt + e.printStackTrace(); + } catch (UnsupportedEncodingException e) { + // UnsupportedEncodingException wird hier behandelt + e.printStackTrace(); + } + } + + // Methode mit StandardCharsets.UTF_8 + static void blf() throws FileNotFoundException { + Formatter s = new Formatter(new File("asdf"), StandardCharsets.UTF_8); // Verwendung von StandardCharsets.UTF_8 + } + + // Beispiel, bei dem das Encoding in einer Variablen gespeichert ist + private String encodingVar = "UTF-8"; + + static void blg() throws FileNotFoundException { + String encoding = "UTF-8"; + Formatter s = new Formatter(new File("asdf"), encoding); // encoding als Variable + } +} +""", """ +package test1; + +import java.io.File; +import java.io.FileNotFoundException; +import java.nio.charset.StandardCharsets; +import java.util.Formatter; + +public class E1 { + + // Methode mit explizitem UTF-8, sollte durch StandardCharsets.UTF_8 ersetzt werden + static void bla() throws FileNotFoundException { + Formatter s = new Formatter(new File("asdf"), StandardCharsets.UTF_8); // 'UTF-8' wird zu StandardCharsets.UTF_8 + } + + // Methode mit try-catch, die eine Kodierung verwendet und Fehler wirft + static void bli() throws FileNotFoundException { + try { + Formatter s = new Formatter(new File("asdf"), StandardCharsets.UTF_8); // 'UTF-8' wird zu StandardCharsets.UTF_8 + } catch (FileNotFoundException e) { + // Der Catch-Block für UnsupportedEncodingException sollte im Cleanup entfernt werden + e.printStackTrace(); + } + } + + // Methode mit benutzerdefinierter Konstante für das Encoding + private static final String ENCODING_UTF8 = "UTF-8"; + + static void blc() throws FileNotFoundException, UnsupportedEncodingException { + Formatter s = new Formatter(new File("asdf"), ENCODING_UTF8); // 'UTF-8' als Konstante + } + + // Methode mit einer ungültigen Kodierung (z.B. 'non-existing-encoding') + static void bld() throws FileNotFoundException { + try { + Formatter s = new Formatter(new File("asdf"), "non-existing-encoding"); // wirft UnsupportedEncodingException + } catch (FileNotFoundException | UnsupportedEncodingException e) { + e.printStackTrace(); // UnsupportedEncodingException wird hier erwartet + } + } + + // Methode, die eine ungültige Kodierung und ein try-catch verwendet + static void ble() throws FileNotFoundException { + try { + Formatter s = new Formatter(new File("asdf"), "non-existing-encoding"); // könnte UnsupportedEncodingException werfen + } catch (FileNotFoundException e) { + // Datei nicht gefunden, hier wird FileNotFoundException behandelt + e.printStackTrace(); + } catch (UnsupportedEncodingException e) { + // UnsupportedEncodingException wird hier behandelt + e.printStackTrace(); + } + } + + // Methode mit StandardCharsets.UTF_8 + static void blf() throws FileNotFoundException { + Formatter s = new Formatter(new File("asdf"), StandardCharsets.UTF_8); // Verwendung von StandardCharsets.UTF_8 + } + + // Beispiel, bei dem das Encoding in einer Variablen gespeichert ist + private String encodingVar = "UTF-8"; + + static void blg() throws FileNotFoundException { + String encoding = "UTF-8"; + Formatter s = new Formatter(new File("asdf"), encoding); // encoding als Variable + } +} +"""), + THREE(""" + package test1; + + import java.io.ByteArrayOutputStream; + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Reader; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + String s="asdf"; //$NON-NLS-1$ + byte[] bytes= s.getBytes(); + System.out.println(bytes.length); + ByteArrayOutputStream ba=new ByteArrayOutputStream(); + String result=ba.toString(); + try { + InputStreamReader is=new InputStreamReader(new FileInputStream("")); //$NON-NLS-1$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + try { + OutputStreamWriter os=new OutputStreamWriter(new FileOutputStream("")); //$NON-NLS-1$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + try { + Reader is=new FileReader(filename); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } + } + """, + + """ +package test1; + +import java.io.ByteArrayOutputStream; +import java.io.InputStreamReader; +import java.io.FileInputStream; +import java.io.FileReader; +import java.io.Reader; +import java.nio.charset.StandardCharsets; +import java.io.FileNotFoundException; + +public class E1 { + void method(String filename) { + String s="asdf"; //$NON-NLS-1$ + byte[] bytes= s.getBytes(StandardCharsets.UTF_8); + System.out.println(bytes.length); + ByteArrayOutputStream ba=new ByteArrayOutputStream(); + String result=ba.toString(StandardCharsets.UTF_8); + try { + InputStreamReader is=new InputStreamReader(new FileInputStream(""), StandardCharsets.UTF_8); //$NON-NLS-1$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + try { + OutputStreamWriter os=new OutputStreamWriter(new FileOutputStream(""), StandardCharsets.UTF_8); //$NON-NLS-1$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + try { + Reader is=new InputStreamReader(new FileInputStream(filename), StandardCharsets.UTF_8); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } +} + """), + ENCODINGASSTRINGPARAMETER( + """ + package test1; + + import java.io.ByteArrayOutputStream; + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Reader; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + String s="asdf"; //$NON-NLS-1$ + //byte[] bytes= s.getBytes(StandardCharsets.UTF_8); + byte[] bytes= s.getBytes("Utf-8"); + System.out.println(bytes.length); + ByteArrayOutputStream ba=new ByteArrayOutputStream(); + String result=ba.toString(); + try { + InputStreamReader is=new InputStreamReader(new FileInputStream(""), "UTF-8"); //$NON-NLS-1$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + try { + OutputStreamWriter os=new OutputStreamWriter(new FileOutputStream(""), "UTF-8"); //$NON-NLS-1$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + try { + Reader is=new FileReader(filename); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } + } + """, + + """ +package test1; + +import java.io.ByteArrayOutputStream; +import java.io.InputStreamReader; +import java.io.FileInputStream; +import java.io.FileReader; +import java.io.Reader; +import java.nio.charset.StandardCharsets; +import java.io.FileNotFoundException; + +public class E1 { + void method(String filename) { + String s="asdf"; //$NON-NLS-1$ + //byte[] bytes= s.getBytes(StandardCharsets.UTF_8); + byte[] bytes= s.getBytes(StandardCharsets.UTF_8); + System.out.println(bytes.length); + ByteArrayOutputStream ba=new ByteArrayOutputStream(); + String result=ba.toString(StandardCharsets.UTF_8); + try { + InputStreamReader is=new InputStreamReader(new FileInputStream(""), StandardCharsets.UTF_8); //$NON-NLS-1$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + try { + OutputStreamWriter os=new OutputStreamWriter(new FileOutputStream(""), StandardCharsets.UTF_8); //$NON-NLS-1$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + try { + Reader is=new InputStreamReader(new FileInputStream(filename), StandardCharsets.UTF_8); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } +} + """); + + String given; + String expected; + + ExplicitEncodingPatternsPreferUTF8(String given, String expected) { + this.given= given; + this.expected= expected; + } + } \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/Java10/QuickFixJava10TestSuite.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/Java10/QuickFixJava10TestSuite.java new file mode 100644 index 00000000000..4c02ef141b4 --- /dev/null +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/Java10/QuickFixJava10TestSuite.java @@ -0,0 +1,24 @@ +/******************************************************************************* + * Copyright (c) 2024 Carsten Hammer and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.quickfix.Java10; + +import org.junit.platform.suite.api.SelectClasses; +import org.junit.platform.suite.api.Suite; + +@Suite +@SelectClasses({ + ExplicitEncodingCleanUpTest.class +}) +public class QuickFixJava10TestSuite { +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/Java22/ExplicitEncodingCleanUpTest.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/Java22/ExplicitEncodingCleanUpTest.java new file mode 100644 index 00000000000..7be88953b25 --- /dev/null +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/Java22/ExplicitEncodingCleanUpTest.java @@ -0,0 +1,107 @@ +/******************************************************************************* + * Copyright (c) 2024 Carsten Hammer and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.quickfix.Java22; + +import java.nio.charset.UnsupportedCharsetException; +import java.util.Hashtable; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; + +import org.eclipse.jdt.testplugin.TestOptions; + +import org.eclipse.core.runtime.CoreException; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.JavaCore; +import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants; + +import org.eclipse.jdt.internal.corext.fix.CleanUpConstants; + +import org.eclipse.jdt.ui.tests.quickfix.rules.AbstractEclipseJava; +import org.eclipse.jdt.ui.tests.quickfix.rules.EclipseJava22; + +import org.eclipse.jdt.internal.ui.JavaPlugin; + +public class ExplicitEncodingCleanUpTest { + + @BeforeEach + protected void setUp() throws Exception,UnsupportedCharsetException { + Hashtable defaultOptions= TestOptions.getDefaultOptions(); + defaultOptions.put(DefaultCodeFormatterConstants.FORMATTER_LINE_SPLIT, Integer.toString(120)); + JavaCore.setOptions(defaultOptions); + TestOptions.initializeCodeGenerationOptions(); + // Use load since restore doesn't really restore the defaults. + JavaPlugin.getDefault().getCodeTemplateStore().load(); + } + + @RegisterExtension + AbstractEclipseJava context= new EclipseJava22(); + + @ParameterizedTest + @EnumSource(ExplicitEncodingPatterns.class) + public void testExplicitEncodingParametrized(ExplicitEncodingPatterns test) throws CoreException { + IPackageFragment pack= context.getfSourceFolder().createPackageFragment("test1", false, null); + ICompilationUnit cu= pack.createCompilationUnit("E1.java", test.given, false, null); + context.enable(CleanUpConstants.EXPLICITENCODING_CLEANUP); + context.enable(CleanUpConstants.EXPLICITENCODING_KEEP_BEHAVIOR); + context.disable(CleanUpConstants.EXPLICITENCODING_INSERT_UTF8); + context.disable(CleanUpConstants.EXPLICITENCODING_AGGREGATE_TO_UTF8); +// context.assertRefactoringResultAsExpected(new ICompilationUnit[] { cu }, new String[] { test.expected }, null); + context.enable(CleanUpConstants.REMOVE_UNNECESSARY_NLS_TAGS); + context.assertRefactoringResultAsExpected(new ICompilationUnit[] { cu }, new String[] { test.expected }, null); + } + + @Test + public void testExplicitEncodingdonttouch() throws CoreException { + IPackageFragment pack= context.getfSourceFolder().createPackageFragment("test1", false, null); + ICompilationUnit cu= pack.createCompilationUnit("E2.java", + """ + package test1; + + import java.io.ByteArrayOutputStream; + import java.io.InputStreamReader; + import java.io.IOException; + import java.nio.charset.Charset; + import java.io.FileInputStream; + import java.io.FileNotFoundException; + import java.io.UnsupportedEncodingException; + + public class E2 { + void method() throws UnsupportedEncodingException, IOException { + String s="asdf"; //$NON-NLS-1$ + byte[] bytes= s.getBytes(Charset.defaultCharset()); + System.out.println(bytes.length); + ByteArrayOutputStream ba=new ByteArrayOutputStream(); + String result=ba.toString(Charset.defaultCharset().displayName()); + try ( + InputStreamReader is=new InputStreamReader(new FileInputStream(""), Charset.defaultCharset()); //$NON-NLS-1$ + ){ } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } + """, + false, null); + + context.enable(CleanUpConstants.EXPLICITENCODING_CLEANUP); + context.enable(CleanUpConstants.EXPLICITENCODING_KEEP_BEHAVIOR); + + context.assertRefactoringHasNoChange(new ICompilationUnit[] { cu }); + } +} diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/Java22/ExplicitEncodingPatterns.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/Java22/ExplicitEncodingPatterns.java new file mode 100644 index 00000000000..322c6c35565 --- /dev/null +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/Java22/ExplicitEncodingPatterns.java @@ -0,0 +1,874 @@ +package org.eclipse.jdt.ui.tests.quickfix.Java22; + +enum ExplicitEncodingPatterns { + + CHARSET( +""" +package test1; + +import java.nio.charset.Charset; + +public class E1 { + + @SuppressWarnings("unused") + void method(String filename) { + // Ursprüngliche Verwendung von Charset.forName() mit verschiedenen Charsets + Charset cs1 = Charset.forName("UTF-8"); //$NON-NLS-1$ + Charset cs1b = Charset.forName("Utf-8"); // Unterschiedliche Schreibweise (diese sollten gleich behandelt werden) //$NON-NLS-1$ + Charset cs2 = Charset.forName("UTF-16"); //$NON-NLS-1$ + Charset cs3 = Charset.forName("UTF-16BE"); //$NON-NLS-1$ + Charset cs4 = Charset.forName("UTF-16LE"); //$NON-NLS-1$ + Charset cs5 = Charset.forName("ISO-8859-1"); //$NON-NLS-1$ + Charset cs6 = Charset.forName("US-ASCII"); //$NON-NLS-1$ + + // Ausgabe, die durch den Cleanup angepasst wird + System.out.println(cs1.toString()); + System.out.println(cs2.toString()); + + // Beispiel mit einer Variablen + String charsetName = "UTF-8"; // Wird durch eine Variable ersetzt //$NON-NLS-1$ + Charset cs7 = Charset.forName(charsetName); // Umstellung erforderlich + System.out.println(cs7); + + // Testen eines ungültigen Charsets + try { + Charset cs8 = Charset.forName("non-existing-charset"); // Ungültiger Charset //$NON-NLS-1$ + System.out.println(cs8); + } catch (IllegalArgumentException e) { + System.out.println("Fehler: " + e.getMessage()); //$NON-NLS-1$ + } + + // Ein benutzerdefinierter Charset-Test + Charset cs9 = Charset.forName("windows-1252"); //$NON-NLS-1$ + System.out.println(cs9.toString()); + } + + void methodWithVariableCharset(String charsetName) { + Charset cs = Charset.forName(charsetName); // Charset über eine Variable + System.out.println(cs.toString()); + } +} +""", + +""" +package test1; + +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; + +public class E1 { + + @SuppressWarnings("unused") + void method(String filename) { + // Ursprüngliche Verwendung von Charset.forName() mit verschiedenen Charsets + Charset cs1 = StandardCharsets.UTF_8; //$NON-NLS-1$ + Charset cs1b = StandardCharsets.UTF_8; // Unterschiedliche Schreibweise (diese sollten gleich behandelt werden) //$NON-NLS-1$ + Charset cs2 = StandardCharsets.UTF_16; //$NON-NLS-1$ + Charset cs3 = StandardCharsets.UTF_16BE; //$NON-NLS-1$ + Charset cs4 = StandardCharsets.UTF_16LE; //$NON-NLS-1$ + Charset cs5 = StandardCharsets.ISO_8859_1; //$NON-NLS-1$ + Charset cs6 = StandardCharsets.US_ASCII; //$NON-NLS-1$ + + // Ausgabe, die durch den Cleanup angepasst wird + System.out.println(cs1.toString()); + System.out.println(cs2.toString()); + + // Beispiel mit einer Variablen + String charsetName = "UTF-8"; // Wird durch eine Variable ersetzt //$NON-NLS-1$ + Charset cs7 = StandardCharsets.UTF_8; // Umstellung erforderlich + System.out.println(cs7); + + // Testen eines ungültigen Charsets + try { + Charset cs8 = Charset.forName("non-existing-charset"); // Ungültiger Charset //$NON-NLS-1$ + System.out.println(cs8); + } catch (IllegalArgumentException e) { + System.out.println("Fehler: " + e.getMessage()); //$NON-NLS-1$ + } + + // Ein benutzerdefinierter Charset-Test + Charset cs9 = Charset.forName("windows-1252"); //$NON-NLS-1$ + System.out.println(cs9.toString()); + } + + void methodWithVariableCharset(String charsetName) { + Charset cs = Charset.forName(charsetName); // Charset über eine Variable + System.out.println(cs.toString()); + } +} +"""), + BYTEARRAYOUTSTREAM(""" + package test1; + + import java.io.ByteArrayOutputStream; + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Reader; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + ByteArrayOutputStream ba=new ByteArrayOutputStream(); + String result=ba.toString(); + ByteArrayOutputStream ba2=new ByteArrayOutputStream(); + String result2=ba2.toString("UTF-8"); + } + } + } + """, + + """ + package test1; + + import java.io.ByteArrayOutputStream; + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Reader; + import java.nio.charset.Charset; + import java.nio.charset.StandardCharsets; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + ByteArrayOutputStream ba=new ByteArrayOutputStream(); + String result=ba.toString(Charset.defaultCharset()); + ByteArrayOutputStream ba2=new ByteArrayOutputStream(); + String result2=ba2.toString(StandardCharsets.UTF_8); + } + } + } + """), + FILEREADER(""" + package test1; + + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Reader; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + try { + Reader is=new FileReader(filename); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } + } + """, + + """ + package test1; + + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Reader; + import java.nio.charset.Charset; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + try { + Reader is=new InputStreamReader(new FileInputStream(filename), Charset.defaultCharset()); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } + } + """), + FILEWRITER(""" + package test1; + + import java.io.FileWriter; + import java.io.Writer; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + try { + Writer fw=new FileWriter(filename); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } + } + """, + + """ + package test1; + + import java.io.FileWriter; + import java.io.OutputStreamWriter; + import java.io.Writer; + import java.nio.charset.Charset; + import java.io.FileNotFoundException; + import java.io.FileOutputStream; + + public class E1 { + void method(String filename) { + try { + Writer fw=new OutputStreamWriter(new FileOutputStream(filename), Charset.defaultCharset()); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } + } + """), + INPUTSTREAMREADER( + """ + package test1; + + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Reader; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + try { + InputStreamReader is1=new InputStreamReader(new FileInputStream("file1.txt")); //$NON-NLS-1$ + InputStreamReader is2=new InputStreamReader(new FileInputStream("file2.txt"), "UTF-8"); //$NON-NLS-1$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } + } + """, + + """ + package test1; + + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Reader; + import java.nio.charset.Charset; + import java.nio.charset.StandardCharsets; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + try { + InputStreamReader is1=new InputStreamReader(new FileInputStream("file1.txt"), Charset.defaultCharset()); //$NON-NLS-1$ + InputStreamReader is2=new InputStreamReader(new FileInputStream("file2.txt"), StandardCharsets.UTF_8); //$NON-NLS-1$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } + } + """), + OUTPUTSTREAMWRITER( + """ + package test1; + + import java.io.ByteArrayOutputStream; + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Reader; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + try { + OutputStreamWriter os=new OutputStreamWriter(new FileOutputStream("")); //$NON-NLS-1$ + OutputStreamWriter os=new OutputStreamWriter(new FileOutputStream(""), "UTF-8"); //$NON-NLS-1$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } + } + """, + + """ + package test1; + + import java.io.ByteArrayOutputStream; + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Reader; + import java.nio.charset.Charset; + import java.nio.charset.StandardCharsets; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + try { + OutputStreamWriter os=new OutputStreamWriter(new FileOutputStream(""), Charset.defaultCharset()); //$NON-NLS-1$ + OutputStreamWriter os=new OutputStreamWriter(new FileOutputStream(""), StandardCharsets.UTF_8); //$NON-NLS-1$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } + } + """), + CHANNELSNEWREADER(""" + package test1; + + import java.io.ByteArrayOutputStream; + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Reader; + import java.nio.channels.ReadableByteChannel; + import java.nio.charset.StandardCharsets; + import java.nio.channels.Channels; + import java.io.FileNotFoundException; + import java.io.UnsupportedEncodingException; + + public class E1 { + void method(String filename) throws UnsupportedEncodingException { + ReadableByteChannel ch; + Reader r=Channels.newReader(ch,"UTF-8"); //$NON-NLS-1$ + } + } + } + """, + + """ + package test1; + + import java.io.ByteArrayOutputStream; + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Reader; + import java.nio.channels.ReadableByteChannel; + import java.nio.charset.StandardCharsets; + import java.nio.channels.Channels; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + ReadableByteChannel ch; + Reader r=Channels.newReader(ch,StandardCharsets.UTF_8); //$NON-NLS-1$ + } + } + } + """), + CHANNELSNEWWRITER(""" + package test1; + + import java.io.ByteArrayOutputStream; + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Writer; + import java.nio.channels.WritableByteChannel; + import java.nio.charset.StandardCharsets; + import java.nio.channels.Channels; + import java.io.FileNotFoundException; + import java.io.UnsupportedEncodingException; + + public class E1 { + void method(String filename) throws UnsupportedEncodingException { + WritableByteChannel ch; + Writer w=Channels.newWriter(ch,"UTF-8"); //$NON-NLS-1$ + } + } + } + """, + + """ + package test1; + + import java.io.ByteArrayOutputStream; + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Writer; + import java.nio.channels.WritableByteChannel; + import java.nio.charset.StandardCharsets; + import java.nio.channels.Channels; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + WritableByteChannel ch; + Writer w=Channels.newWriter(ch,StandardCharsets.UTF_8); //$NON-NLS-1$ + } + } + } + """), + PRINTWRITER(""" + package test1; + + import java.io.PrintWriter; + import java.io.Writer; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + try { + Writer w=new PrintWriter(filename); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } + } + """, + + """ + package test1; + + import java.io.PrintWriter; + import java.io.Writer; + import java.nio.charset.Charset; + import java.io.BufferedWriter; + import java.io.FileNotFoundException; + import java.io.FileOutputStream; + import java.io.OutputStreamWriter; + + public class E1 { + void method(String filename) { + try { + Writer w=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename), Charset.defaultCharset())); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } + } + """), + STRINGGETBYTES( +""" +package test1; + +import java.io.ByteArrayOutputStream; +import java.io.InputStreamReader; +import java.io.FileInputStream; +import java.io.FileReader; +import java.io.Reader; +import java.io.FileNotFoundException; + +public class E1 { + void method(String filename) { + String s="asdf"; //$NON-NLS-1$ + byte[] bytes= s.getBytes(); + byte[] bytes2= s.getBytes("UTF-8"); + System.out.println(bytes.length); + } + } + + void method2(String filename) { + String s="asdf"; //$NON-NLS-1$ + byte[] bytes= s.getBytes(); + try { + byte[] bytes2= s.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + System.out.println(bytes.length); + } +} +""", + +""" +package test1; + +import java.io.ByteArrayOutputStream; +import java.io.InputStreamReader; +import java.io.FileInputStream; +import java.io.FileReader; +import java.io.Reader; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.io.FileNotFoundException; + +public class E1 { + void method(String filename) { + String s="asdf"; //$NON-NLS-1$ + byte[] bytes= s.getBytes(Charset.defaultCharset()); + byte[] bytes2= s.getBytes(StandardCharsets.UTF_8); + System.out.println(bytes.length); + } + } + + void method2(String filename) { + String s="asdf"; //$NON-NLS-1$ + byte[] bytes= s.getBytes(Charset.defaultCharset()); + try { + byte[] bytes2= s.getBytes(StandardCharsets.UTF_8); + } + System.out.println(bytes.length); + } +} +"""), + STRING(""" + package test1; + + import java.io.FileNotFoundException; + import java.io.UnsupportedEncodingException; + + public class E5 { + + static void bla() throws FileNotFoundException, UnsupportedEncodingException { + byte[] b= {(byte)59}; + String s1=new String(b,"UTF-8"); + String s2=new String(b,0,1,"UTF-8"); + } + } + """, + + """ + package test1; + + import java.io.FileNotFoundException; + import java.nio.charset.StandardCharsets; + + public class E5 { + + static void bla() throws FileNotFoundException { + byte[] b= {(byte)59}; + String s1=new String(b,StandardCharsets.UTF_8); + String s2=new String(b,0,1,StandardCharsets.UTF_8); + } + } + """), + PROPERTIESSTORETOXML(""" + package test1; + + import java.io.FileOutputStream; + import java.io.IOException; + import java.util.Properties; + + public class E1 { + static void blu() throws IOException { + Properties p=new Properties(); + try (FileOutputStream os = new FileOutputStream("out.xml")) { + p.storeToXML(os, null, "UTF-8"); + } + try (FileOutputStream os = new FileOutputStream("out.xml")) { + p.storeToXML(os, null); + } + } + } + """, + + """ + package test1; + + import java.io.FileOutputStream; + import java.io.IOException; + import java.nio.charset.StandardCharsets; + import java.util.Properties; + + public class E1 { + static void blu() throws IOException { + Properties p=new Properties(); + try (FileOutputStream os = new FileOutputStream("out.xml")) { + p.storeToXML(os, null, StandardCharsets.UTF_8); + } + try (FileOutputStream os = new FileOutputStream("out.xml")) { + p.storeToXML(os, null, StandardCharsets.UTF_8); + } + } + } + """), + URLDECODER(""" + package test1; + import java.io.UnsupportedEncodingException; + import java.net.URLDecoder; + + public class E2 { + + static void bla() throws UnsupportedEncodingException { + String url=URLDecoder.decode("asdf","UTF-8"); + String url2=URLDecoder.decode("asdf"); + } + } + """, """ + package test1; + import java.net.URLDecoder; + import java.nio.charset.Charset; + import java.nio.charset.StandardCharsets; + + public class E2 { + + static void bla() { + String url=URLDecoder.decode("asdf",StandardCharsets.UTF_8); + String url2=URLDecoder.decode("asdf", Charset.defaultCharset()); + } + } + """), + URLENCODER(""" + package test1; + import java.io.UnsupportedEncodingException; + import java.net.URLEncoder; + + public class E2 { + + static void bla() throws UnsupportedEncodingException { + String url=URLEncoder.encode("asdf","UTF-8"); + String url4=URLEncoder.encode("asdf"); + } + } + """, """ + package test1; + import java.net.URLEncoder; + import java.nio.charset.Charset; + import java.nio.charset.StandardCharsets; + + public class E2 { + + static void bla() { + String url=URLEncoder.encode("asdf",StandardCharsets.UTF_8); + String url4=URLEncoder.encode("asdf", Charset.defaultCharset()); + } + } + """), + SCANNER(""" + package test1; + import java.io.File; + import java.io.FileNotFoundException; + import java.util.Scanner; + + public class E3 { + + static void bla3(InputStream is) throws FileNotFoundException { + Scanner s=new Scanner(new File("asdf"),"UTF-8"); + Scanner s2=new Scanner(is,"UTF-8"); + Scanner s3=new Scanner("asdf"); + } + } + """, +""" +package test1; +import java.io.File; +import java.io.FileNotFoundException; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.Scanner; + +public class E3 { + + static void bla3(InputStream is) throws FileNotFoundException { + Scanner s=new Scanner(new File("asdf"),StandardCharsets.UTF_8); + Scanner s2=new Scanner(is,StandardCharsets.UTF_8); + Scanner s3=new Scanner("asdf", Charset.defaultCharset()); + } +} +"""), + FORMATTER( +""" +package test1; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.UnsupportedEncodingException; +import java.util.Formatter; + +public class E4 { + + static void bla() throws FileNotFoundException, UnsupportedEncodingException { + Formatter s=new Formatter(new File("asdf"),"UTF-8"); + } + + static void bli() throws FileNotFoundException { + try { + Formatter s=new Formatter(new File("asdf"),"UTF-8"); + } catch (FileNotFoundException | UnsupportedEncodingException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } +} +""", """ +package test1; +import java.io.File; +import java.io.FileNotFoundException; +import java.nio.charset.StandardCharsets; +import java.util.Formatter; + +public class E4 { + + static void bla() throws FileNotFoundException { + Formatter s=new Formatter(new File("asdf"),StandardCharsets.UTF_8); + } + + static void bli() throws FileNotFoundException { + try { + Formatter s=new Formatter(new File("asdf"),StandardCharsets.UTF_8); + } catch (FileNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } +} +"""), + THREE(""" + package test1; + + import java.io.ByteArrayOutputStream; + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Reader; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + String s="asdf"; //$NON-NLS-1$ + byte[] bytes= s.getBytes(); + System.out.println(bytes.length); + ByteArrayOutputStream ba=new ByteArrayOutputStream(); + String result=ba.toString(); + try { + InputStreamReader is=new InputStreamReader(new FileInputStream("")); //$NON-NLS-1$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + try { + OutputStreamWriter os=new OutputStreamWriter(new FileOutputStream("")); //$NON-NLS-1$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + try { + Reader is=new FileReader(filename); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } + } + """, + + """ + package test1; + + import java.io.ByteArrayOutputStream; + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Reader; + import java.nio.charset.Charset; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + String s="asdf"; //$NON-NLS-1$ + byte[] bytes= s.getBytes(Charset.defaultCharset()); + System.out.println(bytes.length); + ByteArrayOutputStream ba=new ByteArrayOutputStream(); + String result=ba.toString(Charset.defaultCharset()); + try { + InputStreamReader is=new InputStreamReader(new FileInputStream(""), Charset.defaultCharset()); //$NON-NLS-1$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + try { + OutputStreamWriter os=new OutputStreamWriter(new FileOutputStream(""), Charset.defaultCharset()); //$NON-NLS-1$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + try { + Reader is=new InputStreamReader(new FileInputStream(filename), Charset.defaultCharset()); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } + } + """), + ENCODINGASSTRINGPARAMETER( + """ + package test1; + + import java.io.ByteArrayOutputStream; + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Reader; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + String s="asdf"; //$NON-NLS-1$ + //byte[] bytes= s.getBytes(StandardCharsets.UTF_8); + byte[] bytes= s.getBytes("Utf-8"); + System.out.println(bytes.length); + ByteArrayOutputStream ba=new ByteArrayOutputStream(); + String result=ba.toString(); + try { + InputStreamReader is=new InputStreamReader(new FileInputStream(""), "UTF-8"); //$NON-NLS-1$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + try { + OutputStreamWriter os=new OutputStreamWriter(new FileOutputStream(""), "UTF-8"); //$NON-NLS-1$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + try { + Reader is=new FileReader(filename); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } + } + """, + + """ + package test1; + + import java.io.ByteArrayOutputStream; + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Reader; + import java.nio.charset.Charset; + import java.nio.charset.StandardCharsets; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + String s="asdf"; //$NON-NLS-1$ + //byte[] bytes= s.getBytes(StandardCharsets.UTF_8); + byte[] bytes= s.getBytes(StandardCharsets.UTF_8); + System.out.println(bytes.length); + ByteArrayOutputStream ba=new ByteArrayOutputStream(); + String result=ba.toString(Charset.defaultCharset()); + try { + InputStreamReader is=new InputStreamReader(new FileInputStream(""), StandardCharsets.UTF_8); //$NON-NLS-1$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + try { + OutputStreamWriter os=new OutputStreamWriter(new FileOutputStream(""), StandardCharsets.UTF_8); //$NON-NLS-1$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + try { + Reader is=new InputStreamReader(new FileInputStream(filename), Charset.defaultCharset()); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } + } + """); + + String given; + String expected; + + ExplicitEncodingPatterns(String given, String expected) { + this.given= given; + this.expected= expected; + } + } \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/Java22/QuickFixJava22TestSuite.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/Java22/QuickFixJava22TestSuite.java new file mode 100644 index 00000000000..8c25971a874 --- /dev/null +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/Java22/QuickFixJava22TestSuite.java @@ -0,0 +1,24 @@ +/******************************************************************************* + * Copyright (c) 2024 Carsten Hammer and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.quickfix.Java22; + +import org.junit.platform.suite.api.SelectClasses; +import org.junit.platform.suite.api.Suite; + +@Suite +@SelectClasses({ + ExplicitEncodingCleanUpTest.class +}) +public class QuickFixJava22TestSuite { +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/Java8/ExplicitEncodingCleanUpTest.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/Java8/ExplicitEncodingCleanUpTest.java new file mode 100644 index 00000000000..582ccfc87ab --- /dev/null +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/Java8/ExplicitEncodingCleanUpTest.java @@ -0,0 +1,102 @@ +/******************************************************************************* + * Copyright (c) 2024 Carsten Hammer and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.quickfix.Java8; + +import java.util.Hashtable; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; + +import org.eclipse.jdt.testplugin.TestOptions; + +import org.eclipse.core.runtime.CoreException; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.JavaCore; +import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants; + +import org.eclipse.jdt.internal.corext.fix.CleanUpConstants; + +import org.eclipse.jdt.ui.tests.quickfix.rules.AbstractEclipseJava; +import org.eclipse.jdt.ui.tests.quickfix.rules.EclipseJava8; + +import org.eclipse.jdt.internal.ui.JavaPlugin; + +public class ExplicitEncodingCleanUpTest { + + @BeforeEach + protected void setUp() throws Exception { + Hashtable defaultOptions= TestOptions.getDefaultOptions(); + defaultOptions.put(DefaultCodeFormatterConstants.FORMATTER_LINE_SPLIT, Integer.toString(120)); + JavaCore.setOptions(defaultOptions); + TestOptions.initializeCodeGenerationOptions(); + // Use load since restore doesn't really restore the defaults. + JavaPlugin.getDefault().getCodeTemplateStore().load(); + } + + @RegisterExtension + AbstractEclipseJava context= new EclipseJava8(); + + @ParameterizedTest + @EnumSource(ExplicitEncodingPatterns.class) + public void testExplicitEncodingParametrized(ExplicitEncodingPatterns test) throws CoreException { + IPackageFragment pack= context.getfSourceFolder().createPackageFragment("test1", false, null); + ICompilationUnit cu= pack.createCompilationUnit("E1.java", test.given, false, null); + context.enable(CleanUpConstants.EXPLICITENCODING_CLEANUP); + context.enable(CleanUpConstants.EXPLICITENCODING_KEEP_BEHAVIOR); + context.assertRefactoringResultAsExpected(new ICompilationUnit[] { cu }, new String[] { test.expected }, null); + } + + @Test + public void testExplicitEncodingdonttouch() throws CoreException { + IPackageFragment pack= context.getfSourceFolder().createPackageFragment("test1", false, null); + ICompilationUnit cu= pack.createCompilationUnit("E2.java", + """ + package test1; + + import java.io.ByteArrayOutputStream; + import java.io.InputStreamReader; + import java.io.IOException; + import java.nio.charset.Charset; + import java.io.FileInputStream; + import java.io.FileNotFoundException; + import java.io.UnsupportedEncodingException; + + public class E2 { + void method() throws UnsupportedEncodingException, IOException { + String s="asdf"; //$NON-NLS-1$ + byte[] bytes= s.getBytes(Charset.defaultCharset()); + System.out.println(bytes.length); + ByteArrayOutputStream ba=new ByteArrayOutputStream(); + String result=ba.toString(Charset.defaultCharset().displayName()); + try ( + InputStreamReader is=new InputStreamReader(new FileInputStream(""), Charset.defaultCharset()); //$NON-NLS-1$ + ){ } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } + """, + false, null); + + context.enable(CleanUpConstants.EXPLICITENCODING_CLEANUP); + context.enable(CleanUpConstants.EXPLICITENCODING_KEEP_BEHAVIOR); + + context.assertRefactoringHasNoChange(new ICompilationUnit[] { cu }); + } +} diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/Java8/ExplicitEncodingPatterns.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/Java8/ExplicitEncodingPatterns.java new file mode 100644 index 00000000000..aa5933f75fa --- /dev/null +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/Java8/ExplicitEncodingPatterns.java @@ -0,0 +1,774 @@ +package org.eclipse.jdt.ui.tests.quickfix.Java8; + +enum ExplicitEncodingPatterns { + + CHARSET(""" + package test1; + + import java.io.ByteArrayOutputStream; + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Reader; + import java.nio.charset.Charset; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + Charset cs1= Charset.forName("UTF-8"); + Charset cs1b= Charset.forName("Utf-8"); + Charset cs2= Charset.forName("UTF-16"); + Charset cs3= Charset.forName("UTF-16BE"); + Charset cs4= Charset.forName("UTF-16LE"); + Charset cs5= Charset.forName("ISO-8859-1"); + Charset cs6= Charset.forName("US-ASCII"); + String result= cs1.toString(); + } + } + } + """, + """ + package test1; + + import java.io.ByteArrayOutputStream; + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Reader; + import java.nio.charset.Charset; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + Charset cs1= Charset.forName("UTF-8"); + Charset cs1b= Charset.forName("Utf-8"); + Charset cs2= Charset.forName("UTF-16"); + Charset cs3= Charset.forName("UTF-16BE"); + Charset cs4= Charset.forName("UTF-16LE"); + Charset cs5= Charset.forName("ISO-8859-1"); + Charset cs6= Charset.forName("US-ASCII"); + String result= cs1.toString(); + } + } + } + """), + BYTEARRAYOUTSTREAM(""" + package test1; + + import java.io.ByteArrayOutputStream; + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Reader; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + ByteArrayOutputStream ba=new ByteArrayOutputStream(); + String result=ba.toString(); + ByteArrayOutputStream ba2=new ByteArrayOutputStream(); + String result2=ba2.toString("UTF-8"); + } + } + } + """, + + """ + package test1; + + import java.io.ByteArrayOutputStream; + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Reader; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + ByteArrayOutputStream ba=new ByteArrayOutputStream(); + String result=ba.toString(); + ByteArrayOutputStream ba2=new ByteArrayOutputStream(); + String result2=ba2.toString("UTF-8"); + } + } + } + """), + FILEREADER(""" + package test1; + + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Reader; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + try { + Reader is=new FileReader(filename); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } + } + """, + + """ + package test1; + + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Reader; + import java.nio.charset.Charset; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + try { + Reader is=new InputStreamReader(new FileInputStream(filename), Charset.defaultCharset()); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } + } + """), + FILEWRITER(""" + package test1; + + import java.io.FileWriter; + import java.io.Writer; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + try { + Writer fw=new FileWriter(filename); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } + } + """, + + """ + package test1; + + import java.io.FileWriter; + import java.io.OutputStreamWriter; + import java.io.Writer; + import java.nio.charset.Charset; + import java.io.FileNotFoundException; + import java.io.FileOutputStream; + + public class E1 { + void method(String filename) { + try { + Writer fw=new OutputStreamWriter(new FileOutputStream(filename), Charset.defaultCharset()); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } + } + """), + INPUTSTREAMREADER( + """ + package test1; + + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Reader; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + try { + InputStreamReader is1=new InputStreamReader(new FileInputStream("file1.txt")); //$NON-NLS-1$ + InputStreamReader is2=new InputStreamReader(new FileInputStream("file2.txt"), "UTF-8"); //$NON-NLS-1$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } + } + """, + + """ + package test1; + + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Reader; + import java.nio.charset.Charset; + import java.nio.charset.StandardCharsets; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + try { + InputStreamReader is1=new InputStreamReader(new FileInputStream("file1.txt"), Charset.defaultCharset()); //$NON-NLS-1$ + InputStreamReader is2=new InputStreamReader(new FileInputStream("file2.txt"), StandardCharsets.UTF_8); //$NON-NLS-1$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } + } + """), + OUTPUTSTREAMWRITER( + """ + package test1; + + import java.io.ByteArrayOutputStream; + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Reader; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + try { + OutputStreamWriter os=new OutputStreamWriter(new FileOutputStream("")); //$NON-NLS-1$ + OutputStreamWriter os=new OutputStreamWriter(new FileOutputStream(""), "UTF-8"); //$NON-NLS-1$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } + } + """, + + """ + package test1; + + import java.io.ByteArrayOutputStream; + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Reader; + import java.nio.charset.Charset; + import java.nio.charset.StandardCharsets; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + try { + OutputStreamWriter os=new OutputStreamWriter(new FileOutputStream(""), Charset.defaultCharset()); //$NON-NLS-1$ + OutputStreamWriter os=new OutputStreamWriter(new FileOutputStream(""), StandardCharsets.UTF_8); //$NON-NLS-1$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } + } + """), + CHANNELSNEWREADER(""" + package test1; + + import java.io.ByteArrayOutputStream; + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Reader; + import java.nio.channels.ReadableByteChannel; + import java.nio.charset.StandardCharsets; + import java.nio.channels.Channels; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + ReadableByteChannel ch; + Reader r=Channels.newReader(ch,"UTF-8"); //$NON-NLS-1$ + } + } + } + """, + + """ + package test1; + + import java.io.ByteArrayOutputStream; + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Reader; + import java.nio.channels.ReadableByteChannel; + import java.nio.charset.StandardCharsets; + import java.nio.channels.Channels; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + ReadableByteChannel ch; + Reader r=Channels.newReader(ch,"UTF-8"); //$NON-NLS-1$ + } + } + } + """), + CHANNELSNEWWRITER(""" + package test1; + + import java.io.ByteArrayOutputStream; + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Writer; + import java.nio.channels.WritableByteChannel; + import java.nio.charset.StandardCharsets; + import java.nio.channels.Channels; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + WritableByteChannel ch; + Writer w=Channels.newWriter(ch,"UTF-8"); //$NON-NLS-1$ + } + } + } + """, + + """ + package test1; + + import java.io.ByteArrayOutputStream; + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Writer; + import java.nio.channels.WritableByteChannel; + import java.nio.charset.StandardCharsets; + import java.nio.channels.Channels; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + WritableByteChannel ch; + Writer w=Channels.newWriter(ch,"UTF-8"); //$NON-NLS-1$ + } + } + } + """), + PRINTWRITER(""" + package test1; + + import java.io.PrintWriter; + import java.io.Writer; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + try { + Writer w=new PrintWriter(filename); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } + } + """, + + """ + package test1; + + import java.io.PrintWriter; + import java.io.Writer; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + try { + Writer w=new PrintWriter(filename); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } + } + """), + STRINGGETBYTES(""" + package test1; + + import java.io.ByteArrayOutputStream; + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Reader; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + String s="asdf"; //$NON-NLS-1$ + byte[] bytes= s.getBytes(); + byte[] bytes2= s.getBytes("UTF-8"); + System.out.println(bytes.length); + } + } + } + """, + + """ + package test1; + + import java.io.ByteArrayOutputStream; + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Reader; + import java.nio.charset.Charset; + import java.nio.charset.StandardCharsets; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + String s="asdf"; //$NON-NLS-1$ + byte[] bytes= s.getBytes(Charset.defaultCharset()); + byte[] bytes2= s.getBytes(StandardCharsets.UTF_8); + System.out.println(bytes.length); + } + } + } + """), + STRING(""" + package test1; + + import java.io.FileNotFoundException; + import java.io.UnsupportedEncodingException; + + public class E5 { + + static void bla() throws FileNotFoundException, UnsupportedEncodingException { + byte[] b= {(byte)59}; + String s1=new String(b,"UTF-8"); + String s2=new String(b,0,1,"UTF-8"); + } + } + """, + + """ + package test1; + + import java.io.FileNotFoundException; + import java.io.UnsupportedEncodingException; + + public class E5 { + + static void bla() throws FileNotFoundException, UnsupportedEncodingException { + byte[] b= {(byte)59}; + String s1=new String(b,"UTF-8"); + String s2=new String(b,0,1,"UTF-8"); + } + } + """), + PROPERTIESSTORETOXML(""" + package test1; + + import java.io.FileOutputStream; + import java.io.IOException; + import java.util.Properties; + + public class E1 { + static void blu() throws IOException { + Properties p=new Properties(); + try (FileOutputStream os = new FileOutputStream("out.xml")) { + p.storeToXML(os, null, "UTF-8"); + } + try (FileOutputStream os = new FileOutputStream("out.xml")) { + p.storeToXML(os, null); + } + } + } + """, +""" +package test1; + +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.Properties; + +public class E1 { + static void blu() throws IOException { + Properties p=new Properties(); + try (FileOutputStream os = new FileOutputStream("out.xml")) { + p.storeToXML(os, null, "UTF-8"); + } + try (FileOutputStream os = new FileOutputStream("out.xml")) { + p.storeToXML(os, null); + } + } +} +"""), + URLDECODER(""" + package test1; + import java.io.UnsupportedEncodingException; + import java.net.URLDecoder; + + public class E2 { + + static void bla() throws UnsupportedEncodingException { + String url=URLDecoder.decode("asdf","UTF-8"); + String url2=URLDecoder.decode("asdf"); + } + } + """, """ + package test1; + import java.io.UnsupportedEncodingException; + import java.net.URLDecoder; + + public class E2 { + + static void bla() throws UnsupportedEncodingException { + String url=URLDecoder.decode("asdf","UTF-8"); + String url2=URLDecoder.decode("asdf"); + } + } + """), + URLENCODER(""" + package test1; + import java.io.UnsupportedEncodingException; + import java.net.URLEncoder; + + public class E2 { + + static void bla() throws UnsupportedEncodingException { + String url=URLEncoder.encode("asdf","UTF-8"); + String url4=URLEncoder.encode("asdf"); + } + } + """, """ + package test1; + import java.io.UnsupportedEncodingException; + import java.net.URLEncoder; + + public class E2 { + + static void bla() throws UnsupportedEncodingException { + String url=URLEncoder.encode("asdf","UTF-8"); + String url4=URLEncoder.encode("asdf"); + } + } + """), + SCANNER(""" + package test1; + import java.io.File; + import java.io.FileNotFoundException; + import java.util.Scanner; + + public class E3 { + + static void bla() throws FileNotFoundException { + Scanner s=new Scanner(new File("asdf"),"UTF-8"); + Scanner s2=new Scanner("asdf","UTF-8"); + Scanner s3=new Scanner("asdf"); + } + } + """, """ + package test1; + import java.io.File; + import java.io.FileNotFoundException; + import java.util.Scanner; + + public class E3 { + + static void bla() throws FileNotFoundException { + Scanner s=new Scanner(new File("asdf"),"UTF-8"); + Scanner s2=new Scanner("asdf","UTF-8"); + Scanner s3=new Scanner("asdf"); + } + } + """), + FORMATTER(""" + package test1; + import java.io.File; + import java.io.FileNotFoundException; + import java.io.UnsupportedEncodingException; + import java.util.Formatter; + + public class E4 { + + static void bla() throws FileNotFoundException, UnsupportedEncodingException { + Formatter s=new Formatter(new File("asdf"),"UTF-8"); + } + } + """, +""" +package test1; +import java.io.File; +import java.io.FileNotFoundException; +import java.nio.charset.StandardCharsets; +import java.util.Formatter; + +public class E4 { + + static void bla() throws FileNotFoundException { + Formatter s=new Formatter(new File("asdf"),StandardCharsets.UTF_8); + } +} +"""), + THREE(""" + package test1; + + import java.io.ByteArrayOutputStream; + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Reader; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + String s="asdf"; //$NON-NLS-1$ + byte[] bytes= s.getBytes(); + System.out.println(bytes.length); + ByteArrayOutputStream ba=new ByteArrayOutputStream(); + String result=ba.toString(); + try { + InputStreamReader is=new InputStreamReader(new FileInputStream("")); //$NON-NLS-1$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + try { + OutputStreamWriter os=new OutputStreamWriter(new FileOutputStream("")); //$NON-NLS-1$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + try { + Reader is=new FileReader(filename); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } + } + """, + + """ + package test1; + + import java.io.ByteArrayOutputStream; + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Reader; + import java.nio.charset.Charset; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + String s="asdf"; //$NON-NLS-1$ + byte[] bytes= s.getBytes(Charset.defaultCharset()); + System.out.println(bytes.length); + ByteArrayOutputStream ba=new ByteArrayOutputStream(); + String result=ba.toString(); + try { + InputStreamReader is=new InputStreamReader(new FileInputStream(""), Charset.defaultCharset()); //$NON-NLS-1$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + try { + OutputStreamWriter os=new OutputStreamWriter(new FileOutputStream(""), Charset.defaultCharset()); //$NON-NLS-1$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + try { + Reader is=new InputStreamReader(new FileInputStream(filename), Charset.defaultCharset()); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } + } + """), + ENCODINGASSTRINGPARAMETER( + """ + package test1; + + import java.io.ByteArrayOutputStream; + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Reader; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + String s="asdf"; //$NON-NLS-1$ + //byte[] bytes= s.getBytes(StandardCharsets.UTF_8); + byte[] bytes= s.getBytes("Utf-8"); + System.out.println(bytes.length); + ByteArrayOutputStream ba=new ByteArrayOutputStream(); + String result=ba.toString(); + try { + InputStreamReader is=new InputStreamReader(new FileInputStream(""), "UTF-8"); //$NON-NLS-1$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + try { + OutputStreamWriter os=new OutputStreamWriter(new FileOutputStream(""), "UTF-8"); //$NON-NLS-1$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + try { + Reader is=new FileReader(filename); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } + } + """, + + """ + package test1; + + import java.io.ByteArrayOutputStream; + import java.io.InputStreamReader; + import java.io.FileInputStream; + import java.io.FileReader; + import java.io.Reader; + import java.nio.charset.Charset; + import java.nio.charset.StandardCharsets; + import java.io.FileNotFoundException; + + public class E1 { + void method(String filename) { + String s="asdf"; //$NON-NLS-1$ + //byte[] bytes= s.getBytes(StandardCharsets.UTF_8); + byte[] bytes= s.getBytes(StandardCharsets.UTF_8); + System.out.println(bytes.length); + ByteArrayOutputStream ba=new ByteArrayOutputStream(); + String result=ba.toString(); + try { + InputStreamReader is=new InputStreamReader(new FileInputStream(""), StandardCharsets.UTF_8); //$NON-NLS-1$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + try { + OutputStreamWriter os=new OutputStreamWriter(new FileOutputStream(""), StandardCharsets.UTF_8); //$NON-NLS-1$ + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + try { + Reader is=new InputStreamReader(new FileInputStream(filename), Charset.defaultCharset()); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + } + } + """); + + String given; + String expected; + + ExplicitEncodingPatterns(String given, String expected) { + this.given= given; + this.expected= expected; + } + } \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/Java8/QuickFixJava8TestSuite.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/Java8/QuickFixJava8TestSuite.java new file mode 100644 index 00000000000..124fd5dd2db --- /dev/null +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/Java8/QuickFixJava8TestSuite.java @@ -0,0 +1,24 @@ +/******************************************************************************* + * Copyright (c) 2024 Carsten Hammer and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.quickfix.Java8; + +import org.junit.platform.suite.api.SelectClasses; +import org.junit.platform.suite.api.Suite; + +@Suite +@SelectClasses({ + ExplicitEncodingCleanUpTest.class +}) +public class QuickFixJava8TestSuite { +} diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/rules/AbstractEclipseJava.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/rules/AbstractEclipseJava.java new file mode 100644 index 00000000000..074fd548006 --- /dev/null +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/rules/AbstractEclipseJava.java @@ -0,0 +1,499 @@ +/******************************************************************************* + * Copyright (c) 2024 Carsten Hammer and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.quickfix.rules; + +import static org.eclipse.jdt.internal.corext.fix.CleanUpConstants.DEFAULT_CLEAN_UP_OPTIONS; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.junit.jupiter.api.extension.AfterEachCallback; +import org.junit.jupiter.api.extension.BeforeEachCallback; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleReference; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.core.runtime.Path; +import org.eclipse.core.runtime.preferences.InstanceScope; + +import org.eclipse.core.resources.IContainer; +import org.eclipse.core.resources.IFolder; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IProjectDescription; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.IWorkspace; +import org.eclipse.core.resources.IWorkspaceRoot; +import org.eclipse.core.resources.IWorkspaceRunnable; +import org.eclipse.core.resources.ResourcesPlugin; + +import org.eclipse.ltk.core.refactoring.Change; +import org.eclipse.ltk.core.refactoring.CheckConditionsOperation; +import org.eclipse.ltk.core.refactoring.CompositeChange; +import org.eclipse.ltk.core.refactoring.CreateChangeOperation; +import org.eclipse.ltk.core.refactoring.GroupCategory; +import org.eclipse.ltk.core.refactoring.IUndoManager; +import org.eclipse.ltk.core.refactoring.PerformChangeOperation; +import org.eclipse.ltk.core.refactoring.RefactoringCore; +import org.eclipse.ltk.core.refactoring.RefactoringStatus; +import org.eclipse.ltk.core.refactoring.TextEditBasedChange; +import org.eclipse.ltk.core.refactoring.TextEditBasedChangeGroup; + +import org.eclipse.jdt.core.IClasspathAttribute; +import org.eclipse.jdt.core.IClasspathEntry; +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IJavaElement; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.IPackageFragmentRoot; +import org.eclipse.jdt.core.JavaCore; +import org.eclipse.jdt.core.JavaModelException; +import org.eclipse.jdt.core.compiler.IProblem; +import org.eclipse.jdt.core.dom.ASTParser; +import org.eclipse.jdt.core.dom.CompilationUnit; + +import org.eclipse.jdt.internal.corext.dom.IASTSharedValues; +import org.eclipse.jdt.internal.corext.fix.CleanUpConstants; +import org.eclipse.jdt.internal.corext.fix.CleanUpPreferenceUtil; +import org.eclipse.jdt.internal.corext.fix.CleanUpRefactoring; + +import org.eclipse.jdt.ui.JavaUI; +import org.eclipse.jdt.ui.cleanup.CleanUpOptions; +import org.eclipse.jdt.ui.cleanup.ICleanUp; + +import org.eclipse.jdt.internal.ui.JavaPlugin; +import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; +import org.eclipse.jdt.internal.ui.preferences.cleanup.CleanUpProfileVersioner; +import org.eclipse.jdt.internal.ui.preferences.formatter.ProfileManager; +import org.eclipse.jdt.internal.ui.preferences.formatter.ProfileManager.CustomProfile; +import org.eclipse.jdt.internal.ui.preferences.formatter.ProfileManager.Profile; +import org.eclipse.jdt.internal.ui.preferences.formatter.ProfileStore; +import org.eclipse.jdt.internal.ui.util.CoreUtility; + +public class AbstractEclipseJava implements AfterEachCallback, BeforeEachCallback { + + private final String testresources_stubs; + private final String compliance; + private static final String TEST_SETUP_PROJECT= "TestSetupProject"; //$NON-NLS-1$ + private IPackageFragmentRoot fSourceFolder; + private CustomProfile fProfile; + + public AbstractEclipseJava(String stubs, String compilerversion) { + this.testresources_stubs= stubs; + this.compliance= compilerversion; + } + + @Override + public void beforeEach(ExtensionContext context) throws CoreException { + IJavaProject javaProject= createJavaProject(TEST_SETUP_PROJECT, "bin"); //$NON-NLS-1$ + javaProject.setRawClasspath(getDefaultClasspath(), null); + Map options= javaProject.getOptions(false); + JavaCore.setComplianceOptions(compliance, options); + javaProject.setOptions(options); + setfSourceFolder(addSourceContainer(getProject(TEST_SETUP_PROJECT), "src", new Path[0], //$NON-NLS-1$ + new Path[0], null, new IClasspathAttribute[0])); + Map settings= new HashMap<>(); + fProfile= new ProfileManager.CustomProfile("testProfile", settings, CleanUpProfileVersioner.CURRENT_VERSION, //$NON-NLS-1$ + CleanUpProfileVersioner.PROFILE_KIND); + InstanceScope.INSTANCE.getNode(JavaUI.ID_PLUGIN).put(CleanUpConstants.CLEANUP_PROFILE, fProfile.getID()); + InstanceScope.INSTANCE.getNode(JavaUI.ID_PLUGIN).put(CleanUpConstants.SAVE_PARTICIPANT_PROFILE, + fProfile.getID()); + disableAll(); + } + + @Override + public void afterEach(ExtensionContext context) throws CoreException { + delete(getfSourceFolder()); + } + + public IJavaProject getProject(String projectname) { + return JavaCore.create(ResourcesPlugin.getWorkspace().getRoot().getProject(projectname)); + } + + public IClasspathEntry[] getDefaultClasspath() throws CoreException { + IPath[] rtJarPath= findRtJar(new Path(testresources_stubs)); + return new IClasspathEntry[] { JavaCore.newLibraryEntry(rtJarPath[0], rtJarPath[1], rtJarPath[2], true) }; + } + + protected void disableAll() throws CoreException { + Map settings= fProfile.getSettings(); + JavaPlugin.getDefault().getCleanUpRegistry().getDefaultOptions(DEFAULT_CLEAN_UP_OPTIONS).getKeys() + .forEach(a -> settings.put(a, CleanUpOptions.FALSE)); + commitProfile(); + } + + /** + * Removes an IJavaElement's resource. Retries if deletion failed (e.g. because + * the indexer still locks the file). + * + * @param elem the element to delete + * @throws CoreException if operation failed + */ + public void delete(final IJavaElement elem) throws CoreException { + IWorkspaceRunnable runnable= monitor -> { + if (elem instanceof IJavaProject jproject) { + jproject.setRawClasspath(new IClasspathEntry[0], jproject.getProject().getFullPath(), null); + } + delete(elem.getResource()); + }; + ResourcesPlugin.getWorkspace().run(runnable, null); + } + + private static final int MAX_RETRY= 5; + private static final int RETRY_DELAY= 1000; + + /** + * Removes a resource. Retries if deletion failed (e.g. because the indexer + * still locks the file). + * + * @param resource the resource to delete + * @throws CoreException if operation failed + */ + public static void delete(IResource resource) throws CoreException { + for (int i= 0; i < MAX_RETRY; i++) { + try { + resource.delete(IResource.FORCE | IResource.ALWAYS_DELETE_PROJECT_CONTENT, null); + i= MAX_RETRY; + } catch (CoreException e) { + if (i == MAX_RETRY - 1) { + // JavaPlugin.log(e); + throw e; + } + try { + // JavaPlugin.log(new IllegalStateException("sleep before retrying JavaProjectHelper.delete() for " + resource.getLocationURI())); + Thread.sleep(RETRY_DELAY); // give other threads time to close the file + } catch (InterruptedException e1) { + } + } + } + } + + /** + * @param rtStubsPath the path to the RT stubs + * @return a rt.jar (stubs only) + * @throws CoreException + */ + @SuppressWarnings("javadoc") + public IPath[] findRtJar(IPath rtStubsPath) throws CoreException { + File rtStubs= rtStubsPath.toFile().getAbsoluteFile(); + assertNotNull(rtStubs); + assertTrue(rtStubs.exists()); + return new IPath[] { Path.fromOSString(rtStubs.getPath()), null, null }; + } + + /** + * Returns the bundle associated with this plug-in. + * + * @return the associated bundle + * @since 3.0 + */ + public final Bundle getBundle() { + ClassLoader cl= getClass().getClassLoader(); + if (cl instanceof BundleReference) { + return ((BundleReference) cl).getBundle(); + } + return null; + } + + /** + * Creates a IJavaProject. + * + * @param projectName The name of the project + * @param binFolderName Name of the output folder + * @return Returns the Java project handle + * @throws CoreException Project creation failed + */ + public static IJavaProject createJavaProject(String projectName, String binFolderName) throws CoreException { + IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot(); + IProject project= root.getProject(projectName); + if (!project.exists()) { + project.create(null); + } else { + project.refreshLocal(IResource.DEPTH_INFINITE, null); + } + if (!project.isOpen()) { + project.open(null); + } + IPath outputLocation; + if (binFolderName != null && binFolderName.length() > 0) { + IFolder binFolder= project.getFolder(binFolderName); + if (!binFolder.exists()) { + CoreUtility.createFolder(binFolder, false, true, null); + } + outputLocation= binFolder.getFullPath(); + } else { + outputLocation= project.getFullPath(); + } + if (!project.hasNature(JavaCore.NATURE_ID)) { + addNatureToProject(project, JavaCore.NATURE_ID, null); + } + IJavaProject jproject= JavaCore.create(project); + jproject.setOutputLocation(outputLocation, null); + jproject.setRawClasspath(new IClasspathEntry[0], null); + return jproject; + } + + private static void addNatureToProject(IProject proj, String natureId, IProgressMonitor monitor) + throws CoreException { + IProjectDescription description= proj.getDescription(); + String[] prevNatures= description.getNatureIds(); + String[] newNatures= new String[prevNatures.length + 1]; + System.arraycopy(prevNatures, 0, newNatures, 0, prevNatures.length); + newNatures[prevNatures.length]= natureId; + description.setNatureIds(newNatures); + proj.setDescription(description, monitor); + } + + /** + * Adds a source container to a IJavaProject. + * + * @param jproject The parent project + * @param containerName The name of the new source container + * @param inclusionFilters Inclusion filters to set + * @param exclusionFilters Exclusion filters to set + * @param outputLocation The location where class files are written to, + * null for project output folder + * @param attributes The classpath attributes to set + * @return The handle to the new source container + * @throws CoreException Creation failed + */ + public static IPackageFragmentRoot addSourceContainer(IJavaProject jproject, String containerName, + IPath[] inclusionFilters, IPath[] exclusionFilters, String outputLocation, IClasspathAttribute[] attributes) + throws CoreException { + IProject project= jproject.getProject(); + IContainer container; + if (containerName == null || containerName.length() == 0) { + container= project; + } else { + IFolder folder= project.getFolder(containerName); + if (!folder.exists()) { + CoreUtility.createFolder(folder, false, true, null); + } + container= folder; + } + IPackageFragmentRoot root= jproject.getPackageFragmentRoot(container); + + IPath outputPath= null; + if (outputLocation != null) { + IFolder folder= project.getFolder(outputLocation); + if (!folder.exists()) { + CoreUtility.createFolder(folder, false, true, null); + } + outputPath= folder.getFullPath(); + } + IClasspathEntry cpe= JavaCore.newSourceEntry(root.getPath(), inclusionFilters, exclusionFilters, outputPath, + attributes); + addToClasspath(jproject, cpe); + return root; + } + + public static void addToClasspath(IJavaProject jproject, IClasspathEntry cpe) throws JavaModelException { + IClasspathEntry[] oldEntries= jproject.getRawClasspath(); + for (IClasspathEntry oldEntry : oldEntries) { + if (oldEntry.equals(cpe)) { + return; + } + } + int nEntries= oldEntries.length; + IClasspathEntry[] newEntries= new IClasspathEntry[nEntries + 1]; + System.arraycopy(oldEntries, 0, newEntries, 0, nEntries); + newEntries[nEntries]= cpe; + jproject.setRawClasspath(newEntries, null); + } + + public RefactoringStatus assertRefactoringResultAsExpected(ICompilationUnit[] cus, String[] expected, + Set setOfExpectedGroupCategories) throws CoreException { + RefactoringStatus status= performRefactoring(cus, setOfExpectedGroupCategories); + String[] previews= new String[cus.length]; + for (int i= 0; i < cus.length; i++) { + ICompilationUnit cu= cus[i]; + previews[i]= cu.getBuffer().getContents(); + } + assertEqualStringsIgnoreOrder(previews, expected); + return status; + } + + public RefactoringStatus assertRefactoringHasNoChange(ICompilationUnit[] cus) throws CoreException { + for (ICompilationUnit cu : cus) { + assertNoCompilationError(cu); + } + return assertRefactoringHasNoChangeEventWithError(cus); + } + + protected RefactoringStatus assertRefactoringHasNoChangeEventWithError(ICompilationUnit[] cus) + throws CoreException { + String[] expected= new String[cus.length]; + for (int i= 0; i < cus.length; i++) { + expected[i]= cus[i].getBuffer().getContents(); + } + return assertRefactoringResultAsExpected(cus, expected, null); + } + + protected CompilationUnit assertNoCompilationError(ICompilationUnit cu) { + ASTParser parser= ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL); + parser.setSource(cu); + parser.setResolveBindings(true); + CompilationUnit root= (CompilationUnit) parser.createAST(null); + IProblem[] problems= root.getProblems(); + boolean hasProblems= false; + for (IProblem prob : problems) { + if (!prob.isWarning() && !prob.isInfo()) { + hasProblems= true; + break; + } + } + if (hasProblems) { + StringBuilder builder= new StringBuilder(); + builder.append(cu.getElementName()).append(" has compilation problems: \n"); //$NON-NLS-1$ + for (IProblem prob : problems) { + builder.append(prob.getMessage()).append('\n'); + } + fail(builder.toString()); + } + return root; + } + + public static void assertEqualStringsIgnoreOrder(String[] actuals, String[] expecteds) { + ArrayList list1= new ArrayList<>(Arrays.asList(actuals)); + ArrayList list2= new ArrayList<>(Arrays.asList(expecteds)); + for (int i= list1.size() - 1; i >= 0; i--) { + if (list2.remove(list1.get(i))) { + list1.remove(i); + } + } + int n1= list1.size(); + int n2= list2.size(); + if (n1 + n2 > 0) { + if (n1 == 1 && n2 == 1) { + assertEquals(list2.get(0), list1.get(0)); + } + StringBuilder buf= new StringBuilder(); + for (int i= 0; i < n1; i++) { + String s1= list1.get(i); + if (s1 != null) { + buf.append(s1); + buf.append("\n"); //$NON-NLS-1$ + } + } + String actual= buf.toString(); + buf= new StringBuilder(); + for (int i= 0; i < n2; i++) { + String s2= list2.get(i); + if (s2 != null) { + buf.append(s2); + buf.append("\n"); //$NON-NLS-1$ + } + } + String expected= buf.toString(); + assertEquals(expected, actual); + } + } + + protected final RefactoringStatus performRefactoring(ICompilationUnit[] cus, + Set setOfExpectedGroupCategories) throws CoreException { + final CleanUpRefactoring ref= new CleanUpRefactoring(); + ref.setUseOptionsFromProfile(true); + return performRefactoring(ref, cus, JavaPlugin.getDefault().getCleanUpRegistry().createCleanUps(), + setOfExpectedGroupCategories); + } + + protected RefactoringStatus performRefactoring(final CleanUpRefactoring ref, ICompilationUnit[] cus, + ICleanUp[] cleanUps, Set setOfExpectedGroupCategories) throws CoreException { + for (ICompilationUnit cu : cus) { + ref.addCompilationUnit(cu); + } + for (ICleanUp cleanUp : cleanUps) { + ref.addCleanUp(cleanUp); + } + IUndoManager undoManager= RefactoringCore.getUndoManager(); + undoManager.flush(); + final CreateChangeOperation create= new CreateChangeOperation( + new CheckConditionsOperation(ref, CheckConditionsOperation.ALL_CONDITIONS), RefactoringStatus.FATAL); + final PerformChangeOperation perform= new PerformChangeOperation(create); + perform.setUndoManager(undoManager, ref.getName()); + IWorkspace workspace= ResourcesPlugin.getWorkspace(); + workspace.run(perform, new NullProgressMonitor()); + RefactoringStatus status= create.getConditionCheckingStatus(); + if (status.hasFatalError()) { + throw new CoreException( + new StatusInfo(status.getSeverity(), status.getMessageMatchingSeverity(status.getSeverity()))); + } + assertTrue(perform.changeExecuted(), "Change wasn't executed"); //$NON-NLS-1$ + Change undo= perform.getUndoChange(); + assertNotNull(undo, "Undo doesn't exist"); //$NON-NLS-1$ + assertTrue(undoManager.anythingToUndo(), "Undo manager is empty"); //$NON-NLS-1$ + if (setOfExpectedGroupCategories != null) { + Change change= create.getChange(); + Set actualCategories= new HashSet<>(); + collectGroupCategories(actualCategories, change); + actualCategories.forEach(actualCategory -> { + assertTrue(setOfExpectedGroupCategories.contains(actualCategory.getName()), + () -> "Unexpected group category: " + actualCategory.getName() + ", should find: " //$NON-NLS-1$ //$NON-NLS-2$ + + String.join(", ", setOfExpectedGroupCategories)); //$NON-NLS-1$ + }); + } + return status; + } + + private void collectGroupCategories(Set result, Change change) { + if (change instanceof TextEditBasedChange) { + for (TextEditBasedChangeGroup group : ((TextEditBasedChange) change).getChangeGroups()) { + result.addAll(group.getGroupCategorySet().asList()); + } + } else if (change instanceof CompositeChange) { + for (Change child : ((CompositeChange) change).getChildren()) { + collectGroupCategories(result, child); + } + } + } + + public void enable(String key) throws CoreException { + fProfile.getSettings().put(key, CleanUpOptions.TRUE); + commitProfile(); + } + + public void disable(String key) throws CoreException { + fProfile.getSettings().put(key, CleanUpOptions.FALSE); + commitProfile(); + } + + private void commitProfile() throws CoreException { + List profiles= CleanUpPreferenceUtil.getBuiltInProfiles(); + profiles.add(fProfile); + CleanUpProfileVersioner versioner= new CleanUpProfileVersioner(); + ProfileStore profileStore= new ProfileStore(CleanUpConstants.CLEANUP_PROFILES, versioner); + profileStore.writeProfiles(profiles, InstanceScope.INSTANCE); + CleanUpPreferenceUtil.saveSaveParticipantOptions(InstanceScope.INSTANCE, fProfile.getSettings()); + } + + public IPackageFragmentRoot getfSourceFolder() { + return fSourceFolder; + } + + public void setfSourceFolder(IPackageFragmentRoot fSourceFolder) { + this.fSourceFolder = fSourceFolder; + } +} diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/rules/EclipseJava10.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/rules/EclipseJava10.java new file mode 100644 index 00000000000..52d4f344140 --- /dev/null +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/rules/EclipseJava10.java @@ -0,0 +1,24 @@ +/******************************************************************************* + * Copyright (c) 2024 Carsten Hammer and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.quickfix.rules; + +import org.eclipse.jdt.core.JavaCore; + +public class EclipseJava10 extends AbstractEclipseJava { + private static final String TESTRESOURCES_RTSTUBS_10_JAR= "testresources/rtstubs10.jar"; //$NON-NLS-1$ + + public EclipseJava10() { + super(TESTRESOURCES_RTSTUBS_10_JAR, JavaCore.VERSION_10); + } +} diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/rules/EclipseJava17.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/rules/EclipseJava17.java new file mode 100644 index 00000000000..ef7466ecc63 --- /dev/null +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/rules/EclipseJava17.java @@ -0,0 +1,24 @@ +/******************************************************************************* + * Copyright (c) 2024 Carsten Hammer and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.quickfix.rules; + +import org.eclipse.jdt.core.JavaCore; + +public class EclipseJava17 extends AbstractEclipseJava { + private static final String TESTRESOURCES_RTSTUBS_17_JAR= "testresources/rtstubs_17.jar"; //$NON-NLS-1$ + + public EclipseJava17() { + super(TESTRESOURCES_RTSTUBS_17_JAR, JavaCore.VERSION_17); + } +} diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/rules/EclipseJava18.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/rules/EclipseJava18.java new file mode 100644 index 00000000000..b91b458090c --- /dev/null +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/rules/EclipseJava18.java @@ -0,0 +1,24 @@ +/******************************************************************************* + * Copyright (c) 2024 Carsten Hammer and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.quickfix.rules; + +import org.eclipse.jdt.core.JavaCore; + +public class EclipseJava18 extends AbstractEclipseJava { + private static final String TESTRESOURCES_RTSTUBS_18_JAR= "testresources/rtstubs_17.jar"; //$NON-NLS-1$ + + public EclipseJava18() { + super(TESTRESOURCES_RTSTUBS_18_JAR, JavaCore.VERSION_17); + } +} diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/rules/EclipseJava22.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/rules/EclipseJava22.java new file mode 100644 index 00000000000..d45f01bad04 --- /dev/null +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/rules/EclipseJava22.java @@ -0,0 +1,24 @@ +/******************************************************************************* + * Copyright (c) 2024 Carsten Hammer and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.quickfix.rules; + +import org.eclipse.jdt.core.JavaCore; + +public class EclipseJava22 extends AbstractEclipseJava { + private static final String TESTRESOURCES_RTSTUBS_22_JAR= "testresources/rtstubs_22.jar"; //$NON-NLS-1$ + + public EclipseJava22() { + super(TESTRESOURCES_RTSTUBS_22_JAR, JavaCore.VERSION_22); + } +} diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/rules/EclipseJava8.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/rules/EclipseJava8.java new file mode 100644 index 00000000000..e2b4b678d53 --- /dev/null +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/rules/EclipseJava8.java @@ -0,0 +1,24 @@ +/******************************************************************************* + * Copyright (c) 2024 Carsten Hammer and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.quickfix.rules; + +import org.eclipse.jdt.core.JavaCore; + +public class EclipseJava8 extends AbstractEclipseJava { + private static final String TESTRESOURCES_RTSTUBS18_JAR= "testresources/rtstubs18.jar"; //$NON-NLS-1$ + + public EclipseJava8() { + super(TESTRESOURCES_RTSTUBS18_JAR, JavaCore.VERSION_1_8); + } +} diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/rules/EclipseJava9.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/rules/EclipseJava9.java new file mode 100644 index 00000000000..aa53ce61cce --- /dev/null +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/rules/EclipseJava9.java @@ -0,0 +1,24 @@ +/******************************************************************************* + * Copyright (c) 2024 Carsten Hammer and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.quickfix.rules; + +import org.eclipse.jdt.core.JavaCore; + +public class EclipseJava9 extends AbstractEclipseJava { + private static final String TESTRESOURCES_RTSTUBS_9_JAR= "testresources/rtstubs9.jar"; //$NON-NLS-1$ + + public EclipseJava9() { + super(TESTRESOURCES_RTSTUBS_9_JAR, JavaCore.VERSION_9); + } +} diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/CleanUpConstantsOptions.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/CleanUpConstantsOptions.java index fff49f16e4d..91d26fe898a 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/CleanUpConstantsOptions.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/CleanUpConstantsOptions.java @@ -208,6 +208,10 @@ private static void setEclipseDefaultSettings(CleanUpOptions options) { options.setOption(CONTROL_STATEMENTS_CONVERT_FOR_LOOP_TO_ENHANCED, CleanUpOptions.TRUE); options.setOption(CONTROL_STATEMENTS_CONVERT_FOR_LOOP_ONLY_IF_LOOP_VAR_USED, CleanUpOptions.TRUE); options.setOption(CONTROL_STATEMENTS_USE_ADD_ALL, CleanUpOptions.FALSE); + options.setOption(EXPLICITENCODING_CLEANUP, CleanUpOptions.FALSE); + options.setOption(EXPLICITENCODING_KEEP_BEHAVIOR, CleanUpOptions.TRUE); + options.setOption(EXPLICITENCODING_INSERT_UTF8, CleanUpOptions.FALSE); + options.setOption(EXPLICITENCODING_AGGREGATE_TO_UTF8, CleanUpOptions.FALSE); } private static void setSaveParticipantSettings(CleanUpOptions options) { @@ -396,6 +400,10 @@ private static void setSaveParticipantSettings(CleanUpOptions options) { options.setOption(CONTROL_STATEMENTS_CONVERT_FOR_LOOP_TO_ENHANCED, CleanUpOptions.FALSE); options.setOption(CONTROL_STATEMENTS_CONVERT_FOR_LOOP_ONLY_IF_LOOP_VAR_USED, CleanUpOptions.FALSE); options.setOption(CONTROL_STATEMENTS_USE_ADD_ALL, CleanUpOptions.FALSE); + options.setOption(EXPLICITENCODING_CLEANUP, CleanUpOptions.FALSE); + options.setOption(EXPLICITENCODING_KEEP_BEHAVIOR, CleanUpOptions.TRUE); + options.setOption(EXPLICITENCODING_INSERT_UTF8, CleanUpOptions.FALSE); + options.setOption(EXPLICITENCODING_AGGREGATE_TO_UTF8, CleanUpOptions.FALSE); } public static void initDefaults(IPreferenceStore store) { diff --git a/org.eclipse.jdt.ui/plugin.xml b/org.eclipse.jdt.ui/plugin.xml index 5c21a366586..3a695b9ff91 100644 --- a/org.eclipse.jdt.ui/plugin.xml +++ b/org.eclipse.jdt.ui/plugin.xml @@ -7116,10 +7116,15 @@ id="org.eclipse.jdt.ui.cleanup.switch" runAfter="org.eclipse.jdt.ui.cleanup.toolscleanup"> + + + runAfter="org.eclipse.jdt.ui.cleanup.explicit_encoding"> { + public UseExplicitEncodingCleanUp(final Map options) { + super(options, new UseExplicitEncodingCleanUpCore()); + } + + public UseExplicitEncodingCleanUp() { + this(Collections.EMPTY_MAP); + } +} diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/cleanup/CleanUpMessages.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/cleanup/CleanUpMessages.java index e42841f5dbe..018329b9205 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/cleanup/CleanUpMessages.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/cleanup/CleanUpMessages.java @@ -241,6 +241,12 @@ public class CleanUpMessages extends NLS { public static String JavaFeatureTabPage_CheckboxName_StringBufferBuilderToTextBlock; + public static String JavaFeatureTabPage_GroupName_Encoding; + public static String JavaFeatureTabPage_CheckboxName_ExplicitEncoding; + public static String JavaFeatureTabPage_RadioName_Keep_Behavior; + public static String JavaFeatureTabPage_RadioName_Insert_UTF8; + public static String JavaFeatureTabPage_RadioName_Aggregate_to_UTF8; + static { // initialize resource bundle NLS.initializeMessages(BUNDLE_NAME, CleanUpMessages.class); diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/cleanup/CleanUpMessages.properties b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/cleanup/CleanUpMessages.properties index 0fc33bf6230..1f970689a52 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/cleanup/CleanUpMessages.properties +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/cleanup/CleanUpMessages.properties @@ -218,3 +218,8 @@ JavaFeatureTabPage_CheckboxName_ConstantsForSystemProperty_PathSeparator=Path se JavaFeatureTabPage_CheckboxName_ConstantsForSystemProperty_JavaVersionProperty=Java Version property JavaFeatureTabPage_CheckboxName_ConstantsForSystemProperty_JavaVersionSpecProperty=Java Spec Version property +JavaFeatureTabPage_CheckboxName_ExplicitEncoding=Set explicit encoding +JavaFeatureTabPage_RadioName_Aggregate_to_UTF8=Insert/replace to make use of UTF-8 instead of platform encoding.\n Try to use single constant per project. +JavaFeatureTabPage_RadioName_Insert_UTF8=Insert/replace to make use of UTF-8 instead of platform encoding. +JavaFeatureTabPage_RadioName_Keep_Behavior=Don't change behavior - just insert/replace code to make usage of platform encoding visible. +JavaFeatureTabPage_GroupName_Encoding=Encoding \ No newline at end of file diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/cleanup/CodeStyleTabPage.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/cleanup/CodeStyleTabPage.java index d19506b5fdc..f2625912292 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/cleanup/CodeStyleTabPage.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/cleanup/CodeStyleTabPage.java @@ -33,6 +33,7 @@ import org.eclipse.jdt.internal.ui.fix.ReduceIndentationCleanUp; import org.eclipse.jdt.internal.ui.fix.SimplifyBooleanIfElseCleanUpCore; import org.eclipse.jdt.internal.ui.fix.SwitchCleanUpCore; +import org.eclipse.jdt.internal.ui.fix.UseExplicitEncodingCleanUp; import org.eclipse.jdt.internal.ui.fix.VariableDeclarationCleanUpCore; public final class CodeStyleTabPage extends AbstractCleanUpTabPage { @@ -53,7 +54,8 @@ protected AbstractCleanUp[] createPreviewCleanUps(Map values) { new InstanceofCleanUp(values), new VariableDeclarationCleanUpCore(values), new SimplifyBooleanIfElseCleanUpCore(values), - new LambdaExpressionAndMethodRefCleanUp(values) + new LambdaExpressionAndMethodRefCleanUp(values), + new UseExplicitEncodingCleanUp(values) }; } @@ -122,5 +124,16 @@ protected void doCreatePreferences(Composite composite, int numColumns) { CheckboxPreference simplifyLambdaExpressionAndMethodRef= createCheckboxPref(functionalInterfacesGroup, numColumns, CleanUpMessages.CodeStyleTabPage_CheckboxName_SimplifyLambdaExpressionAndMethodRefSyntax, CleanUpConstants.SIMPLIFY_LAMBDA_EXPRESSION_AND_METHOD_REF, CleanUpModifyDialog.FALSE_TRUE); registerPreference(simplifyLambdaExpressionAndMethodRef); + + Group encodingGroup= createGroup(numColumns, composite, CleanUpMessages.JavaFeatureTabPage_GroupName_Encoding); + final CheckboxPreference explicit_encoding= createCheckboxPref(encodingGroup, numColumns, CleanUpMessages.JavaFeatureTabPage_CheckboxName_ExplicitEncoding, CleanUpConstants.EXPLICITENCODING_CLEANUP, CleanUpModifyDialog.FALSE_TRUE); + intent(encodingGroup); + final RadioPreference useKeep_Behavior= createRadioPref(encodingGroup, numColumns - 1, CleanUpMessages.JavaFeatureTabPage_RadioName_Keep_Behavior, CleanUpConstants.EXPLICITENCODING_KEEP_BEHAVIOR, CleanUpModifyDialog.FALSE_TRUE); + intent(encodingGroup); + final RadioPreference useINSERT_UTF8= createRadioPref(encodingGroup, numColumns - 1, CleanUpMessages.JavaFeatureTabPage_RadioName_Insert_UTF8, CleanUpConstants.EXPLICITENCODING_INSERT_UTF8, CleanUpModifyDialog.FALSE_TRUE); + intent(encodingGroup); + final RadioPreference useAGGREGATE_TO_UTF8= createRadioPref(encodingGroup, numColumns - 1, CleanUpMessages.JavaFeatureTabPage_RadioName_Aggregate_to_UTF8, CleanUpConstants.EXPLICITENCODING_AGGREGATE_TO_UTF8, CleanUpModifyDialog.FALSE_TRUE); + registerSlavePreference(explicit_encoding, new RadioPreference[] {useKeep_Behavior, useINSERT_UTF8, useAGGREGATE_TO_UTF8}); + } } diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/cleanup/JavaFeatureTabPage.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/cleanup/JavaFeatureTabPage.java index 7ebed84b579..5177bb63761 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/cleanup/JavaFeatureTabPage.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/cleanup/JavaFeatureTabPage.java @@ -151,5 +151,7 @@ protected void doCreatePreferences(final Composite composite, final int numColum CheckboxPreference unboxing= createCheckboxPref(java1d5Group, numColumns, CleanUpMessages.JavaFeatureTabPage_CheckboxName_Unboxing, CleanUpConstants.USE_UNBOXING, CleanUpModifyDialog.FALSE_TRUE); registerPreference(unboxing); + + } } diff --git a/pom.xml b/pom.xml index f2de4b86fac..dbccdefd615 100644 --- a/pom.xml +++ b/pom.xml @@ -54,7 +54,7 @@ org.eclipse.jdt.text.tests org.eclipse.jdt.ui.tests - org.eclipse.jdt.ui.tests.refactoring + org.eclipse.jdt.ui.tests.refactoring org.eclipse.jdt.ui.junit.sampleproject org.eclipse.jdt.ui.examples.projects org.eclipse.jdt.core.manipulation