file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
TarBzip2.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/application/algorithm/type/TarBzip2.java
/* * Copyright (C) 2018 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.application.algorithm.type; import org.apache.commons.compress.archivers.ArchiveStreamFactory; import org.apache.commons.compress.compressors.CompressorInputStream; import org.apache.commons.compress.compressors.CompressorOutputStream; import org.apache.commons.compress.compressors.CompressorStreamFactory; import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream; import org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * Represents the TAR+BZIP2 archive type. * * @author Matthias Fussenegger */ public class TarBzip2 extends Tar { /** * Constructs a new instance of this class using the TAR constant of * {@link ArchiveStreamFactory} and the BZIP2 constant of * {@link CompressorStreamFactory}. */ public TarBzip2() { super(ArchiveStreamFactory.TAR, CompressorStreamFactory.BZIP2); } @Override protected CompressorInputStream makeCompressorInputStream(InputStream stream) throws IOException { return new BZip2CompressorInputStream(stream); } @Override protected CompressorOutputStream makeCompressorOutputStream(OutputStream stream) throws IOException { return new BZip2CompressorOutputStream(stream); } }
2,115
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
Gzip.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/application/algorithm/type/Gzip.java
/* * Copyright (C) 2017 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.application.algorithm.type; import org.apache.commons.compress.compressors.CompressorInputStream; import org.apache.commons.compress.compressors.CompressorOutputStream; import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream; import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream; import org.apache.commons.compress.compressors.gzip.GzipParameters; import org.gzipper.java.application.algorithm.CompressorAlgorithm; import org.gzipper.java.application.util.FileUtils; import org.gzipper.java.util.Settings; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * Represents the GZIP archive type. * * @author Matthias Fussenegger */ public class Gzip extends CompressorAlgorithm { /** * Returns {@link GzipParameters} with the operating system, modification * time (which is the current time in milliseconds) and the specified * filename without the directory path already set. * * @param filename the name of the file without directory path. * @return the default {@link GzipParameters}. */ public static GzipParameters getDefaultGzipParams(String filename) { GzipParameters params = new GzipParameters(); Settings settings = Settings.getInstance(); int osValue = settings.getOs().getOsInfo().getValue(); params.setOperatingSystem(osValue); params.setModificationTime(System.currentTimeMillis()); if (filename != null && !FileUtils.normalize(filename).contains("/")) { params.setFileName(filename); } return params; } @Override protected CompressorInputStream makeCompressorInputStream( InputStream stream, CompressorOptions options) throws IOException { GzipCompressorInputStream gcis = new GzipCompressorInputStream(stream); options.setName(gcis.getMetaData().getFileName()); return gcis; } @Override protected CompressorOutputStream makeCompressorOutputStream( OutputStream stream, CompressorOptions options) throws IOException { // set additional parameters for compressor stream GzipParameters params = getDefaultGzipParams(options.getName()); params.setCompressionLevel(options.getLevel()); return new GzipCompressorOutputStream(stream, params); } }
3,100
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
Zip.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/application/algorithm/type/Zip.java
/* * Copyright (C) 2018 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.application.algorithm.type; import org.apache.commons.compress.archivers.ArchiveInputStream; import org.apache.commons.compress.archivers.ArchiveOutputStream; import org.apache.commons.compress.archivers.ArchiveStreamFactory; import org.apache.commons.compress.archivers.zip.Zip64Mode; import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream; import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; import org.apache.commons.compress.compressors.CompressorInputStream; import org.apache.commons.compress.compressors.CompressorOutputStream; import org.apache.commons.compress.compressors.CompressorStreamFactory; import org.gzipper.java.application.algorithm.ArchivingAlgorithm; import java.io.InputStream; import java.io.OutputStream; /** * Represents the ZIP archive type. * * @author Matthias Fussenegger */ public class Zip extends ArchivingAlgorithm { /** * Constructs a new instance of this class using the ZIP constant of * {@link ArchiveStreamFactory} and the DEFLATE constant of * {@link CompressorStreamFactory}. */ public Zip() { super(ArchiveStreamFactory.ZIP, CompressorStreamFactory.DEFLATE); } /** * Constructs a new instance of this class using the specified values. * * @param archiveType the archive type, which has to be a constant of * {@link ArchiveStreamFactory}. * @param compressionType the compression type, which has to be a constant * of {@link CompressorStreamFactory}. */ public Zip(String archiveType, String compressionType) { super(archiveType, compressionType); } @Override protected ArchiveOutputStream makeArchiveOutputStream(OutputStream stream) { ZipArchiveOutputStream zaos = new ZipArchiveOutputStream(stream); zaos.setLevel(compressionLevel); zaos.setUseZip64(Zip64Mode.AsNeeded); return zaos; } @Override protected ArchiveInputStream makeArchiveInputStream(InputStream stream) { return new ZipArchiveInputStream(stream, null, false, true); } @Override protected CompressorInputStream makeCompressorInputStream(InputStream stream) { return null; // as no separate compressor stream is required } @Override protected CompressorOutputStream makeCompressorOutputStream(OutputStream stream) { return null; // as no separate compressor stream is required } }
3,294
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
TarGzip.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/application/algorithm/type/TarGzip.java
/* * Copyright (C) 2018 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.application.algorithm.type; import org.apache.commons.compress.archivers.ArchiveStreamFactory; import org.apache.commons.compress.compressors.CompressorInputStream; import org.apache.commons.compress.compressors.CompressorOutputStream; import org.apache.commons.compress.compressors.CompressorStreamFactory; import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream; import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream; import org.apache.commons.compress.compressors.gzip.GzipParameters; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * Represents the TAR+GZ archive type. * * @author Matthias Fussenegger */ public class TarGzip extends Tar { /** * Constructs a new instance of this class using the TAR constant of * {@link ArchiveStreamFactory} and the GZIP constant of * {@link CompressorStreamFactory}. */ public TarGzip() { super(ArchiveStreamFactory.TAR, CompressorStreamFactory.GZIP); } @Override protected CompressorOutputStream makeCompressorOutputStream(OutputStream stream) throws IOException { // set additional parameters for compressor stream GzipParameters params = Gzip.getDefaultGzipParams(null); params.setCompressionLevel(compressionLevel); return new GzipCompressorOutputStream(stream, params); } @Override protected CompressorInputStream makeCompressorInputStream(InputStream stream) throws IOException { return new GzipCompressorInputStream(stream); } }
2,360
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
Jar.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/application/algorithm/type/Jar.java
/* * Copyright (C) 2018 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.application.algorithm.type; import org.apache.commons.compress.archivers.ArchiveOutputStream; import org.apache.commons.compress.archivers.ArchiveStreamFactory; import org.apache.commons.compress.archivers.jar.JarArchiveOutputStream; import org.apache.commons.compress.archivers.zip.Zip64Mode; import org.apache.commons.compress.compressors.CompressorStreamFactory; import java.io.OutputStream; /** * Represents the JAR archive type. * * @author Matthias Fussenegger */ public class Jar extends Zip { /** * Constructs a new instance of this class using the JAR constant of * {@link ArchiveStreamFactory} and the DEFLATE constant of * {@link CompressorStreamFactory}. */ public Jar() { super(ArchiveStreamFactory.JAR, CompressorStreamFactory.DEFLATE); } @Override protected ArchiveOutputStream makeArchiveOutputStream(OutputStream stream) { JarArchiveOutputStream jaos = new JarArchiveOutputStream(stream); jaos.setLevel(compressionLevel); jaos.setUseZip64(Zip64Mode.AsNeeded); jaos.setFallbackToUTF8(true); return jaos; } }
1,847
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
TarLzma.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/application/algorithm/type/TarLzma.java
/* * Copyright (C) 2018 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.application.algorithm.type; import org.apache.commons.compress.archivers.ArchiveStreamFactory; import org.apache.commons.compress.compressors.CompressorInputStream; import org.apache.commons.compress.compressors.CompressorOutputStream; import org.apache.commons.compress.compressors.CompressorStreamFactory; import org.apache.commons.compress.compressors.lzma.LZMACompressorInputStream; import org.apache.commons.compress.compressors.lzma.LZMACompressorOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * Represents the TAR+LZMA archive type. * * @author Matthias Fussenegger */ public class TarLzma extends Tar { /** * Constructs a new instance of this class using the TAR constant of * {@link ArchiveStreamFactory} and the LZMA constant of * {@link CompressorStreamFactory}. */ public TarLzma() { super(ArchiveStreamFactory.TAR, CompressorStreamFactory.LZMA); } @Override protected CompressorOutputStream makeCompressorOutputStream(OutputStream stream) throws IOException { return new LZMACompressorOutputStream(stream); } @Override protected CompressorInputStream makeCompressorInputStream(InputStream stream) throws IOException { return new LZMACompressorInputStream(stream); } }
2,049
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
ArchiveType.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/application/model/ArchiveType.java
/* * Copyright (C) 2018 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.application.model; import org.gzipper.java.application.algorithm.CompressionAlgorithm; import org.gzipper.java.application.algorithm.type.*; /** * Enumeration for archive types. * * @author Matthias Fussenegger */ public enum ArchiveType { ZIP("Zip", "ZIP", new String[]{"*.zip"}) { @Override public CompressionAlgorithm getAlgorithm() { return new Zip(); } }, JAR("Jar", "JAR", new String[]{"*.jar"}) { @Override public CompressionAlgorithm getAlgorithm() { return new Jar(); } }, GZIP("Gzip", "GZIP", new String[]{"*.gz", "*.gzip"}) { @Override public CompressionAlgorithm getAlgorithm() { return new Gzip(); } }, TAR("Tar", "TAR", new String[]{"*.tar"}) { @Override public CompressionAlgorithm getAlgorithm() { return new Tar(); } }, TAR_GZ("TarGz", "TAR+GZIP", new String[]{"*.tar.gz", "*.tar.gzip", "*.tgz"}) { @Override public CompressionAlgorithm getAlgorithm() { return new TarGzip(); } }, TAR_BZ2("TarBz2", "TAR+BZIP2", new String[]{"*.tar.bz2", "*.tar.bzip2", "*.tbz2"}) { @Override public CompressionAlgorithm getAlgorithm() { return new TarBzip2(); } }, TAR_LZ("TarLz", "TAR+LZMA", new String[]{"*.tar.lzma", "*.tar.lz", "*.tlz"}) { @Override public CompressionAlgorithm getAlgorithm() { return new TarLzma(); } }, TAR_XZ("TarXz", "TAR+XZ", new String[]{"*.tar.xz", "*.txz"}) { @Override public CompressionAlgorithm getAlgorithm() { return new TarXz(); } }; /** * The name of the archive type. */ private final String _name; /** * The display (friendly) name of the archive type. */ private final String _displayName; /** * An array of strings consisting of the file extensions for the archive * type. */ private final String[] _extensionNames; ArchiveType(String name, String displayName, String[] extensionNames) { _name = name; _displayName = displayName; _extensionNames = extensionNames; } /** * Returns the algorithm that belongs to this type. * * @return the algorithm that belongs to this type. */ public abstract CompressionAlgorithm getAlgorithm(); /** * Returns the name of this archive type. * * @return the name of this archive type. */ public String getName() { return _name; } /** * Returns the display (friendly) name of this archive type. * * @return the display (friendly) name of this archive type. */ public String getDisplayName() { return _displayName; } /** * Returns the file extensions of this archive type. * * @param includeAsterisks true to include asterisks, false to remove them. * @return the file extensions of this archive type as string array. */ public String[] getExtensionNames(boolean includeAsterisks) { String[] extensionNames; if (includeAsterisks) { extensionNames = _extensionNames; } else { extensionNames = new String[_extensionNames.length]; for (int i = 0; i < _extensionNames.length; ++i) { extensionNames[i] = _extensionNames[i].substring(1); } } return extensionNames; } /** * Returns the default file extension of this archive type. The default file * extension is the first one that has been specified in the array of file * extensions. * * @return the default file extension of this archive type as string. */ public String getDefaultExtensionName() { return _extensionNames.length > 0 ? _extensionNames[0].substring(1) : ""; } @Override public String toString() { return _displayName + " (" + _extensionNames[0] + ")"; } }
4,793
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
OperatingSystem.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/application/model/OperatingSystem.java
/* * Copyright (C) 2018 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.application.model; /** * Class that represents an operating system. This class basically acts as a * wrapper for an {@link OS} enumeration while offering additional * functionalities that may be required for archiving operations. * * @author Matthias Fussenegger */ public class OperatingSystem { /** * The aggregated enumeration which represents the operating system. */ protected final OS _operatingSystem; /** * Constructs a new instance of this class using the specified enumeration. * * @param operatingSystem the operating system to be aggregated. */ public OperatingSystem(OS operatingSystem) { _operatingSystem = operatingSystem; } /** * Returns the default user directory of the system. * * @return the default user directory as string. */ public String getDefaultUserDirectory() { return System.getProperty("user.home"); } /** * Returns the enumeration for the current operating system. * * @return the enumeration for the current operating system. */ public OS getOsInfo() { return _operatingSystem; } }
1,947
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
OS.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/application/model/OS.java
/* * Copyright (C) 2017 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.application.model; import org.apache.commons.compress.compressors.gzip.GzipParameters; /** * Enumeration for operating systems. * * @author Matthias Fussenegger */ public enum OS { UNIX("Unix", 3), WINDOWS("Windows", 11); /** * The name of the operating system. */ private final String _name; /** * The defined value as of {@link GzipParameters}. */ private final int _value; OS(String name, int value) { _name = name; _value = value; } /** * Returns the name of the operating system. * * @return the name of the operating system. */ public String getName() { return _name; } /** * Returns the value that is defined as of {@link GzipParameters}. * * @return the value that is defined as of {@link GzipParameters}. */ public int getValue() { return _value; } }
1,702
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
I18N.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/i18n/I18N.java
/* * Copyright (C) 2018 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.i18n; import java.util.Locale; import java.util.ResourceBundle; /** * Class that allows global access to the internationalization files, which are * accessed through a {@link ResourceBundle}. * * @author Matthias Fussenegger */ public final class I18N { /** * The resource bundle used to access internationalized strings. */ private static ResourceBundle _bundle; /** * Returns the value that belongs to the specified key. * * @param key the key as string. * @return the value that belongs to the key. */ public static String getString(String key) { return getBundle().getString(key); } /** * Returns the value that belongs to the specified key. * * @param key the key as string. * @param args optional format arguments. * @return the value that belongs to the key. */ public static String getString(String key, Object... args) { return String.format(getString(key), args); } /** * Returns the aggregated {@link ResourceBundle} used by this class. * * @return the aggregated {@link ResourceBundle} used by this class. */ public static synchronized ResourceBundle getBundle() { if (_bundle == null) { final String base = "i18n/gzipper"; final Locale locale = determineLocale(); _bundle = locale != null ? ResourceBundle.getBundle(base, locale) : ResourceBundle.getBundle(base); } return _bundle; } /** * Determines the {@link Locale} of the system. * * @return the {@link Locale} of the system. May be {@code null}. */ private static Locale determineLocale() { final String userLang = System.getProperty("user.language"); for (Locale locale : Locale.getAvailableLocales()) { if (locale.getLanguage().equals(userLang)) { return locale; } } return null; } private I18N() { throw new AssertionError("Holds static members only"); } }
2,830
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
Log.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/util/Log.java
/* * Copyright (C) 2017 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.util; import java.io.PrintWriter; import java.io.StringWriter; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; /** * Convenience class for application wide logging. * * @author Matthias Fussenegger */ public final class Log { /** * Default logger named {@code GZipper.class.getName()}. */ public static final Logger DEFAULT_LOGGER; static { DEFAULT_LOGGER = Logger.getLogger(Log.class.getName()); } /** * Name of the UI logger. The logger will be retrieved via * {@code java.util.logging.Logger.getLogger()}. */ private static String LoggerNameUI; /** * If set to true, verbose logging is enabled. Verbose logging means that * the output in the UI is more detailed. This means that if logged, even * full exception messages will be displayed. */ private static boolean _verboseUiLogging; /** * Enables verbose logging for the UI output. * * @param verboseUiLogging true to enable, false to disable. */ public static void setVerboseUiLogging(boolean verboseUiLogging) { _verboseUiLogging = verboseUiLogging; } /** * Sets the name of the logger to be used for UI logging. * * @param loggerName the name of the logger. */ public static void setLoggerForUI(String loggerName) { LoggerNameUI = loggerName; } /** * Logs a new error message including an exception. * * @param msg the message to log. * @param thrown the exception to include. */ public static void e(String msg, Throwable thrown) { msg += "\n" + stackTraceAsString(thrown); LogRecord record = new LogRecord(Level.SEVERE, msg); record.setThrown(thrown); log(record, _verboseUiLogging); } /** * Logs a new error message with an optional parameter. * * @param msg the message to log. * @param param the optional parameter. */ public static void e(String msg, Object param) { LogRecord record = new LogRecord(Level.SEVERE, msg); record.setParameters(new Object[]{param}); log(record, _verboseUiLogging); } /** * Logs a new error message with optional parameters. * * @param msg the message to log. * @param params the optional parameters. */ public static void e(String msg, Object... params) { LogRecord record = new LogRecord(Level.SEVERE, msg); record.setParameters(params); log(record, _verboseUiLogging); } /** * Logs a new info message including an exception. * * @param msg the message to log. * @param thrown the exception to include. * @param uiLogging true to log to the UI as well. */ public static void i(String msg, Throwable thrown, boolean uiLogging) { msg += "\n" + stackTraceAsString(thrown); LogRecord record = new LogRecord(Level.INFO, msg); record.setThrown(thrown); log(record, uiLogging); } /** * Logs a new info message with an optional parameter. * * @param msg the message to log. * @param param the optional parameter. * @param uiLogging true to log to the UI as well. */ public static void i(String msg, Object param, boolean uiLogging) { LogRecord record = new LogRecord(Level.INFO, msg); record.setParameters(new Object[]{param}); log(record, uiLogging); } /** * Logs a new info message with optional parameters. * * @param msg the message to log. * @param uiLogging true to log to the UI as well. * @param params the optional parameters. */ public static void i(String msg, boolean uiLogging, Object... params) { LogRecord record = new LogRecord(Level.INFO, msg); record.setParameters(params); log(record, uiLogging); } /** * Logs a new warning message including an exception. * * @param msg the message to log. * @param thrown the exception to include. * @param uiLogging true to log to the UI as well. */ public static void w(String msg, Throwable thrown, boolean uiLogging) { msg += "\n" + stackTraceAsString(thrown); LogRecord record = new LogRecord(Level.WARNING, msg); record.setThrown(thrown); log(record, uiLogging); } /** * Logs a new warning message with an optional parameter. * * @param msg the message to log. * @param param the optional parameter. * @param uiLogging true to log to the UI as well. */ public static void w(String msg, Object param, boolean uiLogging) { LogRecord record = new LogRecord(Level.WARNING, msg); record.setParameters(new Object[]{param}); log(record, uiLogging); } /** * Logs a new warning message with optional parameters. * * @param msg the message to log. * @param uiLogging true to log to the UI as well. * @param params the optional parameters. */ public static void w(String msg, boolean uiLogging, Object... params) { LogRecord record = new LogRecord(Level.WARNING, msg); record.setParameters(params); log(record, uiLogging); } /** * Converts the stack trace of the specified {@link Throwable} to a string. * * @param thrown holds the stack trace. * @return string representation of the stack trace. */ private static String stackTraceAsString(Throwable thrown) { StringWriter errors = new StringWriter(); thrown.printStackTrace(new PrintWriter(errors)); return errors.toString(); } /** * Logs the specified {@link LogRecord} using both, the default logger and * the logger for UI output if {@code uiLogging} equals true. * * @param record the {@link LogRecord} to be logged. * @param uiLogging true to also log using the logger for UI. */ private static void log(LogRecord record, boolean uiLogging) { DEFAULT_LOGGER.log(record); if (uiLogging) { Logger.getLogger(LoggerNameUI).log(record); } } }
7,003
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
Settings.java
/FileExtraction/Java_unseen/turbolocust_GZipper/src/main/java/org/gzipper/java/util/Settings.java
/* * Copyright (C) 2018 Matthias Fussenegger * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gzipper.java.util; import org.gzipper.java.application.model.OperatingSystem; import org.gzipper.java.application.util.StringUtils; import java.io.*; import java.util.Properties; /** * Singleton that provides convenience when working with {@link Properties} and * represents the settings file that can be used globally. * * @author Matthias Fussenegger */ public final class Settings { public static final String FALSE_STRING = "false"; public static final String TRUE_STRING = "true"; /** * The actual properties file. Required to store away changed properties. */ private File _propsFile; /** * The properties read from the {@link #_propsFile}; */ private Properties _props; /** * The default properties values for restoration. */ private final Properties _defaults; /** * The operating system the JVM runs on. */ private OperatingSystem _os; private Settings() { _defaults = initDefaults(); } /** * Initializes this singleton class. This may only be called once. * * @param props the properties file to initialize this class with. * @param os the current operating system. */ public void init(File props, OperatingSystem os) { if (_props == null) { _os = os; // to receive environment variables if (props != null) { _propsFile = props; _props = new Properties(_defaults); try (final FileInputStream fis = new FileInputStream(props); final BufferedInputStream bis = new BufferedInputStream(fis)) { _props.load(bis); } catch (IOException ex) { Log.e(ex.getLocalizedMessage(), ex); } } } } /** * Initializes the default properties values. * * @return the default properties. */ private Properties initDefaults() { final Properties defaults = new Properties(); defaults.setProperty("loggingEnabled", FALSE_STRING); defaults.setProperty("recentPath", StringUtils.EMPTY); defaults.setProperty("darkThemeEnabled", FALSE_STRING); defaults.setProperty("showGzipInfoDialog", TRUE_STRING); return defaults; } /** * Sets (or overrides) the value of the property with the specified {@code key}. * * @param key the key of the property. * @param value the value of the property as {@code String}. */ public synchronized void setProperty(String key, String value) { _props.setProperty(key, value); } /** * Sets (or overrides) the value of the property with the specified {@code key}. * * @param key the key of the property. * @param value the value of the property as {@code boolean}. */ public synchronized void setProperty(String key, boolean value) { final String propertyValue = value ? TRUE_STRING : FALSE_STRING; _props.setProperty(key, propertyValue); } /** * Returns the property with the specified key if it exists. * * @param key the key of the property. * @return the value of the property as string. */ public String getProperty(String key) { return _props.getProperty(key); } /** * Evaluates and returns the property with the specified key if it exists. * * @param key the key of the property. * @return true if property equals "true", false otherwise. */ public boolean evaluateProperty(String key) { final String property = _props.getProperty(key); return property != null && property.equals(TRUE_STRING); } /** * Returns the operating system on which the JVM is running on. * * @return the operating system on which the JVM is running on. */ public OperatingSystem getOs() { return _os; } /** * Saves all stored properties to the Properties file. * * @throws IOException if an I/O error occurs. */ public void storeAway() throws IOException { _props.store(new BufferedOutputStream(new FileOutputStream(_propsFile)), ""); } /** * Restores the default properties. */ public void restoreDefaults() { _props.clear(); _props.putAll(_defaults); } /** * Returns the singleton instance of this class. * * @return the singleton instance of this class. */ public static Settings getInstance() { return SettingsHolder.INSTANCE; } /** * Holder class for singleton instance. */ private static class SettingsHolder { private static final Settings INSTANCE = new Settings(); } }
5,689
Java
.java
turbolocust/GZipper
10
3
0
2015-09-20T13:13:16Z
2024-03-31T12:21:03Z
ILogger.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/logging/src/main/java/com/tyron/builder/log/ILogger.java
package com.tyron.builder.log; import com.tyron.builder.model.DiagnosticWrapper; import javax.tools.Diagnostic; public interface ILogger { ILogger STD_OUT = new ILogger() { @Override public void info(DiagnosticWrapper wrapper) { System.out.println("[INFO] " + wrapper.toString()); } @Override public void debug(DiagnosticWrapper wrapper) { System.out.println("[DEBUG] " + wrapper.toString()); } @Override public void warning(DiagnosticWrapper wrapper) { System.out.println("[WARNING] " + wrapper.toString()); } @Override public void error(DiagnosticWrapper wrapper) { System.out.println("[ERROR] " + wrapper.toString()); } }; ILogger EMPTY = new ILogger() { @Override public void info(DiagnosticWrapper wrapper) {} @Override public void debug(DiagnosticWrapper wrapper) {} @Override public void warning(DiagnosticWrapper wrapper) {} @Override public void error(DiagnosticWrapper wrapper) {} }; static ILogger wrap(LogViewModel logViewModel) { return new ILogger() { @Override public void info(DiagnosticWrapper wrapper) { logViewModel.d(LogViewModel.BUILD_LOG, wrapper); } @Override public void debug(DiagnosticWrapper wrapper) { logViewModel.d(LogViewModel.BUILD_LOG, wrapper); } @Override public void warning(DiagnosticWrapper wrapper) { logViewModel.w(LogViewModel.BUILD_LOG, wrapper); } @Override public void error(DiagnosticWrapper wrapper) { logViewModel.e(LogViewModel.BUILD_LOG, wrapper); } }; } void info(DiagnosticWrapper wrapper); void debug(DiagnosticWrapper wrapper); void warning(DiagnosticWrapper wrapper); void error(DiagnosticWrapper wrapper); default void info(String message) { debug(wrap(message)); } default void debug(String message) { debug(wrap(message)); } default void warning(String message) { DiagnosticWrapper wrapped = wrap(message); wrapped.setKind(Diagnostic.Kind.WARNING); warning(wrapped); } default void error(String message) { DiagnosticWrapper wrapped = wrap(message); wrapped.setKind(Diagnostic.Kind.ERROR); error(wrapped); } default void verbose(String message) {} static DiagnosticWrapper wrap(String message) { DiagnosticWrapper wrapper = new DiagnosticWrapper(); wrapper.setMessage(message); return wrapper; } }
2,596
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
LogViewModel.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/logging/src/main/java/com/tyron/builder/log/LogViewModel.java
package com.tyron.builder.log; import android.os.Handler; import android.os.Looper; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; import com.tyron.builder.model.DiagnosticWrapper; import java.util.ArrayList; import java.util.List; import javax.tools.Diagnostic; public class LogViewModel extends ViewModel { private static int totalCount; public static final int APP_LOG = totalCount++; public static final int BUILD_LOG = totalCount++; public static final int DEBUG = totalCount++; public static final int IDE = totalCount++; private final Handler mainHandler = new Handler(Looper.getMainLooper()); private List<MutableLiveData<List<DiagnosticWrapper>>> log; public LiveData<List<DiagnosticWrapper>> getLogs(int id) { if (log == null) { log = init(); } return log.get(id); } public void updateLogs(int id, List<DiagnosticWrapper> diagnostics) { if (log == null) { log = init(); } MutableLiveData<List<DiagnosticWrapper>> logData = this.log.get(id); if (logData != null && diagnostics != null) { logData.setValue(diagnostics); } } private List<MutableLiveData<List<DiagnosticWrapper>>> init() { List<MutableLiveData<List<DiagnosticWrapper>>> list = new ArrayList<>(); for (int i = 0; i < totalCount; i++) { list.add(new MutableLiveData<>(new ArrayList<>())); } return list; } public void clear(int id) { MutableLiveData<List<DiagnosticWrapper>> data = (MutableLiveData<List<DiagnosticWrapper>>) getLogs(id); if (data != null) { data.setValue(new ArrayList<>()); } } public void e(int id, DiagnosticWrapper diagnostic) { add(id, diagnostic); } public void d(int id, String message) { d(id, wrap(message, Diagnostic.Kind.OTHER)); } public void d(int id, DiagnosticWrapper diagnosticWrapper) { add(id, diagnosticWrapper); } public void w(int id, DiagnosticWrapper diagnosticWrapper) { add(id, diagnosticWrapper); } public void w(int id, String message) { add(id, wrap(message, Diagnostic.Kind.WARNING)); } public void e(int id, String message) { add(id, wrap(message, Diagnostic.Kind.ERROR)); } private DiagnosticWrapper wrap(String message, Diagnostic.Kind kind) { DiagnosticWrapper wrapper = new DiagnosticWrapper(); wrapper.setMessage(message); wrapper.setKind(kind); return wrapper; } /** * Convenience method to add a diagnostic to a ViewModel * * @param id the log id to set to * @param diagnosticWrapper the DiagnosticWrapper to add */ private void add(int id, DiagnosticWrapper diagnosticWrapper) { List<DiagnosticWrapper> list = getLogs(id).getValue(); if (list == null) { list = new ArrayList<>(); } if (diagnosticWrapper != null) { list.add(diagnosticWrapper); } maybePost(id, list); } /** * Checks if the current thread is the main thread and does not post it if so * * @param id log id to set the value to * @param current Value to set to the ViewModel */ private void maybePost(int id, List<DiagnosticWrapper> current) { if (Thread.currentThread() != Looper.getMainLooper().getThread()) { // Using postValue will ignore all values except the last one, we don't want that if (current != null) { mainHandler.post(() -> log.get(id).setValue(current)); } } else { if (current != null) { log.get(id).setValue(current); } } } }
3,555
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
DiagnosticWrapper.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/logging/src/main/java/com/tyron/builder/model/DiagnosticWrapper.java
package com.tyron.builder.model; import android.view.View; import java.io.File; import java.util.Locale; import java.util.Objects; import javax.tools.Diagnostic; import javax.tools.JavaFileObject; public class DiagnosticWrapper implements Diagnostic<File> { public static final int USE_LINE_POS = -31; private String code; private File source; private Kind kind; private long position; private long startPosition; private long endPosition; private long lineNumber; private long columnNumber; private View.OnClickListener onClickListener; private String message; /** Extra information for this diagnostic */ private Object mExtra; private int startLine; private int endLine; private int startColumn; private int endColumn; public DiagnosticWrapper() {} public DiagnosticWrapper(Diagnostic<? extends JavaFileObject> obj) { try { this.code = obj.getCode(); if (obj.getSource() != null) { this.source = new File(obj.getSource().toUri()); } this.kind = obj.getKind(); this.position = obj.getPosition(); this.startPosition = obj.getStartPosition(); this.endPosition = obj.getEndPosition(); this.lineNumber = obj.getLineNumber(); this.columnNumber = obj.getColumnNumber(); this.message = obj.getMessage(Locale.getDefault()); this.mExtra = obj; } catch (Throwable e) { // ignored } } public void setOnClickListener(View.OnClickListener listener) { onClickListener = listener; } public View.OnClickListener getOnClickListener() { return onClickListener; } @Override public Kind getKind() { return kind; } @Override public File getSource() { return source; } @Override public long getPosition() { return position; } @Override public long getStartPosition() { return startPosition; } @Override public long getEndPosition() { return endPosition; } @Override public long getLineNumber() { return lineNumber; } @Override public long getColumnNumber() { return columnNumber; } @Override public String getCode() { return code; } @Override public String getMessage(Locale locale) { return message; } public void setCode(String code) { this.code = code; } public void setSource(File source) { this.source = source; } public void setKind(Kind kind) { this.kind = kind; } public void setPosition(long position) { this.position = position; } public void setStartPosition(long startPosition) { this.startPosition = startPosition; } public void setEndPosition(long endPosition) { this.endPosition = endPosition; } public void setMessage(String message) { this.message = message; } public void setLineNumber(long lineNumber) { this.lineNumber = lineNumber; } public void setColumnNumber(long columnNumber) { this.columnNumber = columnNumber; } public Object getExtra() { return mExtra; } public void setExtra(Object mExtra) { this.mExtra = mExtra; } @Override public String toString() { return "startOffset: " + startPosition + "\n" + "endOffset: " + endPosition + "\n" + "position: " + position + "\n" + "startLine: " + startLine + "\n" + "startColumn: " + startColumn + "\n" + "endLine: " + endLine + "\n" + "endColumn: " + endColumn + "\n" + "message: " + message; } @Override public int hashCode() { return Objects.hash( code, source, kind, position, startPosition, endPosition, lineNumber, columnNumber, message, mExtra); } @Override public boolean equals(Object obj) { if (obj instanceof DiagnosticWrapper) { DiagnosticWrapper that = (DiagnosticWrapper) obj; if (that.message != null && this.message == null) { return false; } if (that.message == null && this.message != null) { return false; } if (!Objects.equals(that.message, this.message)) { return false; } if (!Objects.equals(that.source, this.source)) { return false; } if (that.lineNumber != this.lineNumber) { return false; } return that.columnNumber == this.columnNumber; } return super.equals(obj); } public void setStartLine(int line) { this.startLine = line; } public int getStartLine() { return startLine; } public int getEndLine() { return endLine; } public void setEndLine(int endLine) { this.endLine = endLine; } public int getStartColumn() { return startColumn; } public void setStartColumn(int startColumn) { this.startColumn = startColumn; } public int getEndColumn() { return endColumn; } public void setEndColumn(int endColumn) { this.endColumn = endColumn; } }
5,065
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
TreeView.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/treeview/src/main/java/com/tyron/ui/treeview/TreeView.java
/* * Copyright 2016 - 2017 ShineM (Xinyuan) * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF * ANY KIND, either express or implied. See the License for the specific language governing * permissions and limitations under. */ package com.tyron.ui.treeview; import android.annotation.SuppressLint; import android.content.Context; import android.view.View; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.SimpleItemAnimator; import com.tyron.ui.treeview.base.BaseNodeViewFactory; import com.tyron.ui.treeview.base.SelectableTreeAction; import com.tyron.ui.treeview.helper.TreeHelper; import java.util.List; import java.util.Objects; /** Created by xinyuanzhong on 2017/4/20. */ public class TreeView<D> implements SelectableTreeAction<D> { public interface OnTreeNodeClickListener<D> { void onTreeNodeClicked(TreeNode<D> treeNode, boolean expand); } private final Context context; private TreeNode<D> root; private RecyclerView rootView; private TreeViewAdapter<D> adapter; private BaseNodeViewFactory<D> baseNodeViewFactory; private boolean itemSelectable = true; public TreeView(@NonNull Context context, @NonNull TreeNode<D> root) { this.context = context; this.root = root; } public View getView() { if (rootView == null) { this.rootView = buildRootView(); } return rootView; } @Nullable public TreeNode<D> getRoot() { List<TreeNode<D>> allNodes = getAllNodes(); if (allNodes.isEmpty()) { return null; } return allNodes.get(0); } @NonNull private RecyclerView buildRootView() { RecyclerView recyclerView = new RecyclerView(context); recyclerView.setMotionEventSplittingEnabled( false); // disable multi touch event to prevent terrible data set error when calculate list. ((SimpleItemAnimator) Objects.requireNonNull(recyclerView.getItemAnimator())) .setSupportsChangeAnimations(false); recyclerView.setLayoutManager(new LinearLayoutManager(context)); return recyclerView; } public void setAdapter(@NonNull BaseNodeViewFactory<D> baseNodeViewFactory) { this.baseNodeViewFactory = baseNodeViewFactory; adapter = new TreeViewAdapter<>(context, root, baseNodeViewFactory); adapter.setTreeView(this); rootView.setAdapter(adapter); } @Override public void expandAll() { TreeHelper.expandAll(root); refreshTreeView(); } public void refreshTreeView() { if (rootView != null) { ((TreeViewAdapter<?>) rootView.getAdapter()).refreshView(); } } public void refreshTreeView(@NonNull TreeNode<D> root) { this.root = root; setAdapter(baseNodeViewFactory); } @SuppressLint("NotifyDataSetChanged") public void updateTreeView() { if (rootView != null) { rootView.getAdapter().notifyDataSetChanged(); } } @Override public void expandNode(TreeNode<D> treeNode) { adapter.expandNode(treeNode); } @Override public void expandLevel(int level) { TreeHelper.expandLevel(root, level); refreshTreeView(); } @Override public void collapseAll() { TreeHelper.collapseAll(root); refreshTreeView(); } @Override public void collapseNode(TreeNode<D> treeNode) { adapter.collapseNode(treeNode); } @Override public void collapseLevel(int level) { TreeHelper.collapseLevel(root, level); refreshTreeView(); } @Override public void toggleNode(TreeNode<D> treeNode) { if (treeNode.isExpanded()) { collapseNode(treeNode); } else { expandNode(treeNode); } } @Override public void deleteNode(TreeNode<D> node) { adapter.deleteNode(node); } @Override public void addNode(TreeNode<D> parent, TreeNode<D> treeNode) { parent.addChild(treeNode); refreshTreeView(); } @Override public List<TreeNode<D>> getAllNodes() { return TreeHelper.getAllNodes(root); } @Override public void selectNode(TreeNode<D> treeNode) { if (treeNode != null) { adapter.selectNode(true, treeNode); } } @Override public void deselectNode(TreeNode<D> treeNode) { if (treeNode != null) { adapter.selectNode(false, treeNode); } } @Override public void selectAll() { TreeHelper.selectNodeAndChild(root, true); refreshTreeView(); } @Override public void deselectAll() { TreeHelper.selectNodeAndChild(root, false); refreshTreeView(); } @Override public List<TreeNode<D>> getSelectedNodes() { return TreeHelper.getSelectedNodes(root); } public boolean isItemSelectable() { return itemSelectable; } public void setItemSelectable(boolean itemSelectable) { this.itemSelectable = itemSelectable; } }
5,218
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
TreeViewAdapter.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/treeview/src/main/java/com/tyron/ui/treeview/TreeViewAdapter.java
/* * Copyright 2016 - 2017 ShineM (Xinyuan) * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF * ANY KIND, either express or implied. See the License for the specific language governing * permissions and limitations under. */ package com.tyron.ui.treeview; import android.annotation.SuppressLint; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Checkable; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.tyron.ui.treeview.base.BaseNodeViewBinder; import com.tyron.ui.treeview.base.BaseNodeViewFactory; import com.tyron.ui.treeview.base.CheckableNodeViewBinder; import com.tyron.ui.treeview.helper.TreeHelper; import java.util.ArrayList; import java.util.List; /** Created by xinyuanzhong on 2017/4/21. */ public class TreeViewAdapter<D> extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private final Context context; private final TreeNode<D> root; private final List<TreeNode<D>> expandedNodeList; private final BaseNodeViewFactory<D> baseNodeViewFactory; private TreeView<D> treeView; TreeViewAdapter( Context context, TreeNode<D> root, @NonNull BaseNodeViewFactory<D> baseNodeViewFactory) { this.context = context; this.root = root; this.baseNodeViewFactory = baseNodeViewFactory; this.expandedNodeList = new ArrayList<>(); buildExpandedNodeList(); } private void buildExpandedNodeList() { expandedNodeList.clear(); for (TreeNode<D> child : root.getChildren()) { insertNode(expandedNodeList, child); } } private void insertNode(List<TreeNode<D>> nodeList, TreeNode<D> treeNode) { nodeList.add(treeNode); if (!treeNode.hasChild()) { return; } if (treeNode.isExpanded()) { for (TreeNode<D> child : treeNode.getChildren()) { insertNode(nodeList, child); } } } @Override public int getItemViewType(int position) { // return expandedNodeList.get(position).getLevel(); // this old code row used to always return // the level TreeNode<D> treeNode = expandedNodeList.get(position); return this.baseNodeViewFactory.getViewType(treeNode); } @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int level) { View view = LayoutInflater.from(context) .inflate(baseNodeViewFactory.getNodeLayoutId(level), parent, false); BaseNodeViewBinder<D> nodeViewBinder = baseNodeViewFactory.getNodeViewBinder(view, level); nodeViewBinder.setTreeView(treeView); return nodeViewBinder; } @Override public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder holder, final int position) { final View nodeView = holder.itemView; final TreeNode<D> treeNode = expandedNodeList.get(position); final BaseNodeViewBinder<D> viewBinder = (BaseNodeViewBinder<D>) holder; if (viewBinder.getToggleTriggerViewId() != 0) { View triggerToggleView = nodeView.findViewById(viewBinder.getToggleTriggerViewId()); if (triggerToggleView != null) { triggerToggleView.setOnClickListener( v -> { onNodeToggled(treeNode); viewBinder.onNodeToggled(treeNode, treeNode.isExpanded()); }); triggerToggleView.setOnLongClickListener( view -> { return viewBinder.onNodeLongClicked(view, treeNode, treeNode.isExpanded()); }); } } else if (treeNode.isItemClickEnable()) { nodeView.setOnClickListener( v -> { onNodeToggled(treeNode); viewBinder.onNodeToggled(treeNode, treeNode.isExpanded()); }); nodeView.setOnLongClickListener( view -> { return viewBinder.onNodeLongClicked(view, treeNode, treeNode.isExpanded()); }); } if (viewBinder instanceof CheckableNodeViewBinder) { setupCheckableItem(nodeView, treeNode, (CheckableNodeViewBinder<D>) viewBinder); } viewBinder.bindView(treeNode); } private void setupCheckableItem( View nodeView, final TreeNode<D> treeNode, final CheckableNodeViewBinder<D> viewBinder) { final View view = nodeView.findViewById(viewBinder.getCheckableViewId()); if (view instanceof Checkable) { final Checkable checkableView = (Checkable) view; checkableView.setChecked(treeNode.isSelected()); view.setOnClickListener( v -> { boolean checked = checkableView.isChecked(); selectNode(checked, treeNode); viewBinder.onNodeSelectedChanged(treeNode, checked); }); } else { throw new ClassCastException("The getCheckableViewId() " + "must return a CheckBox's id"); } } void selectNode(boolean checked, TreeNode<D> treeNode) { treeNode.setSelected(checked); selectChildren(treeNode, checked); selectParentIfNeed(treeNode, checked); } private void selectChildren(TreeNode<D> treeNode, boolean checked) { List<TreeNode<D>> impactedChildren = TreeHelper.selectNodeAndChild(treeNode, checked); int index = expandedNodeList.indexOf(treeNode); if (index != -1 && impactedChildren.size() > 0) { notifyItemRangeChanged(index, impactedChildren.size() + 1); } } private void selectParentIfNeed(TreeNode<D> treeNode, boolean checked) { List<TreeNode<D>> impactedParents = TreeHelper.selectParentIfNeedWhenNodeSelected(treeNode, checked); if (impactedParents.size() > 0) { for (TreeNode<D> parent : impactedParents) { int position = expandedNodeList.indexOf(parent); if (position != -1) notifyItemChanged(position); } } } public void onNodeToggled(TreeNode<D> treeNode) { treeNode.setExpanded(!treeNode.isExpanded()); if (treeNode.isExpanded()) { expandNode(treeNode); // expand folders recursively if (!treeNode.isLeaf() && treeNode.getChildren().size() == 1) { TreeNode<D> subNode = treeNode.getChildren().get(0); if (!subNode.isLeaf() && !subNode.isExpanded()) { onNodeToggled(subNode); } } } else { collapseNode(treeNode); } } @Override public int getItemCount() { return expandedNodeList == null ? 0 : expandedNodeList.size(); } /** * Refresh all,this operation is only used for refreshing list when a large of nodes have changed * value or structure because it take much calculation. */ @SuppressLint("NotifyDataSetChanged") void refreshView() { buildExpandedNodeList(); notifyDataSetChanged(); } // Insert a node list after index. private void insertNodesAtIndex(int index, List<TreeNode<D>> additionNodes) { if (index < 0 || index > expandedNodeList.size() - 1 || additionNodes == null) { return; } expandedNodeList.addAll(index + 1, additionNodes); notifyItemRangeInserted(index + 1, additionNodes.size()); } // Remove a node list after index. private void removeNodesAtIndex(int index, List<TreeNode<D>> removedNodes) { if (index < 0 || index > expandedNodeList.size() - 1 || removedNodes == null) { return; } expandedNodeList.removeAll(removedNodes); notifyItemRangeRemoved(index + 1, removedNodes.size()); } /** Expand node. This operation will keep the structure of children(not expand children) */ void expandNode(TreeNode<D> treeNode) { if (treeNode == null) { return; } List<TreeNode<D>> additionNodes = TreeHelper.expandNode(treeNode, false); int index = expandedNodeList.indexOf(treeNode); insertNodesAtIndex(index, additionNodes); } /** Collapse node. This operation will keep the structure of children(not collapse children) */ void collapseNode(TreeNode<D> treeNode) { if (treeNode == null) { return; } List<TreeNode<D>> removedNodes = TreeHelper.collapseNode(treeNode, false); int index = expandedNodeList.indexOf(treeNode); removeNodesAtIndex(index, removedNodes); } /** Delete a node from list.This operation will also delete its children. */ void deleteNode(TreeNode<D> node) { if (node == null || node.getParent() == null) { return; } List<TreeNode<D>> allNodes = TreeHelper.getAllNodes(root); if (allNodes.contains(node)) { node.getParent().removeChild(node); } // remove children form list before delete collapseNode(node); int index = expandedNodeList.indexOf(node); if (index != -1) { expandedNodeList.remove(node); } notifyItemRemoved(index); } void setTreeView(TreeView<D> treeView) { this.treeView = treeView; } }
9,061
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
TreeNode.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/treeview/src/main/java/com/tyron/ui/treeview/TreeNode.java
/* * Copyright 2016 - 2017 ShineM (Xinyuan) * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF * ANY KIND, either express or implied. See the License for the specific language governing * permissions and limitations under. */ package com.tyron.ui.treeview; import com.tyron.ui.treeview.helper.TreeHelper; import java.util.ArrayList; import java.util.List; /** Created by xinyuanzhong on 2017/4/20. */ public class TreeNode<D> { private int level; private D value; private TreeNode<D> parent; private List<TreeNode<D>> children; private int index; private boolean expanded; private boolean selected; private boolean itemClickEnable = true; public TreeNode(D value, int level) { this.value = value; this.children = new ArrayList<>(); setLevel(level); } public static <D> TreeNode<D> root() { return new TreeNode<>(null, 0); } public static <D> TreeNode<D> root(List<TreeNode<D>> children) { TreeNode<D> root = root(); root.setChildren(children); return root; } public void addChild(TreeNode<D> treeNode) { if (treeNode == null) { return; } children.add(treeNode); treeNode.setIndex(getChildren().size()); treeNode.setParent(this); } public void removeChild(TreeNode<D> treeNode) { if (treeNode == null || getChildren().size() < 1) { return; } getChildren().remove(treeNode); } public boolean isLeaf() { return children.size() == 0; } public boolean isLastChild() { if (parent == null) { return false; } List<TreeNode<D>> children = parent.getChildren(); return children.size() > 0 && children.indexOf(this) == children.size() - 1; } public boolean isRoot() { return parent == null; } public int getLevel() { return level; } public void setLevel(int level) { this.level = level; } public D getContent() { return value; } public D getValue() { return value; } public void setValue(D value) { this.value = value; } public TreeNode<D> getParent() { return parent; } public void setParent(TreeNode<D> parent) { this.parent = parent; } public List<TreeNode<D>> getChildren() { if (children == null) { return new ArrayList<>(); } return children; } public List<TreeNode<D>> getSelectedChildren() { List<TreeNode<D>> selectedChildren = new ArrayList<>(); for (TreeNode<D> child : getChildren()) { if (child.isSelected()) { selectedChildren.add(child); } } return selectedChildren; } public void setChildren(List<TreeNode<D>> children) { if (children == null) { return; } this.children = new ArrayList<>(); for (TreeNode<D> child : children) { addChild(child); } } /** Updating the list of children while maintaining the tree structure */ public void updateChildren(List<TreeNode<D>> children) { List<Boolean> expands = new ArrayList<>(); List<TreeNode<D>> allNodesPre = TreeHelper.getAllNodes(this); for (TreeNode<D> node : allNodesPre) { expands.add(node.isExpanded()); } this.children = children; List<TreeNode<D>> allNodes = TreeHelper.getAllNodes(this); if (allNodes.size() == expands.size()) { for (int i = 0; i < allNodes.size(); i++) { allNodes.get(i).setExpanded(expands.get(i)); } } } public void setExpanded(boolean expanded) { this.expanded = expanded; } public boolean isExpanded() { return expanded; } public boolean hasChild() { return children.size() > 0; } public boolean isItemClickEnable() { return itemClickEnable; } public void setItemClickEnable(boolean itemClickEnable) { this.itemClickEnable = itemClickEnable; } public String getId() { return getLevel() + "," + getIndex(); } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } public boolean isSelected() { return selected; } public void setSelected(boolean selected) { this.selected = selected; } }
4,456
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
TreeHelper.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/treeview/src/main/java/com/tyron/ui/treeview/helper/TreeHelper.java
/* * Copyright 2016 - 2017 ShineM (Xinyuan) * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF * ANY KIND, either express or implied. See the License for the specific language governing * permissions and limitations under. */ package com.tyron.ui.treeview.helper; import com.tyron.ui.treeview.TreeNode; import java.util.ArrayList; import java.util.List; /** Created by xinyuanzhong on 2017/4/27. */ public class TreeHelper { public static <D> void expandAll(TreeNode<D> node) { if (node == null) { return; } expandNode(node, true); } /** * Expand node and calculate the visible addition nodes. * * @param treeNode target node to expand * @param includeChild should expand child * @return the visible addition nodes */ public static <D> List<TreeNode<D>> expandNode(TreeNode<D> treeNode, boolean includeChild) { List<TreeNode<D>> expandChildren = new ArrayList<>(); if (treeNode == null) { return expandChildren; } treeNode.setExpanded(true); if (!treeNode.hasChild()) { return expandChildren; } for (TreeNode<D> child : treeNode.getChildren()) { expandChildren.add(child); if (includeChild || child.isExpanded()) { expandChildren.addAll(expandNode(child, includeChild)); } } return expandChildren; } /** * Expand the same deep(level) nodes. * * @param root the tree root * @param level the level to expand */ public static <D> void expandLevel(TreeNode<D> root, int level) { if (root == null) { return; } for (TreeNode<D> child : root.getChildren()) { if (child.getLevel() == level) { expandNode(child, false); } else { expandLevel(child, level); } } } public static <D> void collapseAll(TreeNode<D> node) { if (node == null) { return; } for (TreeNode<D> child : node.getChildren()) { performCollapseNode(child, true); } } /** * Collapse node and calculate the visible removed nodes. * * @param node target node to collapse * @param includeChild should collapse child * @return the visible addition nodes before remove */ public static <D> List<TreeNode<D>> collapseNode(TreeNode<D> node, boolean includeChild) { List<TreeNode<D>> treeNodes = performCollapseNode(node, includeChild); node.setExpanded(false); return treeNodes; } private static <D> List<TreeNode<D>> performCollapseNode(TreeNode<D> node, boolean includeChild) { List<TreeNode<D>> collapseChildren = new ArrayList<>(); if (node == null) { return collapseChildren; } if (includeChild) { node.setExpanded(false); } for (TreeNode<D> child : node.getChildren()) { collapseChildren.add(child); if (child.isExpanded()) { collapseChildren.addAll(performCollapseNode(child, includeChild)); } else if (includeChild) { performCollapseNodeInner(child); } } return collapseChildren; } /** * Collapse all children node recursive * * @param node target node to collapse */ private static <D> void performCollapseNodeInner(TreeNode<D> node) { if (node == null) { return; } node.setExpanded(false); for (TreeNode<D> child : node.getChildren()) { performCollapseNodeInner(child); } } public static <D> void collapseLevel(TreeNode<D> root, int level) { if (root == null) { return; } for (TreeNode<D> child : root.getChildren()) { if (child.getLevel() == level) { collapseNode(child, false); } else { collapseLevel(child, level); } } } public static <D> List<TreeNode<D>> getAllNodes(TreeNode<D> root) { List<TreeNode<D>> allNodes = new ArrayList<>(); fillNodeList(allNodes, root); allNodes.remove(root); return allNodes; } private static <D> void fillNodeList(List<TreeNode<D>> treeNodes, TreeNode<D> treeNode) { treeNodes.add(treeNode); if (treeNode.hasChild()) { for (TreeNode<D> child : treeNode.getChildren()) { fillNodeList(treeNodes, child); } } } /** Select the node and node's children,return the visible nodes */ public static <D> List<TreeNode<D>> selectNodeAndChild(TreeNode<D> treeNode, boolean select) { List<TreeNode<D>> expandChildren = new ArrayList<>(); if (treeNode == null) { return expandChildren; } treeNode.setSelected(select); if (!treeNode.hasChild()) { return expandChildren; } if (treeNode.isExpanded()) { for (TreeNode<D> child : treeNode.getChildren()) { expandChildren.add(child); if (child.isExpanded()) { expandChildren.addAll(selectNodeAndChild(child, select)); } else { selectNodeInner(child, select); } } } else { selectNodeInner(treeNode, select); } return expandChildren; } private static <D> void selectNodeInner(TreeNode<D> treeNode, boolean select) { if (treeNode == null) { return; } treeNode.setSelected(select); if (treeNode.hasChild()) { for (TreeNode<D> child : treeNode.getChildren()) { selectNodeInner(child, select); } } } /** * Select parent when all the brothers have been selected, otherwise deselect parent, and check * the grand parent recursive. */ public static <D> List<TreeNode<D>> selectParentIfNeedWhenNodeSelected( TreeNode<D> treeNode, boolean select) { List<TreeNode<D>> impactedParents = new ArrayList<>(); if (treeNode == null) { return impactedParents; } // ensure that the node's level is bigger than 1(first level is 1) TreeNode<D> parent = treeNode.getParent(); if (parent == null || parent.getParent() == null) { return impactedParents; } List<TreeNode<D>> brothers = parent.getChildren(); int selectedBrotherCount = 0; for (TreeNode<D> brother : brothers) { if (brother.isSelected()) selectedBrotherCount++; } if (select && selectedBrotherCount == brothers.size()) { parent.setSelected(true); impactedParents.add(parent); impactedParents.addAll(selectParentIfNeedWhenNodeSelected(parent, true)); } else if (!select && selectedBrotherCount == brothers.size() - 1) { // only the condition that the size of selected's brothers // is one less than total count can trigger the deselect parent.setSelected(false); impactedParents.add(parent); impactedParents.addAll(selectParentIfNeedWhenNodeSelected(parent, false)); } return impactedParents; } /** Get the selected nodes under current node, include itself */ public static <D> List<TreeNode<D>> getSelectedNodes(TreeNode<D> treeNode) { List<TreeNode<D>> selectedNodes = new ArrayList<>(); if (treeNode == null) { return selectedNodes; } if (treeNode.isSelected() && treeNode.getParent() != null) selectedNodes.add(treeNode); for (TreeNode<D> child : treeNode.getChildren()) { selectedNodes.addAll(getSelectedNodes(child)); } return selectedNodes; } /** * Return true when the node has one selected child(recurse all children) at least, otherwise * return false */ public static <D> boolean hasOneSelectedNodeAtLeast(TreeNode<D> treeNode) { if (treeNode == null || treeNode.getChildren().size() == 0) { return false; } List<TreeNode<D>> children = treeNode.getChildren(); for (TreeNode<D> child : children) { if (child.isSelected() || hasOneSelectedNodeAtLeast(child)) { return true; } } return false; } }
8,022
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
CheckableNodeViewBinder.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/treeview/src/main/java/com/tyron/ui/treeview/base/CheckableNodeViewBinder.java
/* * Copyright 2016 - 2017 ShineM (Xinyuan) * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF * ANY KIND, either express or implied. See the License for the specific language governing * permissions and limitations under. */ package com.tyron.ui.treeview.base; import android.view.View; import com.tyron.ui.treeview.TreeNode; /** Created by xinyuanzhong on 2017/4/27. */ public abstract class CheckableNodeViewBinder<D> extends BaseNodeViewBinder<D> { public CheckableNodeViewBinder(View itemView) { super(itemView); } /** * Get the checkable view id. MUST BE A Checkable type! * * @return */ public abstract int getCheckableViewId(); /** * Do something when a node select or deselect(only triggered by clicked) * * @param treeNode * @param selected */ public void onNodeSelectedChanged(TreeNode<D> treeNode, boolean selected) { /*empty*/ } }
1,264
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
BaseTreeAction.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/treeview/src/main/java/com/tyron/ui/treeview/base/BaseTreeAction.java
/* * Copyright 2016 - 2017 ShineM (Xinyuan) * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF * ANY KIND, either express or implied. See the License for the specific language governing * permissions and limitations under. */ package com.tyron.ui.treeview.base; import com.tyron.ui.treeview.TreeNode; import java.util.List; /** Created by xinyuanzhong on 2017/4/20. */ public interface BaseTreeAction<D> { void expandAll(); void expandNode(TreeNode<D> treeNode); void expandLevel(int level); void collapseAll(); void collapseNode(TreeNode<D> treeNode); void collapseLevel(int level); void toggleNode(TreeNode<D> treeNode); void deleteNode(TreeNode<D> node); void addNode(TreeNode<D> parent, TreeNode<D> treeNode); List<TreeNode<D>> getAllNodes(); // 1.add node at position // 2.add slide delete or other operations }
1,214
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
BaseNodeViewBinder.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/treeview/src/main/java/com/tyron/ui/treeview/base/BaseNodeViewBinder.java
/* * Copyright 2016 - 2017 ShineM (Xinyuan) * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF * ANY KIND, either express or implied. See the License for the specific language governing * permissions and limitations under. */ package com.tyron.ui.treeview.base; import android.view.View; import androidx.recyclerview.widget.RecyclerView; import com.tyron.ui.treeview.TreeNode; import com.tyron.ui.treeview.TreeView; /** Created by zxy on 17/4/23. */ public abstract class BaseNodeViewBinder<D> extends RecyclerView.ViewHolder { /** * This reference of TreeView make BaseNodeViewBinder has the ability to expand node or select * node. */ protected TreeView<D> treeView; public BaseNodeViewBinder(View itemView) { super(itemView); } public void setTreeView(TreeView<D> treeView) { this.treeView = treeView; } /** * Bind your data to view,you can get the data from treeNode by getValue() * * @param treeNode Node data */ public abstract void bindView(TreeNode<D> treeNode); /** * if you do not want toggle the node when click whole item view,then you can assign a view to * trigger the toggle action * * @return The assigned view id to trigger expand or collapse. */ public int getToggleTriggerViewId() { return 0; } /** * Callback when a toggle action happened (only by clicked) * * @param treeNode The toggled node * @param expand Expanded or collapsed */ public void onNodeToggled(TreeNode<D> treeNode, boolean expand) { // empty } /** Callback when a node is long clicked. */ public boolean onNodeLongClicked(View view, TreeNode<D> treeNode, boolean expanded) { return false; } }
2,054
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
SelectableTreeAction.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/treeview/src/main/java/com/tyron/ui/treeview/base/SelectableTreeAction.java
/* * Copyright 2016 - 2017 ShineM (Xinyuan) * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF * ANY KIND, either express or implied. See the License for the specific language governing * permissions and limitations under. */ package com.tyron.ui.treeview.base; import com.tyron.ui.treeview.TreeNode; import java.util.List; /** Created by xinyuanzhong on 2017/4/27. */ public interface SelectableTreeAction<D> extends BaseTreeAction<D> { void selectNode(TreeNode<D> treeNode); void deselectNode(TreeNode<D> treeNode); void selectAll(); void deselectAll(); List<TreeNode<D>> getSelectedNodes(); }
972
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
BaseNodeViewFactory.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/treeview/src/main/java/com/tyron/ui/treeview/base/BaseNodeViewFactory.java
/* * Copyright 2016 - 2017 ShineM (Xinyuan) * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF * ANY KIND, either express or implied. See the License for the specific language governing * permissions and limitations under. */ package com.tyron.ui.treeview.base; import android.view.View; import com.tyron.ui.treeview.TreeNode; /** Created by zxy on 17/4/23. */ public abstract class BaseNodeViewFactory<D> { /** * The default implementation below behaves as in previous version when * TreeViewAdapter.getItemViewType always returned the level, but you can override it if you want * some other viewType value to become the parameter to the method getNodeViewBinder. */ public int getViewType(TreeNode<D> treeNode) { return treeNode.getLevel(); } /** * If you want build a tree view,you must implement this factory method * * @param view The parameter for BaseNodeViewBinder's constructor, do not use this for other * purpose! * @param viewType The viewType value is the treeNode level in the default implementation. * @return BaseNodeViewBinder */ public abstract BaseNodeViewBinder<D> getNodeViewBinder(View view, int viewType); /** * If you want build a tree view,you must implement this factory method * * @param level Level of view, returned from {@link #getViewType} * @return node layout id */ public abstract int getNodeLayoutId(int level); }
1,784
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
JavaKeyStore.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/apksigner/src/main/java/com/android/apksig/JavaKeyStore.java
package com.android.apksig; import java.security.KeyStore; import org.bouncycastle.jce.provider.BouncyCastleProvider; /** Created by qingyu on 2023-03-23. */ public class JavaKeyStore extends KeyStore { public JavaKeyStore() { super(new JavaKeyStoreSpi(), new BouncyCastleProvider(), "JKS"); } }
306
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
SignUtils.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/apksigner/src/main/java/com/android/apksig/SignUtils.java
package com.android.apksig; import com.google.common.collect.ImmutableList; import java.io.*; import java.io.File; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Paths; import java.security.Key; import java.security.KeyFactory; import java.security.KeyStore; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.Security; import java.security.cert.Certificate; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import org.bouncycastle.jce.provider.BouncyCastleProvider; public class SignUtils { public static PrivateKey loadPkcs8EncodedPrivateKey(PKCS8EncodedKeySpec spec) throws NoSuchAlgorithmException, InvalidKeySpecException { try { return KeyFactory.getInstance("RSA").generatePrivate(spec); } catch (InvalidKeySpecException e) { // ignore } try { return KeyFactory.getInstance("EC").generatePrivate(spec); } catch (InvalidKeySpecException e) { // ignore } try { return KeyFactory.getInstance("DSA").generatePrivate(spec); } catch (InvalidKeySpecException e) { // ignore } throw new InvalidKeySpecException("Not an RSA, EC, or DSA private key"); } public static ApkSigner.SignerConfig getSignerConfig(String testKeyFile, String testCertFile) throws Exception { byte[] privateKeyBlob = Files.readAllBytes(Paths.get(testKeyFile)); InputStream pemInputStream = new FileInputStream(testCertFile); PrivateKey privateKey; try { final PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBlob); privateKey = loadPkcs8EncodedPrivateKey(keySpec); } catch (InvalidKeySpecException e) { throw new InvalidKeySpecException("Failed to load PKCS #8 encoded private key ", e); } final List<Certificate> certs = ImmutableList.copyOf( CertificateFactory.getInstance("X.509").generateCertificates(pemInputStream).stream() .map(c -> (Certificate) c) .collect(Collectors.toList())); final List<X509Certificate> x509Certs = Collections.checkedList( certs.stream().map(c -> (X509Certificate) c).collect(Collectors.toList()), X509Certificate.class); pemInputStream.close(); return new ApkSigner.SignerConfig.Builder("CERT", privateKey, x509Certs).build(); } public static ApkSigner.SignerConfig getSignerConfig( KeyStore keyStore, String keyAlias, String keyPassword) throws Exception { Key key = keyStore.getKey(keyAlias, keyPassword.toCharArray()); if (key == null) { throw new RuntimeException("No key found with alias '" + keyAlias + "' in keystore."); } if (!(key instanceof PrivateKey)) { throw new RuntimeException( "Key with alias '" + keyAlias + "' in keystore is not a private key."); } Certificate[] chain = keyStore.getCertificateChain(keyAlias); if (chain == null || chain.length == 0) { throw new RuntimeException( "No certificate chain found with alias '" + keyAlias + "' in keystore."); } X509Certificate[] certificates = Arrays.copyOf(chain, chain.length, X509Certificate[].class); return new ApkSigner.SignerConfig.Builder( keyAlias, (PrivateKey) key, ImmutableList.copyOf(certificates)) .build(); } public static KeyStore getKeyStore(File keyStoreFile, String keyStorePassword) throws Exception { Security.addProvider(new BouncyCastleProvider()); InputStream data = new FileInputStream(keyStoreFile); KeyStore keyStore = isJKS(data) ? new JavaKeyStore() : KeyStore.getInstance("PKCS12"); try (InputStream in = new FileInputStream(keyStoreFile)) { keyStore.load(in, keyStorePassword.toCharArray()); } return keyStore; } private static boolean isJKS(InputStream data) { try (final DataInputStream dis = new DataInputStream(new BufferedInputStream(data))) { return dis.readInt() == 0xfeedfeed; } catch (Exception e) { return false; } } }
4,297
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
LoadKeystoreException.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/apksigner/src/main/java/com/android/apksig/LoadKeystoreException.java
package com.android.apksig; import java.io.IOException; /** * Thrown by JKS.engineLoad() for errors that occur after determining the keystore is actually a JKS * keystore. */ @SuppressWarnings("serial") public class LoadKeystoreException extends IOException { public LoadKeystoreException(String message) { super(message); } }
341
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
JavaKeyStoreSpi.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/apksigner/src/main/java/com/android/apksig/JavaKeyStoreSpi.java
/* JKS.java -- implementation of the "JKS" key store. Copyright (C) 2003 Casey Marshall <rsdio@metastatic.org> Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. No representations are made about the suitability of this software for any purpose. It is provided "as is" without express or implied warranty. This program was derived by reverse-engineering Sun's own implementation, using only the public API that is available in the 1.4.1 JDK. Hence nothing in this program is, or is derived from, anything copyrighted by Sun Microsystems. While the "Binary Evaluation License Agreement" that the JDK is licensed under contains blanket statements that forbid reverse-engineering (among other things), it is my position that US copyright law does not and cannot forbid reverse-engineering of software to produce a compatible implementation. There are, in fact, numerous clauses in copyright law that specifically allow reverse-engineering, and therefore I believe it is outside of Sun's power to enforce restrictions on reverse-engineering of their software, and it is irresponsible for them to claim they can. */ package com.android.apksig; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.StandardCharsets; import java.security.DigestInputStream; import java.security.DigestOutputStream; import java.security.Key; import java.security.KeyFactory; import java.security.KeyStoreException; import java.security.KeyStoreSpi; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.UnrecoverableKeyException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.Vector; import javax.crypto.EncryptedPrivateKeyInfo; import javax.crypto.spec.SecretKeySpec; /** * This is an implementation of Sun's proprietary key store algorithm, called "JKS" for "Java Key * Store". This implementation was created entirely through reverse-engineering. * * <p>The format of JKS files is, from the start of the file: * * <ol> * <li>Magic bytes. This is a four-byte integer, in big-endian byte order, equal to <code> * 0xFEEDFEED</code>. * <li>The version number (probably), as a four-byte integer (all multibyte integral types are in * big-endian byte order). The current version number (in modern distributions of the JDK) is * 2. * <li>The number of entries in this keystore, as a four-byte integer. Call this value <i>n</i> * <li>Then, <i>n</i> times: * <ol> * <li>The entry type, a four-byte int. The value 1 denotes a private key entry, and 2 * denotes a trusted certificate. * <li>The entry's alias, formatted as strings such as those written by <a * href="http://java.sun.com/j2se/1.4.1/docs/api/java/io/DataOutput.html#writeUTF(java.lang.String)" * >DataOutput.writeUTF(String)</a>. * <li>An eight-byte integer, representing the entry's creation date, in milliseconds since * the epoch. * <p>Then, if the entry is a private key entry: * <ol> * <li>The size of the encoded key as a four-byte int, then that number of bytes. The * encoded key is the DER encoded bytes of the <a * href="http://java.sun.com/j2se/1.4.1/docs/api/javax/crypto/EncryptedPrivateKeyInfo.html">EncryptedPrivateKeyInfo</a> * structure (the encryption algorithm is discussed later). * <li>A four-byte integer, followed by that many encoded certificates, encoded as * described in the trusted certificates section. * </ol> * <p>Otherwise, the entry is a trusted certificate, which is encoded as the name of the * encoding algorithm (e.g. X.509), encoded the same way as alias names. Then, a * four-byte integer representing the size of the encoded certificate, then that many * bytes representing the encoded certificate (e.g. the DER bytes in the case of X.509). * </ol> * <li>Then, the signature. * </ol> * * </ol> * * </ol> * * <p>(See <a href="http://metastatic.org/source/genkey.java">this file</a> for some idea of how I * was able to figure out these algorithms) * * <p>Decrypting the key works as follows: * * <ol> * <li>The key length is the length of the ciphertext minus 40. The encrypted key, <code>ekey * </code>, is the middle bytes of the ciphertext. * <li>Take the first 20 bytes of the encrypted key as a seed value, <code>K[0]</code>. * <li>Compute <code>K[1] ... K[n]</code>, where <code>|K[i]| = 20</code>, <code> * n = ceil(|ekey| / 20)</code>, and <code>K[i] = SHA-1(UTF-16BE(password) + K[i-1])</code>. * <li><code>key = ekey ^ (K[1] + ... + K[n])</code>. * <li>The last 20 bytes are the checksum, computed as <code>H = * SHA-1(UTF-16BE(password) + key)</code>. If this value does not match the last 20 bytes of the * ciphertext, output <code>FAIL</code>. Otherwise, output <code>key</code>. * </ol> * * <p>The signature is defined as <code>SHA-1(UTF-16BE(password) + * US_ASCII("Mighty Aphrodite") + encoded_keystore)</code> (yup, Sun engineers are just that * clever). * * <p>(Above, SHA-1 denotes the secure hash algorithm, UTF-16BE the big-endian byte representation * of a UTF-16 string, and US_ASCII the ASCII byte representation of the string.) * * <p>The original source code by Casey Marshall of this class should be available in the file <a * href="http://metastatic.org/source/JKS.java">http://metastatic.org/source/JKS.java</a>. * * <p>Changes by Ken Ellinwood: * * <ul> * <li>Fixed a NullPointerException in engineLoad(). This method must return gracefully if the * keystore input stream is null. * <li>engineGetCertificateEntry() was updated to return the first cert in the chain for private * key entries. * <li>Lowercase the alias names, otherwise keytool chokes on the file created by this code. * <li>Fixed the integrity check in engineLoad(), previously the exception was never thrown * regardless of password value. * </ul> * * @author Casey Marshall (rsdio@metastatic.org) * @author Ken Ellinwood */ class JavaKeyStoreSpi extends KeyStoreSpi { /** Ah, Sun. So goddamned clever with those magic bytes. */ private static final int MAGIC = 0xFEEDFEED; private static final int PRIVATE_KEY = 1; private static final int TRUSTED_CERT = 2; private final Vector<String> aliases = new Vector<>(); private final HashMap<String, Certificate> trustedCerts = new HashMap<>(); private final HashMap<String, byte[]> privateKeys = new HashMap<>(); private final HashMap<String, Certificate[]> certChains = new HashMap<>(); private final HashMap<String, Date> dates = new HashMap<>(); @Override public Key engineGetKey(String alias, char[] password) throws NoSuchAlgorithmException, UnrecoverableKeyException { alias = alias.toLowerCase(); if (!privateKeys.containsKey(alias)) return null; byte[] key = decryptKey(privateKeys.get(alias), charsToBytes(password)); Certificate[] chain = engineGetCertificateChain(alias); if (chain.length > 0) { try { // Private and public keys MUST have the same algorithm. KeyFactory fact = KeyFactory.getInstance(chain[0].getPublicKey().getAlgorithm()); return fact.generatePrivate(new PKCS8EncodedKeySpec(key)); } catch (InvalidKeySpecException x) { throw new UnrecoverableKeyException(x.getMessage()); } } else return new SecretKeySpec(key, alias); } @Override public Certificate[] engineGetCertificateChain(String alias) { return certChains.get(alias.toLowerCase()); } @Override public Certificate engineGetCertificate(String alias) { alias = alias.toLowerCase(); if (engineIsKeyEntry(alias)) { Certificate[] certChain = certChains.get(alias); if (certChain != null && certChain.length > 0) return certChain[0]; } return trustedCerts.get(alias); } @Override public Date engineGetCreationDate(String alias) { alias = alias.toLowerCase(); return dates.get(alias); } // XXX implement writing methods. @Override public void engineSetKeyEntry(String alias, Key key, char[] passwd, Certificate[] certChain) throws KeyStoreException { alias = alias.toLowerCase(); if (trustedCerts.containsKey(alias)) throw new KeyStoreException("\"" + alias + " is a trusted certificate entry"); privateKeys.put(alias, encryptKey(key, charsToBytes(passwd))); if (certChain != null) certChains.put(alias, certChain); else certChains.put(alias, new Certificate[0]); if (!aliases.contains(alias)) { dates.put(alias, new Date()); aliases.add(alias); } } @SuppressWarnings("unused") @Override public void engineSetKeyEntry(String alias, byte[] encodedKey, Certificate[] certChain) throws KeyStoreException { alias = alias.toLowerCase(); if (trustedCerts.containsKey(alias)) throw new KeyStoreException("\"" + alias + "\" is a trusted certificate entry"); try { new EncryptedPrivateKeyInfo(encodedKey); } catch (IOException ioe) { throw new KeyStoreException("encoded key is not an EncryptedPrivateKeyInfo"); } privateKeys.put(alias, encodedKey); if (certChain != null) certChains.put(alias, certChain); else certChains.put(alias, new Certificate[0]); if (!aliases.contains(alias)) { dates.put(alias, new Date()); aliases.add(alias); } } @Override public void engineSetCertificateEntry(String alias, Certificate cert) throws KeyStoreException { alias = alias.toLowerCase(); if (privateKeys.containsKey(alias)) throw new KeyStoreException("\"" + alias + "\" is a private key entry"); if (cert == null) throw new NullPointerException(); trustedCerts.put(alias, cert); if (!aliases.contains(alias)) { dates.put(alias, new Date()); aliases.add(alias); } } @Override public void engineDeleteEntry(String alias) throws KeyStoreException { alias = alias.toLowerCase(); aliases.remove(alias); } @Override public Enumeration<String> engineAliases() { return aliases.elements(); } @Override public boolean engineContainsAlias(String alias) { alias = alias.toLowerCase(); return aliases.contains(alias); } @Override public int engineSize() { return aliases.size(); } @Override public boolean engineIsKeyEntry(String alias) { alias = alias.toLowerCase(); return privateKeys.containsKey(alias); } @Override public boolean engineIsCertificateEntry(String alias) { alias = alias.toLowerCase(); return trustedCerts.containsKey(alias); } @Override public String engineGetCertificateAlias(Certificate cert) { for (String alias : trustedCerts.keySet()) if (cert.equals(trustedCerts.get(alias))) return alias; return null; } @Override public void engineStore(OutputStream out, char[] passwd) throws IOException, NoSuchAlgorithmException, CertificateException { MessageDigest md = MessageDigest.getInstance("SHA1"); md.update(charsToBytes(passwd)); md.update("Mighty Aphrodite".getBytes(StandardCharsets.UTF_8)); DataOutputStream dout = new DataOutputStream(new DigestOutputStream(out, md)); dout.writeInt(MAGIC); dout.writeInt(2); dout.writeInt(aliases.size()); for (Enumeration<String> e = aliases.elements(); e.hasMoreElements(); ) { String alias = e.nextElement(); if (trustedCerts.containsKey(alias)) { dout.writeInt(TRUSTED_CERT); dout.writeUTF(alias); dout.writeLong(dates.get(alias).getTime()); writeCert(dout, trustedCerts.get(alias)); } else { dout.writeInt(PRIVATE_KEY); dout.writeUTF(alias); dout.writeLong(dates.get(alias).getTime()); byte[] key = privateKeys.get(alias); dout.writeInt(key.length); dout.write(key); Certificate[] chain = certChains.get(alias); dout.writeInt(chain.length); for (int i = 0; i < chain.length; i++) writeCert(dout, chain[i]); } } byte[] digest = md.digest(); dout.write(digest); } @Override public void engineLoad(InputStream in, char[] passwd) throws IOException, NoSuchAlgorithmException, CertificateException { MessageDigest md = MessageDigest.getInstance("SHA"); if (passwd != null) md.update(charsToBytes(passwd)); md.update("Mighty Aphrodite".getBytes(StandardCharsets.UTF_8)); aliases.clear(); trustedCerts.clear(); privateKeys.clear(); certChains.clear(); dates.clear(); if (in == null) return; DataInputStream din = new DataInputStream(new DigestInputStream(in, md)); if (din.readInt() != MAGIC) throw new IOException("not a JavaKeyStore"); din.readInt(); // version no. final int n = din.readInt(); aliases.ensureCapacity(n); if (n < 0) throw new LoadKeystoreException("Malformed key store"); for (int i = 0; i < n; i++) { int type = din.readInt(); String alias = din.readUTF(); aliases.add(alias); dates.put(alias, new Date(din.readLong())); switch (type) { case PRIVATE_KEY: int len = din.readInt(); byte[] encoded = new byte[len]; din.read(encoded); privateKeys.put(alias, encoded); int count = din.readInt(); Certificate[] chain = new Certificate[count]; for (int j = 0; j < count; j++) chain[j] = readCert(din); certChains.put(alias, chain); break; case TRUSTED_CERT: trustedCerts.put(alias, readCert(din)); break; default: throw new LoadKeystoreException("Malformed key store"); } } if (passwd != null) { byte[] computedHash = md.digest(); byte[] storedHash = new byte[20]; din.read(storedHash); if (!MessageDigest.isEqual(storedHash, computedHash)) { throw new LoadKeystoreException("Incorrect password, or integrity check failed."); } } } // Own methods. // ------------------------------------------------------------------------ private static Certificate readCert(DataInputStream in) throws IOException, CertificateException { String type = in.readUTF(); int len = in.readInt(); byte[] encoded = new byte[len]; in.read(encoded); CertificateFactory factory = CertificateFactory.getInstance(type); return factory.generateCertificate(new ByteArrayInputStream(encoded)); } private static void writeCert(DataOutputStream dout, Certificate cert) throws IOException, CertificateException { dout.writeUTF(cert.getType()); byte[] b = cert.getEncoded(); dout.writeInt(b.length); dout.write(b); } private static byte[] decryptKey(byte[] encryptedPKI, byte[] passwd) throws UnrecoverableKeyException { try { EncryptedPrivateKeyInfo epki = new EncryptedPrivateKeyInfo(encryptedPKI); byte[] encr = epki.getEncryptedData(); byte[] keystream = new byte[20]; System.arraycopy(encr, 0, keystream, 0, 20); byte[] check = new byte[20]; System.arraycopy(encr, encr.length - 20, check, 0, 20); byte[] key = new byte[encr.length - 40]; MessageDigest sha = MessageDigest.getInstance("SHA1"); int count = 0; while (count < key.length) { sha.reset(); sha.update(passwd); sha.update(keystream); sha.digest(keystream, 0, keystream.length); for (int i = 0; i < keystream.length && count < key.length; i++) { key[count] = (byte) (keystream[i] ^ encr[count + 20]); count++; } } sha.reset(); sha.update(passwd); sha.update(key); if (!MessageDigest.isEqual(check, sha.digest())) throw new UnrecoverableKeyException("checksum mismatch"); return key; } catch (Exception x) { throw new UnrecoverableKeyException(x.getMessage()); } } private static byte[] encryptKey(Key key, byte[] passwd) throws KeyStoreException { try { MessageDigest sha = MessageDigest.getInstance("SHA1"); // SecureRandom rand = SecureRandom.getInstance("SHA1PRNG"); byte[] k = key.getEncoded(); byte[] encrypted = new byte[k.length + 40]; byte[] keystream = SecureRandom.getSeed(20); System.arraycopy(keystream, 0, encrypted, 0, 20); int count = 0; while (count < k.length) { sha.reset(); sha.update(passwd); sha.update(keystream); sha.digest(keystream, 0, keystream.length); for (int i = 0; i < keystream.length && count < k.length; i++) { encrypted[count + 20] = (byte) (keystream[i] ^ k[count]); count++; } } sha.reset(); sha.update(passwd); sha.update(k); sha.digest(encrypted, encrypted.length - 20, 20); // 1.3.6.1.4.1.42.2.17.1.1 is Sun's private OID for this encryption algorithm. return new EncryptedPrivateKeyInfo("1.3.6.1.4.1.42.2.17.1.1", encrypted).getEncoded(); } catch (Exception x) { throw new KeyStoreException(x.getMessage()); } } private static byte[] charsToBytes(char[] passwd) { byte[] buf = new byte[passwd.length * 2]; for (int i = 0, j = 0; i < passwd.length; i++) { buf[j++] = (byte) (passwd[i] >>> 8); buf[j++] = (byte) passwd[i]; } return buf; } }
18,201
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
GradleUtils.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/common/src/main/java/com/deenu143/gradle/utils/GradleUtils.java
package com.deenu143.gradle.utils; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.io.FileUtils; public class GradleUtils { private static final Pattern PLUGINS_ID = Pattern.compile("\\s*(id)\\s*(')([a-zA-Z0-9.'/-:\\-]+)(')"); private static final Pattern PLUGINS_ID_QUOT = Pattern.compile("\\s*(id)\\s*(\")([a-zA-Z0-9.'/-:\\-]+)(\")"); private static final Pattern NAMESPLACE = Pattern.compile("\\s*(namespace)\\s*(')([a-zA-Z0-9.'/-:\\-]+)(')"); private static final Pattern NAMESPLACE_QUOT = Pattern.compile("\\s*(namespace)\\s*(\")([a-zA-Z0-9.'/-:\\-]+)(\")"); private static final Pattern APPLICATION_ID = Pattern.compile("\\s*(applicationId)\\s*(')([a-zA-Z0-9.'/-:\\-]+)(')"); private static final Pattern APPLICATION_ID_QUOT = Pattern.compile("\\s*(applicationId)\\s*(\")([a-zA-Z0-9.'/-:\\-]+)(\")"); private static final Pattern MIN_SDK = Pattern.compile("\\s*(minSdk)\\s*()([a-zA-Z0-9.'/-:\\-]+)()"); private static final Pattern TARGET_SDK = Pattern.compile("\\s*(targetSdk)\\s*()([a-zA-Z0-9.'/-:\\-]+)()"); private static final Pattern VERSION_CODE = Pattern.compile("\\s*(versionCode)\\s*()([a-zA-Z0-9.'/-:\\-]+)()"); private static final Pattern VERSION_NAME = Pattern.compile("\\s*(versionName)\\s*(')([a-zA-Z0-9.'/-:\\-]+)(')"); private static final Pattern VERSION_NAME_QUOT = Pattern.compile("\\s*(versionName)\\s*(\")([a-zA-Z0-9.'/-:\\-]+)(\")"); private static final Pattern MINIFY_ENABLED = Pattern.compile("\\s*(minifyEnabled)\\s*()([a-zA-Z0-9.'/-:\\-]+)()"); private static final Pattern SHRINK_RESOURCES = Pattern.compile("\\s*(shrinkResources)\\s*()([a-zA-Z0-9.'/-:\\-]+)()"); private static final Pattern USE_LEGACY_PACKAGING = Pattern.compile("\\s*(useLegacyPackaging)\\s*()([a-zA-Z0-9.'/-:\\-]+)()"); private static final Pattern IMPLEMENTATION_PROJECT = Pattern.compile("\\s*(implementation project)\\s*(')([a-zA-Z0-9.'/-:\\-]+)(')"); private static final Pattern IMPLEMENTATION_PROJECT_QUOT = Pattern.compile("\\s*(implementation project)\\s*(\")([a-zA-Z0-9.'/-:\\-]+)(\")"); private static final Pattern INCLUDE = Pattern.compile("\\s*(include)\\s*(')([a-zA-Z0-9.'/-:\\-]+)(')"); private static final Pattern INCLUDE_QUOT = Pattern.compile("\\s*(include)\\s*(\")([a-zA-Z0-9.'/-:\\-]+)(\")"); public static List<String> parsePlugins(File file) throws IOException { String readString = FileUtils.readFileToString(file, Charset.defaultCharset()); return parsePlugins(readString); } public static List<String> parsePlugins(String readString) throws IOException { readString = readString.replaceAll("\\s*//.*", ""); Matcher matcher = PLUGINS_ID.matcher(readString); List<String> plugins = new ArrayList<>(); while (matcher.find()) { String declaration = matcher.group(3); if (declaration != null) { plugins.add(String.valueOf(declaration)); } } matcher = PLUGINS_ID_QUOT.matcher(readString); while (matcher.find()) { String declaration = matcher.group(3); if (declaration != null) { plugins.add(String.valueOf(declaration)); } } return plugins; } public static String parseNameSpace(File file) throws IOException { String readString = FileUtils.readFileToString(file, Charset.defaultCharset()); return parseNameSpace(readString); } public static String parseNameSpace(String readString) throws IOException { readString = readString.replaceAll("\\s*//.*", ""); Matcher matcher = NAMESPLACE.matcher(readString); while (matcher.find()) { String declaration = matcher.group(3); if (declaration != null) { String namespace = String.valueOf(declaration); return namespace; } } matcher = NAMESPLACE_QUOT.matcher(readString); while (matcher.find()) { String declaration = matcher.group(3); if (declaration != null) { String namespace = String.valueOf(declaration); return namespace; } } return null; } public static String parseApplicationId(File file) throws IOException { String readString = FileUtils.readFileToString(file, Charset.defaultCharset()); return parseApplicationId(readString); } public static String parseApplicationId(String readString) throws IOException { readString = readString.replaceAll("\\s*//.*", ""); Matcher matcher = APPLICATION_ID.matcher(readString); while (matcher.find()) { String declaration = matcher.group(3); if (declaration != null) { String applicationId = String.valueOf(declaration); return applicationId; } } matcher = APPLICATION_ID_QUOT.matcher(readString); while (matcher.find()) { String declaration = matcher.group(3); if (declaration != null) { String applicationId = String.valueOf(declaration); return applicationId; } } return null; } public static String parseMinSdk(File file) throws IOException { String readString = FileUtils.readFileToString(file, Charset.defaultCharset()); return parseMinSdk(readString); } public static String parseMinSdk(String readString) throws IOException { Matcher matcher = MIN_SDK.matcher(readString); while (matcher.find()) { String declaration = matcher.group(3); if (declaration != null) { int minSdk = Integer.parseInt(String.valueOf(declaration)); return String.valueOf(minSdk); } } return null; } public static String parseTargetSdk(File file) throws IOException { String readString = FileUtils.readFileToString(file, Charset.defaultCharset()); return parseTargetSdk(readString); } public static String parseTargetSdk(String readString) throws IOException { Matcher matcher = TARGET_SDK.matcher(readString); while (matcher.find()) { String declaration = matcher.group(3); if (declaration != null) { int targetSdk = Integer.parseInt(String.valueOf(declaration)); return String.valueOf(targetSdk); } } return null; } public static String parseVersionCode(File file) throws IOException { String readString = FileUtils.readFileToString(file, Charset.defaultCharset()); return parseVersionCode(readString); } public static String parseVersionCode(String readString) throws IOException { Matcher matcher = VERSION_CODE.matcher(readString); while (matcher.find()) { String declaration = matcher.group(3); if (declaration != null) { int versionCode = Integer.parseInt(String.valueOf(declaration)); return String.valueOf(versionCode); } } return null; } public static String parseVersionName(File file) throws IOException { String readString = FileUtils.readFileToString(file, Charset.defaultCharset()); return parseVersionName(readString); } public static String parseVersionName(String readString) throws IOException { readString = readString.replaceAll("\\s*//.*", ""); Matcher matcher = VERSION_NAME.matcher(readString); while (matcher.find()) { String declaration = matcher.group(3); if (declaration != null) { String versionName = String.valueOf(declaration); return versionName; } } matcher = VERSION_NAME_QUOT.matcher(readString); while (matcher.find()) { String declaration = matcher.group(3); if (declaration != null) { String versionName = String.valueOf(declaration); return versionName; } } return null; } public static String parseMinfyEnabled(File file) throws IOException { String readString = FileUtils.readFileToString(file, Charset.defaultCharset()); return parseMinfyEnabled(readString); } public static String parseMinfyEnabled(String readString) throws IOException { Matcher matcher = MINIFY_ENABLED.matcher(readString); while (matcher.find()) { String declaration = matcher.group(3); if (declaration != null) { String minifyEnabled = String.valueOf(declaration); return minifyEnabled; } } return null; } public static String parseUseLegacyPackaging(File file) throws IOException { String readString = FileUtils.readFileToString(file, Charset.defaultCharset()); return parseUseLegacyPackaging(readString); } public static String parseUseLegacyPackaging(String readString) throws IOException { Matcher matcher = USE_LEGACY_PACKAGING.matcher(readString); while (matcher.find()) { String declaration = matcher.group(3); if (declaration != null) { String useLegacyPackaging = String.valueOf(declaration); return useLegacyPackaging; } } return null; } public static String parseShrinkResources(File file) throws IOException { String readString = FileUtils.readFileToString(file, Charset.defaultCharset()); return parseShrinkResources(readString); } public static String parseShrinkResources(String readString) throws IOException { Matcher matcher = SHRINK_RESOURCES.matcher(readString); while (matcher.find()) { String declaration = matcher.group(3); if (declaration != null) { String shrinkResources = String.valueOf(declaration); return shrinkResources; } } return null; } public static List<String> parseImplementationProject(File file) throws IOException { String readString = FileUtils.readFileToString(file, Charset.defaultCharset()); return parseImplementationProject(readString); } public static List<String> parseImplementationProject(String readString) throws IOException { readString = readString .replaceAll("\\s*//.*", "") .replace("(", "") .replace(")", "") .replace(":", "") .replace("path", ""); Matcher matcher = IMPLEMENTATION_PROJECT.matcher(readString); List<String> implementationProject = new ArrayList<>(); while (matcher.find()) { String declaration = matcher.group(3); if (declaration != null) { implementationProject.add(String.valueOf(declaration)); } } matcher = IMPLEMENTATION_PROJECT_QUOT.matcher(readString); while (matcher.find()) { String declaration = matcher.group(3); if (declaration != null) { implementationProject.add(String.valueOf(declaration)); } } return implementationProject; } public static List<String> parseInclude(File file) throws IOException { String readString = FileUtils.readFileToString(file, Charset.defaultCharset()); return parseInclude(readString); } public static List<String> parseInclude(String readString) throws IOException { readString = readString.replaceAll("\\s*//.*", "").replace(":", ""); Matcher matcher = INCLUDE.matcher(readString); List<String> include = new ArrayList<>(); while (matcher.find()) { String declaration = matcher.group(3); if (declaration != null) { include.add(String.valueOf(declaration)); } } matcher = INCLUDE_QUOT.matcher(readString); while (matcher.find()) { String declaration = matcher.group(3); if (declaration != null) { include.add(String.valueOf(declaration)); } } return include; } }
11,568
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
SharedPreferenceKeys.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/common/src/main/java/com/tyron/common/SharedPreferenceKeys.java
package com.tyron.common; public class SharedPreferenceKeys { public static final String PROJECT_SAVE_PATH = "save_path"; public static final String KEYBOARD_ENABLE_SUGGESTIONS = "keyboard_enable_suggestions"; public static final String EDITOR_WORDWRAP = "editor_wordwrap"; public static final String DELETE_WHITESPACES = "editor_delete_whitespaces"; public static final String FONT_SIZE = "font_size"; public static final String CLASSPATH = "classpath"; public static final String KOTLIN_COMPLETIONS = "kotlin_completion"; public static final String INSTALL_APK_DIRECTLY = "install_apk_directly"; public static final String JAVA_COMPLETIONS_TARGET_VERSION = "javaCompletionsTargetVersion"; public static final String JAVA_COMPLETIONS_SOURCE_VERSION = "javaCompletionsSourceVersion"; public static final String JAVA_CASE_INSENSITIVE_MATCH = "java_case_insensitive_match"; public static final String KOTLIN_HIGHLIGHTING = "kotlin_error_highlight"; public static final String JAVA_ERROR_HIGHLIGHTING = "code_editor_error_highlight"; public static final String JAVA_CODE_COMPLETION = "code_editor_completion"; public static final String SCHEME = "scheme"; public static final String THEME = "theme"; public static final String EDITOR_TAB_UNIQUE_FILE_NAME = "editor_tab_unique_file_name"; public static final String GIT_USER_NAME = "user_name"; public static final String GIT_USER_EMAIL = "user_email"; public static final String SSH_KEYS = "ssh_keys"; public static final String SSH_KEY_NAME = "ssh_key_name"; public static final String SAVED_PROJECT_ROOT_NAME = "root_name"; public static final String SAVED_PROJECT_PATH = "project_path"; }
1,687
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
ApplicationProvider.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/common/src/main/java/com/tyron/common/ApplicationProvider.java
package com.tyron.common; import android.content.Context; import androidx.annotation.NonNull; /** Utility class to retrieve the application context from anywhere. */ public class ApplicationProvider { private static Context sApplicationContext; public static void initialize(@NonNull Context context) { sApplicationContext = context.getApplicationContext(); } public static Context getApplicationContext() { if (sApplicationContext == null) { throw new IllegalStateException("initialize() has not been called yet."); } return sApplicationContext; } }
588
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
TestUtil.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/common/src/main/java/com/tyron/common/TestUtil.java
package com.tyron.common; import java.io.File; import java.io.IOException; import java.nio.file.Paths; public class TestUtil { public static boolean isWindows() { return System.getProperty("os.name", "").startsWith("Windows"); } public static boolean isDalvik() { return System.getProperty("java.vm.name", "").contains("Dalvik"); } public static File getResourcesDirectory() throws IOException { File currentDirFile = Paths.get(".").toFile(); String helper = currentDirFile.getAbsolutePath(); String currentDir = helper.substring(0, helper.length() - 1); return new File(new File(currentDir), "src/test/resources"); } }
661
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
IdeLog.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/common/src/main/java/com/tyron/common/logging/IdeLog.java
package com.tyron.common.logging; import androidx.annotation.NonNull; import java.util.logging.Logger; public class IdeLog { @NonNull public static Logger getLogger() { return Logger.getGlobal(); } @NonNull public static Logger getCurrentLogger(@NonNull Object clazz) { return getCurrentLogger(clazz.getClass()); } public static Logger getCurrentLogger(@NonNull Class<?> clazz) { Logger logger = Logger.getLogger(clazz.getName()); if (logger.getParent() != getLogger()) { logger.setParent(getLogger()); } return logger; } }
575
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
BinaryExecutor.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/common/src/main/java/com/tyron/common/util/BinaryExecutor.java
package com.tyron.common.util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.StringWriter; import java.util.List; import java.util.Scanner; public class BinaryExecutor { private static final String TAG = BinaryExecutor.class.getSimpleName(); private final ProcessBuilder mProcess = new ProcessBuilder(); private final StringWriter mWriter = new StringWriter(); public void setCommands(List<String> arrayList) { mProcess.command(arrayList); } public String execute() { try { Process process = mProcess.start(); Scanner scanner = new Scanner(process.getErrorStream()); while (scanner.hasNextLine()) { mWriter.append(scanner.nextLine()); mWriter.append(System.lineSeparator()); } process.waitFor(); } catch (Exception e) { mWriter.write(e.getMessage()); } return mWriter.toString(); } public String getLog() { return mWriter.toString(); } public ExecutionResult run() { try { Process process = mProcess.start(); Scanner scanner = new Scanner(process.getErrorStream()); while (scanner.hasNextLine()) { mWriter.append(scanner.nextLine()); mWriter.append(System.lineSeparator()); } BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); StringBuilder output = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { output.append(line).append("\n"); } reader.close(); int exitValue = process.waitFor(); return new ExecutionResult(exitValue, output.toString()); } catch (IOException | InterruptedException e) { mWriter.write(e.getMessage()); } return null; } }
1,802
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
Decompress.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/common/src/main/java/com/tyron/common/util/Decompress.java
package com.tyron.common.util; import android.content.Context; import android.util.Log; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; public class Decompress { private static final int BUFFER_SIZE = 1024 * 10; private static final String TAG = "Decompress"; public static void unzipFromAssets(Context context, String zipFile, String destination) { try { if (destination == null || destination.length() == 0) destination = context.getFilesDir().getAbsolutePath(); try (InputStream stream = context.getAssets().open(zipFile)) { unzip(stream, destination); } } catch (IOException e) { e.printStackTrace(); } } @SuppressWarnings("unused") public static void unzip(String zipFile, String location) { try (FileInputStream fin = new FileInputStream(zipFile)) { unzip(fin, location); } catch (IOException e) { e.printStackTrace(); } } public static void unzip(InputStream stream, String destination) { dirChecker(destination, ""); byte[] buffer = new byte[BUFFER_SIZE]; try { ZipInputStream zin = new ZipInputStream(stream); ZipEntry ze; while ((ze = zin.getNextEntry()) != null) { Log.v(TAG, "Unzipping " + ze.getName()); if (ze.isDirectory()) { dirChecker(destination, ze.getName()); } else { File f = new File(destination, ze.getName()); if (!f.exists()) { if (f.getParentFile() == null || !f.getParentFile().exists()) { if (!f.getParentFile().mkdirs()) { continue; } } boolean success = f.createNewFile(); if (!success) { Log.w(TAG, "Failed to create file " + f.getName()); continue; } FileOutputStream fout = new FileOutputStream(f); int count; while ((count = zin.read(buffer)) != -1) { fout.write(buffer, 0, count); } zin.closeEntry(); fout.close(); } } } zin.close(); } catch (Exception e) { Log.e(TAG, "unzip", e); } } private static void dirChecker(String destination, String dir) { File f = new File(destination, dir); if (!f.isDirectory()) { boolean success = f.mkdirs(); if (!success) { Log.w(TAG, "Failed to create folder " + f.getName()); } } } }
2,609
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
IOUtils.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/common/src/main/java/com/tyron/common/util/IOUtils.java
package com.tyron.common.util; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import org.apache.commons.io.FileUtils; public class IOUtils { public static void writeAndClose(String content, File file) { try { FileUtils.writeStringToFile(file, content, Charset.defaultCharset()); } catch (IOException e) { e.printStackTrace(); } } }
398
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
Cache.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/common/src/main/java/com/tyron/common/util/Cache.java
package com.tyron.common.util; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.FileTime; import java.time.Instant; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Set; /** * Cache maps a file + an arbitrary key to a value. When the file is modified, the mapping expires. */ public class Cache<K, V> { public static class Key<K> { public final Path file; public final K key; Key(Path file, K key) { this.file = file; this.key = key; } @Override public boolean equals(Object other) { if (other.getClass() != Cache.Key.class) return false; Cache.Key that = (Cache.Key) other; return Objects.equals(this.key, that.key) && Objects.equals(this.file, that.file); } @Override public int hashCode() { return Objects.hash(file, key); } } private class Value { final V value; final Instant created = Instant.now(); Value(V value) { this.value = value; } } private final Map<Key<K>, Value> map = new HashMap<>(); public boolean has(Path file, K k) { return !needs(file, k); } public void clear() { map.clear(); } public boolean needs(Path file, K k) { // If key is not in map, it needs to be loaded Key<K> key = new Key<>(file, k); if (!map.containsKey(key)) return true; // If key was loaded before file was last modified, it needs to be reloaded Value value = map.get(key); FileTime modified = null; try { modified = Files.getLastModifiedTime(file); } catch (IOException e) { modified = FileTime.from(Instant.now()); } // TODO remove all keys associated with file when file changes boolean before = value.created.isBefore(modified.toInstant()); return before; } @SafeVarargs public final void remove(Path file, K... keys) { for (K k : keys) { Key<K> key = new Key<>(file, k); map.remove(key); } } public Set<Key<K>> getKeys() { return map.keySet(); } public void load(Path file, K k, V v) { // TODO limit total size of cache Key<K> key = new Key<>(file, k); Value value = new Value(v); map.put(key, value); } public V get(Path file, K k) { Key<K> key = new Key<>(file, k); if (!map.containsKey(key)) { throw new IllegalArgumentException(k + " is not in map " + map); } return (V) map.get(key).value; } }
2,489
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
SingleTextWatcher.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/common/src/main/java/com/tyron/common/util/SingleTextWatcher.java
package com.tyron.common.util; import android.text.Editable; import android.text.TextWatcher; /** Utility class if you want to only override one method of {@link TextWatcher} */ public class SingleTextWatcher implements TextWatcher { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {} @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {} @Override public void afterTextChanged(Editable editable) {} }
496
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
UniqueNameBuilder.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/common/src/main/java/com/tyron/common/util/UniqueNameBuilder.java
package com.tyron.common.util; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; /** * Adopted from: <a * href="https://github.com/JetBrains/intellij-community/blob/master/platform/util/base/src/com/intellij/filename/UniqueNameBuilder.java">UniqueNameBuilder.java</a> */ public final class UniqueNameBuilder<T> { private static final String VFS_SEPARATOR = "/"; private final Map<T, String> myPaths = new HashMap<>(); private final String mySeparator; private final String myRoot; public UniqueNameBuilder(String root, String separator) { myRoot = root; mySeparator = separator; } public boolean contains(T file) { return myPaths.containsKey(file); } public int size() { return myPaths.size(); } private static final class Node { final String myText; final HashMap<String, Node> myChildren; final Node myParentNode; int myNestedChildrenCount; Node(String text, Node parentNode) { myText = text; myParentNode = parentNode; myChildren = new HashMap<>(); } Node findOrAddChild(String word) { Node node = myChildren.get(word); if (node == null) myChildren.put(word, node = new Node(word, this)); return node; } } private final Node myRootNode = new Node("", null); // Build a trie from path components starting from end // E.g. following try will be build from example // // |<-------[/fabrique] <- [/idea] // /idea/pycharm/download/index.html | // /idea/fabrique/download/index.html [RootNode] <- [/index.html] <- [/download] <- // [/pycharm] <- [/idea] // /idea/pycharm/documentation/index.html | // |<------[/documentation] <- // [/pycharm] <- [/idea] public void addPath(T key, String path) { path = trimStart(path, myRoot); myPaths.put(key, path); Node current = myRootNode; Iterator<String> pathComponentsIterator = new PathComponentsIterator(path); while (pathComponentsIterator.hasNext()) { String word = pathComponentsIterator.next(); current = current.findOrAddChild(word); } for (Node c = current; c != null; c = c.myParentNode) ++c.myNestedChildrenCount; } private static String trimStart(String s, String prefix) { if (s.startsWith(prefix)) { return s.substring(prefix.length()); } return s; } public String getShortPath(T key) { String path = myPaths.get(key); if (path == null) return key.toString(); Node current = myRootNode; Node firstNodeWithBranches = null; Node firstNodeBeforeNodeWithBranches = null; Node fileNameNode = null; Iterator<String> pathComponentsIterator = new PathComponentsIterator(path); while (pathComponentsIterator.hasNext()) { String pathComponent = pathComponentsIterator.next(); current = current.findOrAddChild(pathComponent); if (fileNameNode == null) fileNameNode = current; if (firstNodeBeforeNodeWithBranches == null && firstNodeWithBranches != null && current.myChildren.size() <= 1) { if (current.myParentNode.myNestedChildrenCount - current.myParentNode.myChildren.size() < 1) { firstNodeBeforeNodeWithBranches = current; } } if (current.myChildren.size() != 1 && firstNodeWithBranches == null) { firstNodeWithBranches = current; } } StringBuilder b = new StringBuilder(); if (firstNodeBeforeNodeWithBranches == null) { firstNodeBeforeNodeWithBranches = current; } boolean skipFirstSeparator = true; for (Node c = firstNodeBeforeNodeWithBranches; c != myRootNode; c = c.myParentNode) { if (c != fileNameNode && c != firstNodeBeforeNodeWithBranches && c.myParentNode.myChildren.size() == 1) { b.append(mySeparator); b.append("\u2026"); while (c.myParentNode != fileNameNode && c.myParentNode.myChildren.size() == 1) c = c.myParentNode; } else { if (c.myText.startsWith(VFS_SEPARATOR)) { if (!skipFirstSeparator) b.append(mySeparator); skipFirstSeparator = false; b.append(c.myText, VFS_SEPARATOR.length(), c.myText.length()); } else { b.append(c.myText); } } } return b.toString(); } public String getSeparator() { return mySeparator; } private static final class PathComponentsIterator implements Iterator<String> { private final String myPath; private int myLastPos; private int mySeparatorPos; PathComponentsIterator(String path) { myPath = path; myLastPos = path.length(); mySeparatorPos = path.lastIndexOf(VFS_SEPARATOR); } @Override public boolean hasNext() { return myLastPos != 0; } @Override public String next() { if (myLastPos == 0) throw new NoSuchElementException(); String pathComponent; if (mySeparatorPos != -1) { pathComponent = myPath.substring(mySeparatorPos, myLastPos); myLastPos = mySeparatorPos; mySeparatorPos = myPath.lastIndexOf(VFS_SEPARATOR, myLastPos - 1); } else { pathComponent = myPath.substring(0, myLastPos); if (!pathComponent.startsWith(VFS_SEPARATOR)) pathComponent = VFS_SEPARATOR + pathComponent; myLastPos = 0; } return pathComponent; } @Override public void remove() { throw new UnsupportedOperationException("remove"); } } }
5,666
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
ThreadUtil.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/common/src/main/java/com/tyron/common/util/ThreadUtil.java
package com.tyron.common.util; import android.os.Handler; import android.os.Looper; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ThreadUtil { private static final ExecutorService sExecutorService = Executors.newSingleThreadExecutor(); private static final Handler sMainHandler = new Handler(Looper.getMainLooper()); public static void runOnBackgroundThread(Runnable runnable) { sExecutorService.execute(runnable); } public static void runOnUiThread(Runnable runnable) { sMainHandler.post(runnable); } }
580
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
StringSearch.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/common/src/main/java/com/tyron/common/util/StringSearch.java
package com.tyron.common.util; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.StringReader; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.util.Arrays; import java.util.regex.Matcher; import java.util.regex.Pattern; public class StringSearch { // pattern is the string that we are searching for in the text. private final byte[] pattern; // badCharSkip[b] contains the distance between the last byte of pattern // and the rightmost occurrence of b in pattern. If b is not in pattern, // badCharSkip[b] is len(pattern). // // Whenever a mismatch is found with byte b in the text, we can safely // shift the matching frame at least badCharSkip[b] until the next time // the matching char could be in alignment. // TODO 256 is not coloring private final int[] badCharSkip = new int[256]; // goodSuffixSkip[i] defines how far we can shift the matching frame given // that the suffix pattern[i+1:] matches, but the byte pattern[i] does // not. There are two cases to consider: // // 1. The matched suffix occurs elsewhere in pattern (with a different // byte preceding it that we might possibly match). In this case, we can // shift the matching frame to align with the next suffix chunk. For // example, the pattern "mississi" has the suffix "issi" next occurring // (in right-to-left order) at index 1, so goodSuffixSkip[3] == // shift+len(suffix) == 3+4 == 7. // // 2. If the matched suffix does not occur elsewhere in pattern, then the // matching frame may share part of its prefix with the end of the // matching suffix. In this case, goodSuffixSkip[i] will contain how far // to shift the frame to align this portion of the prefix to the // suffix. For example, in the pattern "abcxxxabc", when the first // mismatch from the back is found to be in position 3, the matching // suffix "xxabc" is not found elsewhere in the pattern. However, its // rightmost "abc" (at position 6) is a prefix of the whole pattern, so // goodSuffixSkip[3] == shift+len(suffix) == 6+5 == 11. private final int[] goodSuffixSkip; StringSearch(String patternSting) { this.pattern = patternSting.getBytes(); this.goodSuffixSkip = new int[pattern.length]; // last is the index of the last character in the pattern. int last = pattern.length - 1; // Build bad character table. // Bytes not in the pattern can skip one pattern's length. Arrays.fill(badCharSkip, pattern.length); // The loop condition is < instead of <= so that the last byte does not // have a zero distance to itself. Finding this byte out of place implies // that it is not in the last position. for (int i = 0; i < last; i++) { badCharSkip[pattern[i] + 128] = last - i; } // Build good suffix table. // First pass: set each value to the next index which starts a prefix of // pattern. int lastPrefix = last; for (int i = last; i >= 0; i--) { if (hasPrefix(pattern, new Slice(pattern, i + 1))) { lastPrefix = i + 1; } // lastPrefix is the shift, and (last-i) is len(suffix). goodSuffixSkip[i] = lastPrefix + last - i; } // Second pass: find repeats of pattern's suffix starting from the front. for (int i = 0; i < last; i++) { int lenSuffix = longestCommonSuffix(pattern, new Slice(pattern, 1, i + 1)); if (pattern[i - lenSuffix] != pattern[last - lenSuffix]) { // (last-i) is the shift, and lenSuffix is len(suffix). goodSuffixSkip[last - lenSuffix] = lenSuffix + last - i; } } } int next(String text) { return next(text.getBytes()); } private int next(byte[] text) { return next(ByteBuffer.wrap(text)); } private int next(ByteBuffer text) { return next(text, 0); } private int next(ByteBuffer text, int startingAfter) { int i = startingAfter + pattern.length - 1; while (i < text.limit()) { // Compare backwards from the end until the first unmatching character. int j = pattern.length - 1; while (j >= 0 && text.get(i) == pattern[j]) { i--; j--; } if (j < 0) { return i + 1; // match } i += Math.max(badCharSkip[text.get(i) + 128], goodSuffixSkip[j]); } return -1; } private boolean hasPrefix(byte[] s, Slice prefix) { for (int i = 0; i < prefix.length(); i++) { if (s[i] != prefix.get(i)) { return false; } } return true; } private int longestCommonSuffix(byte[] a, Slice b) { int i = 0; for (; i < a.length && i < b.length(); i++) { if (a[a.length - 1 - i] != b.get(b.length() - 1 - i)) { break; } } return i; } int nextWord(String text) { return nextWord(text.getBytes()); } private int nextWord(byte[] text) { return nextWord(ByteBuffer.wrap(text)); } private int nextWord(ByteBuffer text) { int i = 0; while (true) { i = next(text, i); if (i == -1) { return -1; } if (isWord(text, i)) { return i; } i++; } } public static int endOfLine(CharSequence contents, int cursor) { while (cursor < contents.length()) { char c = contents.charAt(cursor); if (c == '\r' || c == '\n') { break; } cursor++; } return cursor; } private boolean isWordChar(byte b) { char c = (char) (b + 128); return Character.isAlphabetic(c) || Character.isDigit(c) || c == '$' || c == '_'; } private boolean startsWord(ByteBuffer text, int offset) { if (offset == 0) { return true; } return !isWordChar(text.get(offset - 1)); } private boolean endsWord(ByteBuffer text, int offset) { if (offset + 1 >= text.limit()) { return true; } return !isWordChar(text.get(offset + 1)); } private boolean isWord(ByteBuffer text, int offset) { return startsWord(text, offset) && endsWord(text, offset + pattern.length - 1); } public static boolean containsWord(Path java, String query) { StringSearch search = new StringSearch(query); // if (FileStore.activeDocuments().contains(java)) { // var text = FileStore.contents(java).getBytes(); // return search.nextWord(text) != -1; // } try (FileChannel channel = FileChannel.open(java)) { // Read up to 1 MB of data from file int limit = Math.min((int) channel.size(), SEARCH_BUFFER.capacity()); SEARCH_BUFFER.position(0); SEARCH_BUFFER.limit(limit); channel.read(SEARCH_BUFFER); SEARCH_BUFFER.position(0); return search.nextWord(SEARCH_BUFFER) != -1; } catch (NoSuchFileException e) { return false; } catch (IOException e) { throw new RuntimeException(e); } } public static boolean matchesPartialName(CharSequence candidate, CharSequence partialName) { if (partialName.length() == 1 && partialName.equals(".")) { return true; } if (candidate.length() < partialName.length()) { return false; } for (int i = 0; i < partialName.length(); i++) { if (candidate.charAt(i) != partialName.charAt(i)) { return false; } } return true; // if (candidate.length() > partialName.length()) { // candidate = candidate.subSequence(0, partialName.length()); // } // double similarity = similarity(candidate.toString(), partialName.toString()); // return similarity > 0.5; } public static boolean matchesPartialNameLowercase( CharSequence candidate, CharSequence partialName) { if (partialName.length() == 1 && partialName.equals(".")) { return true; } if (candidate.length() < partialName.length()) { return false; } for (int i = 0; i < partialName.length(); i++) { if (Character.toLowerCase(candidate.charAt(i)) != Character.toLowerCase(partialName.charAt(i))) { return false; } } return true; } public static String packageName(File file) { Pattern packagePattern = Pattern.compile("package\\s+([a-zA_Z][.\\w]*+)(;)?"); Pattern startOfClass = Pattern.compile("^[\\w ]*class +\\w+"); try (BufferedReader lines = bufferedReader(file)) { for (String line = lines.readLine(); line != null; line = lines.readLine()) { if (startOfClass.matcher(line).find()) { return ""; } Matcher matchPackage = packagePattern.matcher(line); if (matchPackage.matches()) { String id = matchPackage.group(1); return id; } } } catch (IOException e) { throw new RuntimeException(e); } // TODO fall back on parsing file return ""; } // TODO this doesn't work for inner classes, eliminate public static String mostName(String name) { int lastDot = name.lastIndexOf('.'); return lastDot == -1 ? "" : name.substring(0, lastDot); } // TODO this doesn't work for inner classes, eliminate public static String lastName(String name) { int i = name.lastIndexOf('.'); if (i == -1) { return name; } else { return name.substring(i + 1); } } public static BufferedReader bufferedReader(File file) { try { return new BufferedReader(new InputStreamReader(new FileInputStream(file))); } catch (FileNotFoundException e) { return new BufferedReader(new StringReader("")); } } public static double similarity(String s1, String s2) { String longer = s1, shorter = s2; if (s1.length() < s2.length()) { // longer should always have greater length longer = s2; shorter = s1; } int longerLength = longer.length(); if (longerLength == 0) { return 1.0; /* both strings are zero length */ } return (longerLength - editDistance(longer, shorter)) / (double) longerLength; } public static int editDistance(String s1, String s2) { s1 = s1.toLowerCase(); s2 = s2.toLowerCase(); int[] costs = new int[s2.length() + 1]; for (int i = 0; i <= s1.length(); i++) { int lastValue = i; for (int j = 0; j <= s2.length(); j++) { if (i == 0) { costs[j] = j; } else { if (j > 0) { int newValue = costs[j - 1]; if (s1.charAt(i - 1) != s2.charAt(j - 1)) { newValue = Math.min(Math.min(newValue, lastValue), costs[j]) + 1; } costs[j - 1] = lastValue; lastValue = newValue; } } } if (i > 0) { costs[s2.length()] = lastValue; } } return costs[s2.length()]; } private static boolean containsString(Path java, String query) { StringSearch search = new StringSearch(query); // if (FileStore.activeDocuments().contains(java)) { // var text = FileStore.contents(java).getBytes(); // return search.next(text) != -1; // } try (FileChannel channel = FileChannel.open(java)) { // Read up to 1 MB of data from file int limit = Math.min((int) channel.size(), SEARCH_BUFFER.capacity()); SEARCH_BUFFER.position(0); SEARCH_BUFFER.limit(limit); channel.read(SEARCH_BUFFER); SEARCH_BUFFER.position(0); return search.next(SEARCH_BUFFER) != -1; } catch (NoSuchFileException e) { return false; } catch (IOException e) { throw new RuntimeException(e); } } public static boolean endsWithParen(CharSequence contents, int cursor) { for (int i = cursor; i < contents.length(); i++) { if (!Character.isJavaIdentifierPart(contents.charAt(i))) { return contents.charAt(i) == '('; } } return false; } public static String partialIdentifier(String contents, int end) { int start = end; while (start > 0 && Character.isJavaIdentifierPart(contents.charAt(start - 1))) { start--; } return contents.substring(start, end); } public static boolean isQualifiedIdentifierChar(char c) { return c == '.' || Character.isJavaIdentifierPart(c); } public static String qualifiedPartialIdentifier(String contents, int end) { int start = end; while (start > 0 && isQualifiedIdentifierChar(contents.charAt(start - 1))) { start--; } return contents.substring(start, end); } private static class Slice { private final byte[] target; private int from, until; int length() { return until - from; } byte get(int i) { return target[from + i]; } Slice(byte[] target, int from) { this(target, from, target.length); } Slice(byte[] target, int from, int until) { this.target = target; this.from = from; this.until = until; } } private static final ByteBuffer SEARCH_BUFFER = ByteBuffer.allocateDirect(1024 * 1024); }
13,109
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
AndroidUtilities.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/common/src/main/java/com/tyron/common/util/AndroidUtilities.java
package com.tyron.common.util; import android.app.Activity; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.util.DisplayMetrics; import android.util.Log; import android.util.TypedValue; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.StringRes; import com.google.android.material.dialog.MaterialAlertDialogBuilder; import com.tyron.common.ApplicationProvider; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; @SuppressWarnings("unused") public class AndroidUtilities { public static void showToast(String message) { Toast.makeText(ApplicationProvider.getApplicationContext(), message, Toast.LENGTH_LONG).show(); } public static void showToast(@StringRes int id) { Toast.makeText(ApplicationProvider.getApplicationContext(), id, Toast.LENGTH_SHORT).show(); } public static int dp(float px) { return Math.round( ApplicationProvider.getApplicationContext().getResources().getDisplayMetrics().density * px); } public static void setMargins( View view, int startMargin, int topMargin, int endMargin, int bottomMargin) { ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) view.getLayoutParams(); layoutParams.setMargins(dp(startMargin), dp(topMargin), dp(endMargin), dp(bottomMargin)); } /** * Converts a dp value into px that can be applied on margins, paddings etc * * @param dp The dp value that will be converted into px * @return The converted px value from the dp argument given */ public static int dpToPx(float dp) { return Math.round( TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, dp, ApplicationProvider.getApplicationContext().getResources().getDisplayMetrics())); } public static void hideKeyboard(View view) { if (view == null) { return; } try { InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Activity.INPUT_METHOD_SERVICE); if (!imm.isActive()) { return; } imm.hideSoftInputFromWindow(view.getWindowToken(), 0); } catch (Exception e) { Log.d("AndroidUtilities", "Failed to close keyboard " + e.getMessage()); } } public static String calculateMD5(File updateFile) { InputStream is; try { is = new FileInputStream(updateFile); } catch (FileNotFoundException e) { Log.e("calculateMD5", "Exception while getting FileInputStream", e); return null; } return calculateMD5(is); } public static String calculateMD5(InputStream is) { MessageDigest digest; try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { Log.e("calculateMD5", "Exception while getting Digest", e); return null; } byte[] buffer = new byte[8192]; int read; try { while ((read = is.read(buffer)) > 0) { digest.update(buffer, 0, read); } byte[] md5sum = digest.digest(); BigInteger bigInt = new BigInteger(1, md5sum); String output = bigInt.toString(16); // Fill to 32 chars output = String.format("%32s", output).replace(' ', '0'); return output; } catch (IOException e) { throw new RuntimeException("Unable to process file for MD5", e); } finally { try { is.close(); } catch (IOException e) { Log.e("calculateMD5", "Exception on closing MD5 input stream", e); } } } public static void showSimpleAlert( Context context, @StringRes int title, @StringRes int message) { showSimpleAlert(context, context.getString(title), context.getString(message)); } public static void showSimpleAlert( @NonNull Context context, @StringRes int title, String message) { showSimpleAlert(context, context.getString(title), message); } public static void showSimpleAlert(Context context, String title, String message) { new MaterialAlertDialogBuilder(context) .setTitle(title) .setMessage(message) .setPositiveButton(android.R.string.ok, null) .show(); } public static void copyToClipboard(String text) { ClipboardManager clipboard = (ClipboardManager) ApplicationProvider.getApplicationContext().getSystemService(Context.CLIPBOARD_SERVICE); ClipData clip = ClipData.newPlainText("", text); // is label important? clipboard.setPrimaryClip(clip); } @Nullable public static CharSequence getPrimaryClip() { ClipboardManager clipboard = (ClipboardManager) ApplicationProvider.getApplicationContext().getSystemService(Context.CLIPBOARD_SERVICE); ClipData primaryClip = clipboard.getPrimaryClip(); if (primaryClip != null) { if (primaryClip.getItemCount() >= 1) { return primaryClip.getItemAt(0).getText(); } } return null; } public static void copyToClipboard(String text, boolean showToast) { copyToClipboard(text); if (showToast) showToast("Copied \"" + text + "\" to clipboard"); } public static int getHeight(ViewGroup viewGroup) { int height = 0; for (int i = 0; i < viewGroup.getChildCount(); i++) { View view = viewGroup.getChildAt(i); height += view.getMeasuredHeight(); } return height; } public static int getRowCount(int itemWidth) { DisplayMetrics displayMetrics = ApplicationProvider.getApplicationContext().getResources().getDisplayMetrics(); return (displayMetrics.widthPixels / itemWidth); } }
6,004
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
ExecutionResult.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/common/src/main/java/com/tyron/common/util/ExecutionResult.java
package com.tyron.common.util; public class ExecutionResult { private final int exitValue; private final String output; public ExecutionResult(int exitValue, String output) { this.exitValue = exitValue; this.output = output; } public int getExitValue() { return exitValue; } public String getOutput() { return output; } }
359
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
FileUtilsEx.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/common/src/main/java/com/tyron/common/util/FileUtilsEx.java
package com.tyron.common.util; import java.io.File; import java.io.IOException; public class FileUtilsEx { /** * Creates the given file and throws {@link IOException} if it fails, also checks if the file * already exists before creating */ public static void createFile(File file) throws IOException { if (!file.exists() && !file.createNewFile()) { throw new IOException("Unable to create file: " + file); } } }
444
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
ExtensionPoint.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/language-api/src/main/java/com/tyron/extension/ExtensionPoint.java
package com.tyron.extension; import org.jetbrains.annotations.NotNull; public interface ExtensionPoint<T> { void registerExtension(T extension); T @NotNull [] getExtensions(); }
186
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
LanguageFileType.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/language-api/src/main/java/com/tyron/language/fileTypes/LanguageFileType.java
package com.tyron.language.fileTypes; import com.tyron.language.api.Language; import org.jetbrains.annotations.NotNull; public abstract class LanguageFileType implements FileType { private final Language mLanguage; private final boolean mSecondary; protected LanguageFileType(@NotNull Language instance) { this(instance, false); } protected LanguageFileType(@NotNull Language instance, boolean secondary) { mLanguage = instance; mSecondary = secondary; } @NotNull public final Language getLanguage() { return mLanguage; } public boolean isSecondary() { return mSecondary; } @NotNull public String getDisplayName() { return mLanguage.getDisplayName(); } }
715
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
FileType.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/language-api/src/main/java/com/tyron/language/fileTypes/FileType.java
package com.tyron.language.fileTypes; import android.graphics.drawable.Drawable; import org.jetbrains.annotations.NotNull; public interface FileType { @NotNull String getName(); @NotNull String getDisplayName(); @NotNull String getDescription(); @NotNull String getDefaultExtension(); @NotNull Drawable getIcon(); }
343
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
FileTypeManager.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/language-api/src/main/java/com/tyron/language/fileTypes/FileTypeManager.java
package com.tyron.language.fileTypes; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class FileTypeManager { private static FileTypeManager sInstance; public static FileTypeManager getInstance() { if (sInstance == null) { sInstance = new FileTypeManager(); } return sInstance; } private final List<LanguageFileType> sRegisteredFileTypes = Collections.synchronizedList(new ArrayList<>()); private FileTypeManager() {} public void registerFileType(@NotNull LanguageFileType fileType) { if (sRegisteredFileTypes.contains(fileType)) { return; } sRegisteredFileTypes.add(fileType); } @Nullable public LanguageFileType findFileType(@NotNull File file) { for (LanguageFileType fileType : sRegisteredFileTypes) { if (getExtension(file).equals(fileType.getDefaultExtension())) { return fileType; } } return null; } private String getExtension(@NotNull File file) { String name = file.getName(); if (!name.contains(".")) { return ""; } return name.substring(name.lastIndexOf('.') + 1, name.length()); } }
1,271
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
Language.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/language-api/src/main/java/com/tyron/language/api/Language.java
package com.tyron.language.api; import com.tyron.language.fileTypes.LanguageFileType; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public abstract class Language { private static final Map<Class<? extends Language>, Language> sRegisteredLanguages = new ConcurrentHashMap<>(); private static final Map<String, Language> sRegisteredIds = new ConcurrentHashMap<>(); public static final Language ANY = new Language("") { @Override public @NotNull String toString() { return "Language: ANY"; } @Override public @Nullable LanguageFileType getAssociatedFileType() { return null; } }; private final String mId; protected Language(@NotNull String id) { mId = id; Class<? extends Language> langClass = getClass(); Language prev = sRegisteredLanguages.putIfAbsent(langClass, this); if (prev != null) { throw new IllegalStateException("Language of " + langClass + " is already registered."); } Language prevId = sRegisteredIds.putIfAbsent(id, this); if (prevId != null) { throw new IllegalStateException("Language with ID " + id + " is already registered."); } } @NotNull public static Collection<Language> getRegisteredLanguages() { Collection<Language> values = sRegisteredLanguages.values(); return Collections.unmodifiableCollection(values); } @NotNull public String getId() { return mId; } @Nullable public LanguageFileType getAssociatedFileType() { return null; } @NotNull public String toString() { return "Language: " + mId; } public String getDisplayName() { return getId(); } }
1,852
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
PluginProblemReporterImpl.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/kotlinc/src/main/java/org/jetbrains/kotlin/com/intellij/diagnostic/PluginProblemReporterImpl.java
package org.jetbrains.kotlin.com.intellij.diagnostic; public class PluginProblemReporterImpl implements PluginProblemReporter { @Override public PluginException createPluginExceptionByClass(String s, Throwable throwable, Class aClass) { return new PluginException(s, throwable, null); } public static Class<PluginProblemReporter> getInterface() { return PluginProblemReporter.class; } }
407
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
FileModificationService2.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/kotlinc/src/main/java/org/jetbrains/kotlin/com/intellij/codeInsight/FileModificationService2.java
package org.jetbrains.kotlin.com.intellij.codeInsight; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import java.util.Arrays; import java.util.Collection; import org.jetbrains.kotlin.com.intellij.openapi.application.ApplicationManager; import org.jetbrains.kotlin.com.intellij.openapi.project.Project; import org.jetbrains.kotlin.com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.kotlin.com.intellij.psi.PsiElement; import org.jetbrains.kotlin.com.intellij.psi.PsiFile; public abstract class FileModificationService2 { public static FileModificationService2 getInstance() { return ApplicationManager.getApplication().getService(FileModificationService2.class); } public abstract boolean preparePsiElementsForWrite( @NonNull Collection<? extends PsiElement> elements); public abstract boolean prepareFileForWrite(@Nullable final PsiFile psiFile); public boolean preparePsiElementForWrite(@Nullable PsiElement element) { PsiFile file = element == null ? null : element.getContainingFile(); return prepareFileForWrite(file); } public boolean preparePsiElementsForWrite(PsiElement... elements) { return preparePsiElementsForWrite(Arrays.asList(elements)); } public abstract boolean prepareVirtualFilesForWrite( @NonNull Project project, @NonNull Collection<? extends VirtualFile> files); }
1,375
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
CodeInsightUtilCore2.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/kotlinc/src/main/java/org/jetbrains/kotlin/com/intellij/codeInsight/CodeInsightUtilCore2.java
package org.jetbrains.kotlin.com.intellij.codeInsight; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import gnu.trove.THashSet; import java.util.Collection; import java.util.Set; import org.jetbrains.kotlin.com.intellij.openapi.diagnostic.Logger; import org.jetbrains.kotlin.com.intellij.openapi.project.Project; import org.jetbrains.kotlin.com.intellij.openapi.vfs.VfsUtilCore; import org.jetbrains.kotlin.com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.kotlin.com.intellij.psi.PsiElement; import org.jetbrains.kotlin.com.intellij.psi.PsiFile; public class CodeInsightUtilCore2 extends FileModificationService2 { private static final Logger LOG = Logger.getInstance(CodeInsightUtilCore.class); @Override public boolean preparePsiElementsForWrite(@NonNull Collection<? extends PsiElement> elements) { if (elements.isEmpty()) return true; Set<VirtualFile> files = new THashSet<VirtualFile>(); Project project = null; for (PsiElement element : elements) { PsiFile file = element.getContainingFile(); if (file == null) continue; project = file.getProject(); VirtualFile virtualFile = file.getVirtualFile(); if (virtualFile == null) continue; files.add(virtualFile); } if (!files.isEmpty()) { VirtualFile[] virtualFiles = VfsUtilCore.toVirtualFileArray(files); // ReadonlyStatusHandler.OperationStatus status = // ReadonlyStatusHandler.getInstance(project).ensureFilesWritable(virtualFiles); // return !status.hasReadonlyFiles(); } return true; } @Override public boolean prepareFileForWrite(@Nullable PsiFile psiFile) { if (psiFile == null) return false; final VirtualFile file = psiFile.getVirtualFile(); final Project project = psiFile.getProject(); // final Editor editor = // psiFile.isWritable() ? null : // FileEditorManager.getInstance(project).openTextEditor(new OpenFileDescriptor(project, file), // true); // if (!ReadonlyStatusHandler.ensureFilesWritable(project, file)) { // ApplicationManager.getApplication().invokeLater(new Runnable() { // @Override // public void run() { // if (editor != null && editor.getComponent().isDisplayable()) { // HintManager.getInstance() // .showErrorHint(editor, // CodeInsightBundle.message("error.hint.file.is.readonly", file.getPresentableUrl())); // } // } // }); // // return false; // } return true; } @Override public boolean prepareVirtualFilesForWrite( @NonNull Project project, @NonNull Collection<? extends VirtualFile> files) { return true; } }
2,884
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
CoreApplicationEnvironment.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/kotlinc/src/main/java/org/jetbrains/kotlin/com/intellij/core/CoreApplicationEnvironment.java
// // Source code recreated from a .class file by IntelliJ IDEA // (powered by FernFlower decompiler) // package org.jetbrains.kotlin.com.intellij.core; import androidx.annotation.Nullable; import java.lang.reflect.Modifier; import java.nio.file.Path; import java.util.Arrays; import java.util.List; import org.jetbrains.kotlin.com.intellij.codeInsight.folding.CodeFoldingSettings; import org.jetbrains.kotlin.com.intellij.concurrency.JobLauncher; import org.jetbrains.kotlin.com.intellij.ide.plugins.DisabledPluginsState; import org.jetbrains.kotlin.com.intellij.ide.plugins.PluginManagerCore; import org.jetbrains.kotlin.com.intellij.lang.DefaultASTFactory; import org.jetbrains.kotlin.com.intellij.lang.DefaultASTFactoryImpl; import org.jetbrains.kotlin.com.intellij.lang.Language; import org.jetbrains.kotlin.com.intellij.lang.LanguageExtension; import org.jetbrains.kotlin.com.intellij.lang.LanguageParserDefinitions; import org.jetbrains.kotlin.com.intellij.lang.ParserDefinition; import org.jetbrains.kotlin.com.intellij.lang.PsiBuilderFactory; import org.jetbrains.kotlin.com.intellij.lang.impl.PsiBuilderFactoryImpl; import org.jetbrains.kotlin.com.intellij.mock.MockApplication; import org.jetbrains.kotlin.com.intellij.mock.MockFileDocumentManagerImpl; import org.jetbrains.kotlin.com.intellij.openapi.Disposable; import org.jetbrains.kotlin.com.intellij.openapi.application.ApplicationInfo; import org.jetbrains.kotlin.com.intellij.openapi.application.ApplicationManager; import org.jetbrains.kotlin.com.intellij.openapi.application.impl.ApplicationInfoImpl; import org.jetbrains.kotlin.com.intellij.openapi.command.CommandProcessor; import org.jetbrains.kotlin.com.intellij.openapi.command.impl.CoreCommandProcessor; import org.jetbrains.kotlin.com.intellij.openapi.editor.impl.DocumentImpl; import org.jetbrains.kotlin.com.intellij.openapi.extensions.BaseExtensionPointName; import org.jetbrains.kotlin.com.intellij.openapi.extensions.ExtensionPoint; import org.jetbrains.kotlin.com.intellij.openapi.extensions.ExtensionPoint.Kind; import org.jetbrains.kotlin.com.intellij.openapi.extensions.ExtensionPointName; import org.jetbrains.kotlin.com.intellij.openapi.extensions.Extensions; import org.jetbrains.kotlin.com.intellij.openapi.extensions.ExtensionsArea; import org.jetbrains.kotlin.com.intellij.openapi.fileEditor.FileDocumentManager; import org.jetbrains.kotlin.com.intellij.openapi.fileTypes.FileType; import org.jetbrains.kotlin.com.intellij.openapi.fileTypes.FileTypeExtension; import org.jetbrains.kotlin.com.intellij.openapi.progress.ProgressManager; import org.jetbrains.kotlin.com.intellij.openapi.progress.impl.CoreProgressManager; import org.jetbrains.kotlin.com.intellij.openapi.util.ClassExtension; import org.jetbrains.kotlin.com.intellij.openapi.util.Disposer; import org.jetbrains.kotlin.com.intellij.openapi.vfs.VirtualFileManager; import org.jetbrains.kotlin.com.intellij.openapi.vfs.VirtualFileManagerListener; import org.jetbrains.kotlin.com.intellij.openapi.vfs.VirtualFileSystem; import org.jetbrains.kotlin.com.intellij.openapi.vfs.encoding.EncodingManager; import org.jetbrains.kotlin.com.intellij.openapi.vfs.impl.CoreVirtualFilePointerManager; import org.jetbrains.kotlin.com.intellij.openapi.vfs.impl.VirtualFileManagerImpl; import org.jetbrains.kotlin.com.intellij.openapi.vfs.impl.jar.CoreJarFileSystem; import org.jetbrains.kotlin.com.intellij.openapi.vfs.local.CoreLocalFileSystem; import org.jetbrains.kotlin.com.intellij.openapi.vfs.pointers.VirtualFilePointerManager; import org.jetbrains.kotlin.com.intellij.psi.PsiReferenceService; import org.jetbrains.kotlin.com.intellij.psi.PsiReferenceServiceImpl; import org.jetbrains.kotlin.com.intellij.psi.impl.source.resolve.reference.ReferenceProvidersRegistry; import org.jetbrains.kotlin.com.intellij.psi.impl.source.resolve.reference.ReferenceProvidersRegistryImpl; import org.jetbrains.kotlin.com.intellij.psi.stubs.CoreStubTreeLoader; import org.jetbrains.kotlin.com.intellij.psi.stubs.StubTreeLoader; import org.jetbrains.kotlin.com.intellij.util.KeyedLazyInstanceEP; import org.jetbrains.kotlin.com.intellij.util.graph.GraphAlgorithms; import org.jetbrains.kotlin.com.intellij.util.graph.impl.GraphAlgorithmsImpl; import org.jetbrains.kotlin.org.picocontainer.MutablePicoContainer; import org.jetbrains.kotlin.resolve.diagnostics.DiagnosticSuppressor; public class CoreApplicationEnvironment { private final CoreFileTypeRegistry myFileTypeRegistry; protected final MockApplication myApplication; private final CoreLocalFileSystem myLocalFileSystem; protected final VirtualFileSystem myJarFileSystem; private final VirtualFileSystem myJrtFileSystem; private final Disposable myParentDisposable; private final boolean myUnitTestMode; public CoreApplicationEnvironment(Disposable parentDisposable) { this(parentDisposable, true); } public CoreApplicationEnvironment(Disposable parentDisposable, boolean unitTestMode) { super(); this.myParentDisposable = parentDisposable; this.myUnitTestMode = unitTestMode; DisabledPluginsState.dontLoadDisabledPlugins(); this.myFileTypeRegistry = new CoreFileTypeRegistry(); this.myApplication = this.createApplication(this.myParentDisposable); ApplicationManager.setApplication( this.myApplication, () -> this.myFileTypeRegistry, this.myParentDisposable); this.myLocalFileSystem = this.createLocalFileSystem(); this.myJarFileSystem = this.createJarFileSystem(); this.myJrtFileSystem = this.createJrtFileSystem(); this.registerApplicationService( FileDocumentManager.class, new MockFileDocumentManagerImpl(null, DocumentImpl::new)); registerApplicationExtensionPoint( new ExtensionPointName<>("org.jetbrains.kotlin.com.intellij.virtualFileManagerListener"), VirtualFileManagerListener.class); List<VirtualFileSystem> fs = this.myJrtFileSystem != null ? Arrays.asList(this.myLocalFileSystem, this.myJarFileSystem, this.myJrtFileSystem) : Arrays.asList(this.myLocalFileSystem, this.myJarFileSystem); this.registerApplicationService(VirtualFileManager.class, new VirtualFileManagerImpl(fs)); registerApplicationExtensionPoint( new ExtensionPointName<>("org.jetbrains.kotlin.com.intellij.virtualFileSystem"), KeyedLazyInstanceEP.class); registerApplicationExtensionPoint( DiagnosticSuppressor.Companion.getEP_NAME(), DiagnosticSuppressor.class); this.registerApplicationService(EncodingManager.class, new CoreEncodingRegistry()); this.registerApplicationService( VirtualFilePointerManager.class, this.createVirtualFilePointerManager()); this.registerApplicationService(DefaultASTFactory.class, new DefaultASTFactoryImpl()); this.registerApplicationService(PsiBuilderFactory.class, new PsiBuilderFactoryImpl()); this.registerApplicationService( ReferenceProvidersRegistry.class, new ReferenceProvidersRegistryImpl()); this.registerApplicationService(StubTreeLoader.class, new CoreStubTreeLoader()); this.registerApplicationService(PsiReferenceService.class, new PsiReferenceServiceImpl()); this.registerApplicationService(ProgressManager.class, this.createProgressIndicatorProvider()); this.registerApplicationService(JobLauncher.class, this.createJobLauncher()); this.registerApplicationService(CodeFoldingSettings.class, new CodeFoldingSettings()); this.registerApplicationService(CommandProcessor.class, new CoreCommandProcessor()); this.registerApplicationService(GraphAlgorithms.class, new GraphAlgorithmsImpl()); this.myApplication.registerService(ApplicationInfo.class, ApplicationInfoImpl.class); } public <T> void registerApplicationService(Class<T> serviceInterface, T serviceImplementation) { this.myApplication.registerService(serviceInterface, serviceImplementation); } protected VirtualFilePointerManager createVirtualFilePointerManager() { return new CoreVirtualFilePointerManager(); } protected MockApplication createApplication(Disposable parentDisposable) { return new MockApplication(parentDisposable) { public boolean isUnitTestMode() { return CoreApplicationEnvironment.this.myUnitTestMode; } }; } protected JobLauncher createJobLauncher() { return new JobLauncher() {}; } protected ProgressManager createProgressIndicatorProvider() { return new CoreProgressManager(); } protected VirtualFileSystem createJarFileSystem() { return new CoreJarFileSystem(); } protected CoreLocalFileSystem createLocalFileSystem() { return new CoreLocalFileSystem(); } @Nullable protected VirtualFileSystem createJrtFileSystem() { return null; } public MockApplication getApplication() { return this.myApplication; } public Disposable getParentDisposable() { return this.myParentDisposable; } public <T> void registerApplicationComponent(Class<T> interfaceClass, T implementation) { registerComponentInstance( this.myApplication.getPicoContainer(), interfaceClass, implementation); if (implementation instanceof Disposable) { Disposer.register(this.myApplication, (Disposable) implementation); } } public void registerFileType(FileType fileType, String extension) { this.myFileTypeRegistry.registerFileType(fileType, extension); } public void registerParserDefinition(ParserDefinition definition) { this.addExplicitExtension( LanguageParserDefinitions.INSTANCE, definition.getFileNodeType().getLanguage(), definition); } public static <T> void registerComponentInstance( MutablePicoContainer container, Class<T> key, T implementation) { container.unregisterComponent(key); container.registerComponentInstance(key, implementation); } public <T> void addExplicitExtension(LanguageExtension<T> instance, Language language, T object) { instance.addExplicitExtension(language, object, this.myParentDisposable); } public void registerParserDefinition(Language language, ParserDefinition parserDefinition) { this.addExplicitExtension( LanguageParserDefinitions.INSTANCE, (Language) language, parserDefinition); } public <T> void addExplicitExtension(FileTypeExtension<T> instance, FileType fileType, T object) { instance.addExplicitExtension(fileType, object, this.myParentDisposable); } public <T> void addExplicitExtension(ClassExtension<T> instance, Class<T> aClass, T object) { instance.addExplicitExtension(aClass, object, this.myParentDisposable); } public <T> void addExtension(ExtensionPointName<T> name, T extension) { ExtensionPoint<T> extensionPoint = Extensions.getRootArea().getExtensionPoint(name); extensionPoint.registerExtension(extension, this.myParentDisposable); } public static <T> void registerExtensionPoint( ExtensionsArea area, ExtensionPointName<T> extensionPointName, Class<? extends T> aClass) { registerExtensionPoint(area, extensionPointName.getName(), aClass); } public static <T> void registerExtensionPoint( ExtensionsArea area, BaseExtensionPointName<T> extensionPointName, Class<? extends T> aClass) { registerExtensionPoint(area, extensionPointName.getName(), aClass); } public static <T> void registerExtensionPoint( ExtensionsArea area, String name, Class<? extends T> aClass) { if (!area.hasExtensionPoint(name)) { Kind kind = !aClass.isInterface() && !Modifier.isAbstract(aClass.getModifiers()) ? Kind.BEAN_CLASS : Kind.INTERFACE; area.registerExtensionPoint(name, aClass.getName(), kind); } } public static <T> void registerDynamicExtensionPoint( ExtensionsArea area, String name, Class<? extends T> aClass) { if (!area.hasExtensionPoint(name)) { Kind kind = !aClass.isInterface() && !Modifier.isAbstract(aClass.getModifiers()) ? Kind.BEAN_CLASS : Kind.INTERFACE; area.registerDynamicExtensionPoint(name, aClass.getName(), kind); } } public static <T> void registerApplicationDynamicExtensionPoint(String name, Class<T> clazz) { registerDynamicExtensionPoint(Extensions.getRootArea(), name, clazz); } public static <T> void registerApplicationExtensionPoint( ExtensionPointName<T> extensionPointName, Class<? extends T> aClass) { registerExtensionPoint(Extensions.getRootArea(), extensionPointName, aClass); } public static void registerExtensionPointAndExtensions( Path pluginRoot, String fileName, ExtensionsArea area) { PluginManagerCore.registerExtensionPointAndExtensions(pluginRoot, fileName, area); } public CoreLocalFileSystem getLocalFileSystem() { return this.myLocalFileSystem; } public VirtualFileSystem getJarFileSystem() { return this.myJarFileSystem; } @Nullable public VirtualFileSystem getJrtFileSystem() { return this.myJrtFileSystem; } }
12,976
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
WriteCommandAction.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/kotlinc/src/main/java/org/jetbrains/kotlin/com/intellij/openapi/command/WriteCommandAction.java
package org.jetbrains.kotlin.com.intellij.openapi.command; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import java.util.Arrays; import java.util.concurrent.atomic.AtomicReference; import org.jetbrains.kotlin.com.intellij.codeInsight.FileModificationService2; import org.jetbrains.kotlin.com.intellij.core.CoreBundle; import org.jetbrains.kotlin.com.intellij.openapi.application.Application; import org.jetbrains.kotlin.com.intellij.openapi.application.ApplicationManager; import org.jetbrains.kotlin.com.intellij.openapi.application.BaseActionRunnable2; import org.jetbrains.kotlin.com.intellij.openapi.application.ModalityState; import org.jetbrains.kotlin.com.intellij.openapi.application.Result; import org.jetbrains.kotlin.com.intellij.openapi.application.RunResult; import org.jetbrains.kotlin.com.intellij.openapi.diagnostic.Logger; import org.jetbrains.kotlin.com.intellij.openapi.progress.ProcessCanceledException; import org.jetbrains.kotlin.com.intellij.openapi.project.Project; import org.jetbrains.kotlin.com.intellij.openapi.util.Computable; import org.jetbrains.kotlin.com.intellij.openapi.util.Ref; import org.jetbrains.kotlin.com.intellij.openapi.util.ThrowableComputable; import org.jetbrains.kotlin.com.intellij.psi.PsiFile; import org.jetbrains.kotlin.com.intellij.util.ArrayUtil; import org.jetbrains.kotlin.com.intellij.util.ObjectUtils; import org.jetbrains.kotlin.com.intellij.util.ThrowableRunnable; public abstract class WriteCommandAction<T> extends BaseActionRunnable2<T> { private static final Logger LOG = Logger.getInstance(WriteCommandAction.class); private static final String DEFAULT_GROUP_ID = null; public interface Builder { @NonNull Builder withName(@Nullable String name); @NonNull Builder withGroupId(@Nullable String groupId); @NonNull Builder withUndoConfirmationPolicy(@NonNull UndoConfirmationPolicy policy); @NonNull Builder withGlobalUndo(); @NonNull Builder shouldRecordActionForActiveDocument(boolean value); <E extends Throwable> void run(@NonNull ThrowableRunnable<E> action) throws E; <R, E extends Throwable> R compute(@NonNull ThrowableComputable<R, E> action) throws E; } private static final class BuilderImpl implements Builder { private final Project myProject; private final PsiFile[] myPsiFiles; private String myCommandName = getDefaultCommandName(); private String myGroupId = DEFAULT_GROUP_ID; private UndoConfirmationPolicy myUndoConfirmationPolicy; private boolean myGlobalUndoAction; private boolean myShouldRecordActionForActiveDocument = true; private BuilderImpl(Project project, PsiFile... files) { myProject = project; myPsiFiles = files; } @NonNull @Override public Builder withName(String name) { myCommandName = name; return this; } @NonNull @Override public Builder withGlobalUndo() { myGlobalUndoAction = true; return this; } @NonNull @Override public Builder shouldRecordActionForActiveDocument(boolean value) { myShouldRecordActionForActiveDocument = value; return this; } @NonNull @Override public Builder withUndoConfirmationPolicy(@NonNull UndoConfirmationPolicy policy) { if (myUndoConfirmationPolicy != null) throw new IllegalStateException("do not call withUndoConfirmationPolicy() several times"); myUndoConfirmationPolicy = policy; return this; } @NonNull @Override public Builder withGroupId(String groupId) { myGroupId = groupId; return this; } @Override public <E extends Throwable> void run(@NonNull final ThrowableRunnable<E> action) throws E { Application application = ApplicationManager.getApplication(); boolean dispatchThread = application.isDispatchThread(); if (!dispatchThread && application.isReadAccessAllowed()) { LOG.error( "Must not start write action from within read action in the other thread - deadlock is coming"); throw new IllegalStateException(); } AtomicReference<E> thrown = new AtomicReference<>(); if (dispatchThread) { thrown.set(doRunWriteCommandAction(action)); } else { try { ApplicationManager.getApplication() .invokeAndWait( () -> thrown.set(doRunWriteCommandAction(action)), ModalityState.defaultModalityState()); } catch (ProcessCanceledException ignored) { } } if (thrown.get() != null) { throw thrown.get(); } } private <E extends Throwable> E doRunWriteCommandAction(@NonNull ThrowableRunnable<E> action) { if (myPsiFiles.length > 0 && !FileModificationService2.getInstance().preparePsiElementsForWrite(myPsiFiles)) { return null; } AtomicReference<Throwable> thrown = new AtomicReference<>(); Runnable wrappedRunnable = () -> { if (myGlobalUndoAction) { // CommandProcessor.getInstance().markCurrentCommandAsGlobal(myProject); } ApplicationManager.getApplication() .runWriteAction( () -> { try { action.run(); } catch (Throwable e) { thrown.set(e); } }); }; CommandProcessor.getInstance() .executeCommand( myProject, wrappedRunnable, myCommandName, ObjectUtils.notNull( myUndoConfirmationPolicy, UndoConfirmationPolicy.DO_NOT_REQUEST_CONFIRMATION)); //noinspection unchecked return (E) thrown.get(); } @Override public <R, E extends Throwable> R compute(@NonNull final ThrowableComputable<R, E> action) throws E { AtomicReference<R> result = new AtomicReference<>(); run(() -> result.set(action.compute())); return result.get(); } } @NonNull public static Builder writeCommandAction(Project project) { return new BuilderImpl(project); } @NonNull public static Builder writeCommandAction(@NonNull PsiFile first, PsiFile... others) { return new BuilderImpl(first.getProject(), ArrayUtil.prepend(first, others)); } @NonNull public static Builder writeCommandAction(Project project, PsiFile... files) { return new BuilderImpl(project, files); } private final String myCommandName; private final String myGroupID; private final Project myProject; private final PsiFile[] myPsiFiles; /** * @deprecated Use {@link #writeCommandAction(Project, PsiFile...)}{@code .run()} instead */ @Deprecated protected WriteCommandAction(@Nullable Project project, PsiFile... files) { this(project, getDefaultCommandName(), files); } /** * @deprecated Use {@link #writeCommandAction(Project, PsiFile...)}{@code * .withName(commandName).run()} instead */ @Deprecated protected WriteCommandAction( @Nullable Project project, @Nullable String commandName, PsiFile... files) { this(project, commandName, DEFAULT_GROUP_ID, files); } /** * @deprecated Use {@link #writeCommandAction(Project, PsiFile...)}{@code * .withName(commandName).withGroupId(groupID).run()} instead */ @Deprecated protected WriteCommandAction( @Nullable Project project, @Nullable String commandName, @Nullable String groupID, PsiFile... files) { myCommandName = commandName; myGroupID = groupID; myProject = project; myPsiFiles = files.length == 0 ? PsiFile.EMPTY_ARRAY : files; } public final Project getProject() { return myProject; } public final String getCommandName() { return myCommandName; } public String getGroupID() { return myGroupID; } /** * @deprecated Use {@code #writeCommandAction(Project).run()} or compute() instead */ @Deprecated @NonNull @Override public RunResult<T> execute() { Application application = ApplicationManager.getApplication(); boolean dispatchThread = application.isDispatchThread(); if (!dispatchThread && application.isReadAccessAllowed()) { LOG.error( "Must not start write action from within read action in the other thread - deadlock is coming"); throw new IllegalStateException(); } final RunResult<T> result = new RunResult<T>(this); if (dispatchThread) { performWriteCommandAction(result); } else { try { ApplicationManager.getApplication() .invokeAndWait( () -> performWriteCommandAction(result), ModalityState.defaultModalityState()); } catch (ProcessCanceledException ignored) { } } return result; } private void performWriteCommandAction(@NonNull RunResult<T> result) { if (myPsiFiles.length > 0 && !FileModificationService2.getInstance() .preparePsiElementsForWrite(Arrays.asList(myPsiFiles))) { return; } // this is needed to prevent memory leak, since the command is put into undo queue Ref<RunResult<?>> resultRef = new Ref<>(result); doExecuteCommand( () -> ApplicationManager.getApplication() .runWriteAction( () -> { resultRef.get().run(); resultRef.set(null); })); } /** * @deprecated Use {@link #writeCommandAction(Project)}.withGlobalUndo() instead */ @Deprecated protected boolean isGlobalUndoAction() { return false; } /** * See {@link CommandProcessor#executeCommand(Project, Runnable, String, Object, * UndoConfirmationPolicy, boolean)} for details. * * @deprecated Use {@link #writeCommandAction(Project)}.withUndoConfirmationPolicy() instead */ @Deprecated @NonNull protected UndoConfirmationPolicy getUndoConfirmationPolicy() { return UndoConfirmationPolicy.DO_NOT_REQUEST_CONFIRMATION; } private void doExecuteCommand(@NonNull Runnable runnable) { Runnable wrappedRunnable = () -> { // if (isGlobalUndoAction()) // CommandProcessor.getInstance().markCurrentCommandAsGlobal(getProject()); runnable.run(); }; CommandProcessorEx.getInstance() .executeCommand( getProject(), wrappedRunnable, getCommandName(), getUndoConfirmationPolicy()); } /** * WriteCommandAction without result * * @deprecated Use {@link #writeCommandAction(Project)}.run() or .compute() instead */ @Deprecated public abstract static class Simple<T> extends WriteCommandAction<T> { protected Simple(Project project, /*@NonNull*/ PsiFile... files) { super(project, files); } protected Simple(Project project, String commandName, /*@NonNull*/ PsiFile... files) { super(project, commandName, files); } protected Simple(Project project, String name, String groupID, /*@NonNull*/ PsiFile... files) { super(project, name, groupID, files); } @Override protected void run(@NonNull Result<T> result) throws Throwable { run(); } protected abstract void run() throws Throwable; } /** * If run a write command using this method then "Undo" action always shows "Undefined" text. * * <p>Please use {@link #runWriteCommandAction(Project, String, String, Runnable, PsiFile...)} * instead. */ @VisibleForTesting public static void runWriteCommandAction(Project project, @NonNull Runnable runnable) { runWriteCommandAction(project, getDefaultCommandName(), DEFAULT_GROUP_ID, runnable); } private static String getDefaultCommandName() { return CoreBundle.message("command.name.undefined"); } public static void runWriteCommandAction( Project project, @Nullable final String commandName, @Nullable final String groupID, @NonNull final Runnable runnable, PsiFile... files) { writeCommandAction(project, files) .withName(commandName) .withGroupId(groupID) .run(() -> runnable.run()); } public static <T> T runWriteCommandAction( Project project, @NonNull final Computable<T> computable) { return writeCommandAction(project).compute(() -> computable.compute()); } public static <T, E extends Throwable> T runWriteCommandAction( Project project, @NonNull final ThrowableComputable<T, E> computable) throws E { return writeCommandAction(project).compute(computable); } }
12,683
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
Result.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/kotlinc/src/main/java/org/jetbrains/kotlin/com/intellij/openapi/application/Result.java
package org.jetbrains.kotlin.com.intellij.openapi.application; public class Result<T> { protected T myResult; public final void setResult(T result) { myResult = result; } }
186
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
BaseActionRunnable2.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/kotlinc/src/main/java/org/jetbrains/kotlin/com/intellij/openapi/application/BaseActionRunnable2.java
package org.jetbrains.kotlin.com.intellij.openapi.application; public abstract class BaseActionRunnable2<T> { private boolean mySilentExecution; public boolean isSilentExecution() { return mySilentExecution; } protected abstract void run(Result<T> result) throws Throwable; public abstract RunResult<T> execute(); protected boolean canWriteNow() { return getApplication().isWriteAccessAllowed(); } protected boolean canReadNow() { return getApplication().isReadAccessAllowed(); } protected Application getApplication() { return ApplicationManager.getApplication(); } /** Same as execute() but do not log error if exception occurred. */ public final RunResult<T> executeSilently() { mySilentExecution = true; return execute(); } }
791
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
RunResult.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/kotlinc/src/main/java/org/jetbrains/kotlin/com/intellij/openapi/application/RunResult.java
package org.jetbrains.kotlin.com.intellij.openapi.application; import org.jetbrains.kotlin.com.intellij.openapi.diagnostic.Logger; import org.jetbrains.kotlin.com.intellij.openapi.progress.ProcessCanceledException; public class RunResult<T> extends Result<T> { private BaseActionRunnable2<T> myActionRunnable; private Throwable myThrowable; protected RunResult() {} public RunResult(BaseActionRunnable2<T> action) { myActionRunnable = action; } public RunResult<T> run() { try { myActionRunnable.run(this); } catch (ProcessCanceledException e) { throw e; // this exception may occur from time to time and it shouldn't be catched } catch (Throwable throwable) { myThrowable = throwable; if (!myActionRunnable.isSilentExecution()) { if (throwable instanceof RuntimeException) throw (RuntimeException) throwable; if (throwable instanceof Error) { throw (Error) throwable; } else { throw new RuntimeException(myThrowable); } } } finally { myActionRunnable = null; } return this; } public T getResultObject() { return myResult; } public RunResult logException(Logger logger) { if (hasException()) { logger.error(myThrowable); } return this; } public RunResult<T> throwException() throws RuntimeException, Error { if (hasException()) { if (myThrowable instanceof RuntimeException) { throw (RuntimeException) myThrowable; } if (myThrowable instanceof Error) { throw (Error) myThrowable; } throw new RuntimeException(myThrowable); } return this; } public boolean hasException() { return myThrowable != null; } public Throwable getThrowable() { return myThrowable; } public void setThrowable(Exception throwable) { myThrowable = throwable; } }
1,897
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
SafeStAXStreamBuilderWrapper.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/kotlinc/src/main/java/org/jetbrains/kotlin/com/intellij/openapi/util/SafeStAXStreamBuilderWrapper.java
package org.jetbrains.kotlin.com.intellij.openapi.util; import static org.openjdk.javax.xml.stream.XMLStreamConstants.CHARACTERS; import static org.openjdk.javax.xml.stream.XMLStreamConstants.COMMENT; import static org.openjdk.javax.xml.stream.XMLStreamConstants.DTD; import static org.openjdk.javax.xml.stream.XMLStreamConstants.END_ELEMENT; import static org.openjdk.javax.xml.stream.XMLStreamConstants.PROCESSING_INSTRUCTION; import static org.openjdk.javax.xml.stream.XMLStreamConstants.SPACE; import static org.openjdk.javax.xml.stream.XMLStreamConstants.START_DOCUMENT; import static org.openjdk.javax.xml.stream.XMLStreamConstants.START_ELEMENT; import org.jetbrains.kotlin.org.jdom.AttributeType; import org.jetbrains.kotlin.org.jdom.Element; import org.jetbrains.kotlin.org.jdom.Namespace; import org.openjdk.javax.xml.stream.XMLStreamException; import org.openjdk.javax.xml.stream.XMLStreamReader; public class SafeStAXStreamBuilderWrapper { public static final SafeJdomFactory FACTORY = new SafeJdomFactory.BaseSafeJdomFactory(); public static Element build( XMLStreamReader stream, boolean isIgnoreBoundaryWhitespace, boolean isNsSupported, SafeJdomFactory factory) throws XMLStreamException { int state = stream.getEventType(); if (state != START_DOCUMENT) { throw new XMLStreamException("beginning"); } Element rootElement = null; while (state != END_ELEMENT) { switch (state) { case START_DOCUMENT: case SPACE: case CHARACTERS: case COMMENT: case PROCESSING_INSTRUCTION: case DTD: break; case START_ELEMENT: rootElement = processElement(stream, isNsSupported, factory); break; default: throw new XMLStreamException("Unexpected"); } if (stream.hasNext()) { state = stream.next(); } else { throw new XMLStreamException("Unexpected"); } } if (rootElement == null) { return new Element("empty"); } return rootElement; } public static Element processElement( XMLStreamReader reader, boolean isNsSupported, SafeJdomFactory factory) { Element element = factory.element( reader.getLocalName(), isNsSupported ? Namespace.getNamespace(reader.getPrefix(), reader.getNamespaceURI()) : Namespace.NO_NAMESPACE); // handle attributes for (int i = 0, len = reader.getAttributeCount(); i < len; i++) { element.setAttribute( factory.attribute( reader.getAttributeLocalName(i), reader.getAttributeValue(i), AttributeType.valueOf(reader.getAttributeType(i)), isNsSupported ? Namespace.getNamespace(reader.getAttributePrefix(i), reader.getNamespaceURI()) : Namespace.NO_NAMESPACE)); } if (isNsSupported) { for (int i = 0, len = reader.getNamespaceCount(); i < len; i++) { element.addNamespaceDeclaration( Namespace.getNamespace(reader.getAttributePrefix(i), reader.getNamespaceURI(i))); } } return element; } }
3,194
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
NullableComputable.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/kotlinc/src/main/java/org/jetbrains/kotlin/com/intellij/openapi/util/NullableComputable.java
package org.jetbrains.kotlin.com.intellij.openapi.util; @FunctionalInterface public interface NullableComputable<T> extends Computable<T> { @Override T compute(); }
170
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
JDOMUtil.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/kotlinc/src/main/java/org/jetbrains/kotlin/com/intellij/openapi/util/JDOMUtil.java
// // Source code recreated from a .class file by IntelliJ IDEA // (powered by FernFlower decompiler) // package org.jetbrains.kotlin.com.intellij.openapi.util; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringWriter; import java.io.Writer; import java.nio.charset.StandardCharsets; import java.nio.file.ClosedFileSystemException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.regex.Pattern; import org.jetbrains.kotlin.com.intellij.openapi.diagnostic.Logger; import org.jetbrains.kotlin.com.intellij.openapi.vfs.CharsetToolkit; import org.jetbrains.kotlin.com.intellij.util.text.CharArrayUtil; import org.jetbrains.kotlin.com.intellij.xml.util.XmlStringUtil; import org.jetbrains.kotlin.org.jdom.Attribute; import org.jetbrains.kotlin.org.jdom.Content; import org.jetbrains.kotlin.org.jdom.Element; import org.jetbrains.kotlin.org.jdom.JDOMException; import org.jetbrains.kotlin.org.jdom.Namespace; import org.jetbrains.kotlin.org.jdom.Text; import org.jetbrains.kotlin.org.jdom.filter.Filter; import org.jetbrains.kotlin.org.jdom.output.Format; import org.jetbrains.kotlin.org.jdom.output.Format.TextMode; import org.jetbrains.kotlin.org.jdom.output.XMLOutputter; import org.openjdk.javax.xml.stream.XMLInputFactory; import org.openjdk.javax.xml.stream.XMLStreamException; import org.openjdk.javax.xml.stream.XMLStreamReader; public final class JDOMUtil { public static final Pattern XPOINTER_PATTERN = Pattern.compile("xpointer\\((.*)\\)"); public static final Namespace XINCLUDE_NAMESPACE = Namespace.getNamespace("xi", "http://www.w3.org/2001/XInclude"); public static final Pattern CHILDREN_PATTERN = Pattern.compile("/([^/]*)(/[^/]*)?/\\*"); private static volatile XMLInputFactory XML_INPUT_FACTORY; private static final JDOMUtil.EmptyTextFilter CONTENT_FILTER = new JDOMUtil.EmptyTextFilter(); private static XMLInputFactory getXmlInputFactory() { XMLInputFactory factory = XML_INPUT_FACTORY; if (factory != null) { return factory; } else { Class var1 = JDOMUtil.class; synchronized (JDOMUtil.class) { factory = XML_INPUT_FACTORY; if (factory != null) { return factory; } else { String property = System.setProperty( "javax.xml.stream.XMLInputFactory", "org.openjdk.com.sun.xml.internal.stream.XMLInputFactoryImpl"); try { factory = XMLInputFactory.newFactory(); } finally { if (property != null) { System.setProperty("javax.xml.stream.XMLInputFactory", property); } else { System.clearProperty("javax.xml.stream.XMLInputFactory"); } } if (!SystemInfo.isIbmJvm) { try { factory.setProperty( "http://java.sun.com/xml/stream/properties/report-cdata-event", true); } catch (Exception var8) { getLogger() .error("cannot set \"report-cdata-event\" property for XMLInputFactory", var8); } } factory.setProperty("javax.xml.stream.isCoalescing", true); factory.setProperty("javax.xml.stream.isSupportingExternalEntities", false); factory.setProperty("javax.xml.stream.supportDTD", false); XML_INPUT_FACTORY = factory; return factory; } } } } private JDOMUtil() {} private static Logger getLogger() { return JDOMUtil.LoggerHolder.ourLogger; } private static Element loadUsingStaX(Reader reader, SafeJdomFactory factory) throws JDOMException, IOException { Element var3; try { XMLStreamReader xmlStreamReader = getXmlInputFactory().createXMLStreamReader(reader); try { var3 = SafeStAXStreamBuilderWrapper.build( xmlStreamReader, true, true, factory == null ? SafeStAXStreamBuilderWrapper.FACTORY : factory); } finally { xmlStreamReader.close(); } } catch (XMLStreamException var13) { throw new JDOMException(var13.getMessage(), var13); } finally { reader.close(); } return var3; } // @Internal public static Element load(Path file, SafeJdomFactory factory) throws JDOMException, IOException { if (file == null) { ; } try { return loadUsingStaX( new InputStreamReader( CharsetToolkit.inputStreamSkippingBOM( new BufferedInputStream(Files.newInputStream(file))), StandardCharsets.UTF_8), factory); } catch (ClosedFileSystemException var3) { throw new IOException("Cannot read file from closed file system: " + file, var3); } } // @Contract("null -> null; !null -> !null") public static Element load(InputStream stream) throws JDOMException, IOException { return stream == null ? null : load((InputStream) stream, (SafeJdomFactory) null); } // @Internal public static Element load(InputStream stream, SafeJdomFactory factory) throws JDOMException, IOException { if (stream == null) { ; } return loadUsingStaX(new InputStreamReader(stream, StandardCharsets.UTF_8), factory); } public static void writeElement(Element element, Writer writer, String lineSeparator) throws IOException { if (element == null) { ; } writeElement(element, writer, createOutputter(lineSeparator)); } public static void writeElement(Element element, Writer writer, XMLOutputter xmlOutputter) throws IOException { if (element == null) { ; } if (writer == null) { ; } if (xmlOutputter == null) { ; } try { xmlOutputter.output(element, writer); } catch (NullPointerException var4) { getLogger().error(var4); printDiagnostics(element, ""); } } public static String writeElement(Element element) { if (element == null) { ; } return writeElement(element, "\n"); } public static String writeElement(Element element, String lineSeparator) { if (element == null) { ; } String var10000; try { StringWriter writer = new StringWriter(); writeElement(element, writer, (String) lineSeparator); var10000 = writer.toString(); } catch (IOException var3) { throw new RuntimeException(var3); } if (var10000 == null) { ; } return var10000; } public static Format createFormat(String lineSeparator) { Format var10000 = Format.getCompactFormat() .setIndent(" ") .setTextMode(TextMode.TRIM) .setEncoding("UTF-8") .setOmitEncoding(false) .setOmitDeclaration(false) .setLineSeparator(lineSeparator); if (var10000 == null) { ; } return var10000; } public static XMLOutputter createOutputter(String lineSeparator) { return new JDOMUtil.MyXMLOutputter(createFormat(lineSeparator)); } private static String escapeChar( char c, boolean escapeApostrophes, boolean escapeSpaces, boolean escapeLineEnds) { switch (c) { case '\t': return escapeLineEnds ? "&#9;" : null; case '\n': return escapeLineEnds ? "&#10;" : null; case '\r': return escapeLineEnds ? "&#13;" : null; case ' ': return escapeSpaces ? "&#20" : null; case '"': return "&quot;"; case '&': return "&amp;"; case '\'': return escapeApostrophes ? "&apos;" : null; case '<': return "&lt;"; case '>': return "&gt;"; default: return null; } } public static String escapeText(String text, boolean escapeSpaces, boolean escapeLineEnds) { if (text == null) { ; } return escapeText(text, false, escapeSpaces, escapeLineEnds); } public static String escapeText( String text, boolean escapeApostrophes, boolean escapeSpaces, boolean escapeLineEnds) { if (text == null) { ; } StringBuilder buffer = null; for (int i = 0; i < text.length(); ++i) { char ch = text.charAt(i); String quotation = escapeChar(ch, escapeApostrophes, escapeSpaces, escapeLineEnds); buffer = XmlStringUtil.appendEscapedSymbol(text, buffer, i, quotation, ch); } String var10000 = buffer == null ? text : buffer.toString(); if (var10000 == null) { ; } return var10000; } private static void printDiagnostics(Element element, String prefix) { if (element == null) { ; } JDOMUtil.ElementInfo info = getElementInfo(element); prefix = prefix + "/" + info.name; if (info.hasNullAttributes) { System.err.println(prefix); } Iterator var3 = element.getChildren().iterator(); while (var3.hasNext()) { Element child = (Element) var3.next(); printDiagnostics(child, prefix); } } private static JDOMUtil.ElementInfo getElementInfo(Element element) { if (element == null) { ; } boolean hasNullAttributes = false; StringBuilder buf = new StringBuilder(element.getName()); List<Attribute> attributes = getAttributes(element); int length = attributes.size(); if (length > 0) { buf.append("["); for (int idx = 0; idx < length; ++idx) { Attribute attr = (Attribute) attributes.get(idx); if (idx != 0) { buf.append(";"); } buf.append(attr.getName()); buf.append("="); buf.append(attr.getValue()); if (attr.getValue() == null) { hasNullAttributes = true; } } buf.append("]"); } return new JDOMUtil.ElementInfo(buf, hasNullAttributes); } public static boolean isEmpty(Element element) { return element == null || !element.hasAttributes() && element.getContent().isEmpty(); } public static List<Attribute> getAttributes(Element e) { if (e == null) { ; } List var10000 = e.hasAttributes() ? e.getAttributes() : Collections.emptyList(); if (var10000 == null) { ; } return var10000; } private static class ElementInfo { final CharSequence name; final boolean hasNullAttributes; private ElementInfo(CharSequence name, boolean attributes) { this.name = name; this.hasNullAttributes = attributes; } } private static final class MyXMLOutputter extends XMLOutputter { MyXMLOutputter(Format format) { super(format); } public String escapeAttributeEntities(String str) { if (str == null) {} String var10000 = JDOMUtil.escapeText(str, false, true); if (var10000 == null) {} return var10000; } public String escapeElementEntities(String str) { if (str == null) {} String var10000 = JDOMUtil.escapeText(str, false, false); if (var10000 == null) {} return var10000; } } private static final class EmptyTextFilter implements Filter<Content> { private EmptyTextFilter() {} public boolean matches(Object obj) { return !(obj instanceof Text) || !CharArrayUtil.containsOnlyWhiteSpaces(((Text) obj).getText()); } } private static class LoggerHolder { private static final Logger ourLogger = Logger.getInstance(JDOMUtil.class); } }
11,605
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
AugmentProvider.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/kotlinc/src/main/java/org/jetbrains/kotlin/com/intellij/psi/augment/AugmentProvider.java
package org.jetbrains.kotlin.com.intellij.psi.augment; public class AugmentProvider extends PsiAugmentProvider { public AugmentProvider() {} }
147
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
DescriptorLoadingContext.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/kotlinc/src/main/java/org/jetbrains/kotlin/com/intellij/ide/plugins/DescriptorLoadingContext.java
// // Source code recreated from a .class file by IntelliJ IDEA // (powered by FernFlower decompiler) // package org.jetbrains.kotlin.com.intellij.ide.plugins; import com.github.marschall.com.sun.nio.zipfs.ZipFileSystemProvider; import gnu.trove.THashMap; import java.io.IOException; import java.nio.file.FileSystem; import java.nio.file.Path; import java.util.Collections; import java.util.Map; /** * I have modified this class to use {@link com.github.marschall.com.sun.nio.zipfs.ZipFileSystem} * because android doesn't provide a ZipFileSystem */ final class DescriptorLoadingContext implements AutoCloseable { private final Map<Path, FileSystem> openedFiles = new THashMap<>(); final DescriptorListLoadingContext parentContext; final boolean isBundled; final boolean isEssential; final PathBasedJdomXIncluder.PathResolver<?> pathResolver; /** * parentContext is null only for CoreApplicationEnvironment - it is not valid otherwise because * in this case XML is not interned. */ DescriptorLoadingContext( DescriptorListLoadingContext parentContext, boolean isBundled, boolean isEssential, PathBasedJdomXIncluder.PathResolver<?> pathResolver) { this.parentContext = parentContext; this.isBundled = isBundled; this.isEssential = isEssential; this.pathResolver = pathResolver; } FileSystem open(Path file) throws IOException { FileSystem result = openedFiles.get(file); if (result == null) { result = new ZipFileSystemProvider().newFileSystem(file, Collections.emptyMap()); openedFiles.put(file, result); } return result; } @Override public void close() { for (FileSystem file : openedFiles.values()) { try { file.close(); } catch (IOException ignore) { } } } public DescriptorLoadingContext copy(boolean isEssential) { return new DescriptorLoadingContext(parentContext, isBundled, isEssential, pathResolver); } }
1,970
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
ReadMostlyRWLock.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/kotlinc/src/main/java/org/jetbrains/kotlin/com/intellij/util/ReadMostlyRWLock.java
package org.jetbrains.kotlin.com.intellij.util; import androidx.annotation.NonNull; import androidx.annotation.VisibleForTesting; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.LockSupport; import org.jetbrains.kotlin.com.intellij.openapi.progress.ProcessCanceledException; import org.jetbrains.kotlin.com.intellij.openapi.progress.ProgressIndicator; import org.jetbrains.kotlin.com.intellij.openapi.progress.ProgressIndicatorProvider; import org.jetbrains.kotlin.com.intellij.openapi.progress.ProgressManager; import org.jetbrains.kotlin.com.intellij.openapi.progress.impl.CoreProgressManager; import org.jetbrains.kotlin.com.intellij.util.containers.ConcurrentList; import org.jetbrains.kotlin.com.intellij.util.containers.ContainerUtil; public final class ReadMostlyRWLock { @NonNull final Thread writeThread; @VisibleForTesting volatile boolean writeRequested; private final AtomicBoolean writeIntent = new AtomicBoolean(false); private volatile boolean writeAcquired; private final ConcurrentList<Reader> readers = ContainerUtil.createConcurrentList(); private volatile boolean writeSuspended; private volatile long deadReadersGCStamp; public ReadMostlyRWLock(@NonNull Thread writeThread) { this.writeThread = writeThread; } public static class Reader { @NonNull private final Thread thread; volatile boolean readRequested; private volatile boolean blocked; private volatile boolean impatientReads; Reader(@NonNull Thread readerThread) { thread = readerThread; } @Override public String toString() { return "Reader{" + "thread=" + thread + ", readRequested=" + readRequested + ", " + "blocked=" + blocked + ", impatientReads=" + impatientReads + '}'; } } private final ThreadLocal<Reader> R = ThreadLocal.withInitial( () -> { Reader status = new Reader(Thread.currentThread()); boolean added = readers.addIfAbsent(status); assert added : readers + "; " + Thread.currentThread(); return status; }); public boolean isWriteThread() { return Thread.currentThread() == writeThread; } public boolean isReadLockedByThisThread() { checkReadThreadAccess(); Reader status = R.get(); return status.readRequested; } public Reader startRead() { if (Thread.currentThread() == writeThread) return null; Reader status = R.get(); throwIfImpatient(status); if (status.readRequested) return null; if (!tryReadLock(status)) { ProgressIndicator progress = ProgressIndicatorProvider.getGlobalProgressIndicator(); for (int iter = 0; ; iter++) { if (tryReadLock(status)) { break; } if (progress != null && progress.isCanceled() && !ProgressManager.getInstance().isInNonCancelableSection()) { throw new ProcessCanceledException(); } waitABit(status, iter); } } return status; } public Reader startTryRead() { if (Thread.currentThread() == writeThread) return null; Reader status = R.get(); throwIfImpatient(status); if (status.readRequested) return null; tryReadLock(status); return status; } public void endRead(Reader status) { checkReadThreadAccess(); status.readRequested = false; if (writeRequested) { LockSupport.unpark(writeThread); } } private static final int SPIN_TO_WAIT_FOR_LOCK = 100; private void waitABit(Reader status, int iteration) { if (iteration > SPIN_TO_WAIT_FOR_LOCK) { status.blocked = true; try { throwIfImpatient(status); LockSupport.parkNanos(this, 1_000_000); } finally { status.blocked = false; } } else { Thread.yield(); } } public static class CannotRunReadActionException extends RuntimeException {} private void throwIfImpatient(Reader status) throws CannotRunReadActionException { if (status.impatientReads && writeRequested && !ProgressManager.getInstance().isInNonCancelableSection() && CoreProgressManager.ENABLED) { throw new CannotRunReadActionException(); } } public boolean isInImpatientReader() { return R.get().impatientReads; } public void executeByImpatientReader(@NonNull Runnable runnable) throws CannotRunReadActionException { checkReadThreadAccess(); Reader status = R.get(); boolean old = status.impatientReads; try { status.impatientReads = true; runnable.run(); } finally { status.impatientReads = old; } } private boolean tryReadLock(Reader status) { throwIfImpatient(status); if (!writeRequested) { status.readRequested = true; if (!writeRequested) { return true; } status.readRequested = false; } return false; } public void writeIntentLock() { checkWriteThreadAccess(); for (int iter = 0; ; iter++) { if (writeIntent.compareAndSet(false, true)) { assert !writeRequested; assert !writeAcquired; break; } if (iter > SPIN_TO_WAIT_FOR_LOCK) { LockSupport.parkNanos(this, 1_000_000); } else { Thread.yield(); } } } public void writeIntentUnlock() { checkWriteThreadAccess(); assert !writeAcquired; assert !writeRequested; writeIntent.set(false); LockSupport.unpark(writeThread); } public void writeLock() { checkWriteThreadAccess(); assert !writeRequested; assert !writeAcquired; writeRequested = true; for (int iter = 0; ; iter++) { if (areAllReadersIdle()) { writeAcquired = true; break; } if (iter > SPIN_TO_WAIT_FOR_LOCK) { LockSupport.parkNanos(this, 1_000_000); } else { Thread.yield(); } } } public void writeSuspendWhilePumpingIdeEventQueueHopingForTheBest(@NonNull Runnable runnable) { boolean prev = writeSuspended; writeSuspended = true; writeUnlock(); try { runnable.run(); } finally { // cancelActionToBeCancelledBeforeWrite(); writeLock(); writeSuspended = prev; } } public void writeUnlock() { checkWriteThreadAccess(); writeAcquired = false; writeRequested = false; List<Reader> dead; long current = System.nanoTime(); if (current - deadReadersGCStamp > 1_000_000) { dead = new ArrayList<>(readers.size()); deadReadersGCStamp = current; } else { dead = null; } for (Reader reader : readers) { if (reader.blocked) { LockSupport.unpark(reader.thread); } else if (dead != null && !reader.thread.isAlive()) { dead.add(reader); } } if (dead != null) { readers.removeAll(dead); } } private void checkWriteThreadAccess() { if (Thread.currentThread() != writeThread) { throw new IllegalStateException( "Current thread: " + Thread.currentThread() + "; " + "expected: " + writeThread); } } private void checkReadThreadAccess() { if (Thread.currentThread() == writeThread) { throw new IllegalStateException( "Must not start read from the write thread: " + Thread.currentThread()); } } private boolean areAllReadersIdle() { for (Reader reader : readers) { if (reader.readRequested) { return false; } } return true; } public boolean isWriteLocked() { return writeAcquired; } @Override public String toString() { return "ReadMostlyRWLock{" + "writeThread=" + writeThread + ", writeRequested=" + writeRequested + ", writeIntent=" + writeIntent + ", writeAcquired=" + writeAcquired + ", readers=" + readers + ", writeSuspended=" + writeSuspended + ", deadReadersGCStamp=" + deadReadersGCStamp + ", R=" + R + '}'; } }
8,175
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
ConcurrentIntObjectHashMap.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/kotlinc/src/main/java/org/jetbrains/kotlin/com/intellij/util/containers/ConcurrentIntObjectHashMap.java
package org.jetbrains.kotlin.com.intellij.util.containers; // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the // Apache 2.0 license that can be found in the LICENSE file. import androidx.annotation.NonNull; import java.util.Arrays; import java.util.Collection; import java.util.Enumeration; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.concurrent.locks.LockSupport; import sun.misc.Unsafe; /** * Adapted from Doug Lea ConcurrentHashMap (see * http://gee.cs.oswego.edu/dl/concurrency-interest/index.html) to int keys with following * additions/changes: - added hashing strategy argument - added cacheOrGet convenience method - Null * values are NOT allowed * * @author Doug Lea * @param <V> the type of mapped values * @deprecated Use {@link ConcurrentCollectionFactory#createConcurrentIntObjectMap()} instead */ @Deprecated public final class ConcurrentIntObjectHashMap<V> implements ConcurrentIntObjectMap<V> { /** * The largest possible table capacity. This value must be exactly 1<<30 to stay within Java array * allocation and indexing bounds for power of two table sizes, and is further required because * the top two bits of 32bit hash fields are used for control purposes. */ private static final int MAXIMUM_CAPACITY = 1 << 30; /** * The default initial table capacity. Must be a power of 2 (i.e., at least 1) and at most * MAXIMUM_CAPACITY. */ private static final int DEFAULT_CAPACITY = 16; /** The largest possible (non-power of two) array size. Needed by toArray and related methods. */ static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; /** * The bin count threshold for using a tree rather than list for a bin. Bins are converted to * trees when adding an element to a bin with at least this many nodes. The value must be greater * than 2, and should be at least 8 to mesh with assumptions in tree removal about conversion back * to plain bins upon shrinkage. */ static final int TREEIFY_THRESHOLD = 8; /** * The bin count threshold for untreeifying a (split) bin during a resize operation. Should be * less than TREEIFY_THRESHOLD, and at most 6 to mesh with shrinkage detection under removal. */ static final int UNTREEIFY_THRESHOLD = 6; /** * The smallest table capacity for which bins may be treeified. (Otherwise the table is resized if * too many nodes in a bin.) The value should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts * between resizing and treeification thresholds. */ static final int MIN_TREEIFY_CAPACITY = 64; /** * Minimum number of rebinnings per transfer step. Ranges are subdivided to allow multiple resizer * threads. This value serves as a lower bound to avoid resizers encountering excessive memory * contention. The value should be at least DEFAULT_CAPACITY. */ private static final int MIN_TRANSFER_STRIDE = 16; /** * The number of bits used for generation stamp in sizeCtl. Must be at least 6 for 32bit arrays. */ private static final int RESIZE_STAMP_BITS = 16; /** * The maximum number of threads that can help resize. Must fit in 32 - RESIZE_STAMP_BITS bits. */ private static final int MAX_RESIZERS = (1 << (32 - RESIZE_STAMP_BITS)) - 1; /** The bit shift for recording size stamp in sizeCtl. */ private static final int RESIZE_STAMP_SHIFT = 32 - RESIZE_STAMP_BITS; /* * Encodings for Node hash fields. See above for explanation. */ static final int MOVED = -1; // hash for forwarding nodes static final int TREEBIN = -2; // hash for roots of trees static final int RESERVED = -3; // hash for transient reservations static final int HASH_BITS = 0x7fffffff; // usable bits of normal node hash /** Number of CPUS, to place bounds on some sizings */ static final int NCPU = Runtime.getRuntime().availableProcessors(); /* ---------------- Nodes -------------- */ /** * Key-value entry. This class is never exported out as a user-mutable Map.Entry (i.e., one * supporting setValue; see MapEntry below), but can be used for read-only traversals used in bulk * tasks. Subclasses of Node with a negative hash field are special, and contain null keys and * values (but are never exported). Otherwise, keys and vals are never null. */ static class Node<V> implements Entry<V> { final int hash; final int key; volatile V val; volatile Node<V> next; Node(int hash, int key, V val, Node<V> next) { this.hash = hash; this.key = key; this.val = val; this.next = next; } @Override public final int getKey() { return key; } @NonNull @Override public final V getValue() { return val; } @Override public final int hashCode() { return (key ^ val.hashCode()); } @Override public final String toString() { return key + "=" + val; } @Override public final boolean equals(Object o) { Object v; Object u; Entry<?> e; return ((o instanceof Entry) && (e = (Entry<?>) o).getKey() == key && (v = e.getValue()) != null && (v == (u = val) || v.equals(u))); } /** Virtualized support for map.get(); overridden in subclasses. */ Node<V> find(int h, int k) { Node<V> e = this; do { if ((e.key == k)) { return e; } } while ((e = e.next) != null); return null; } } /* ---------------- Static utilities -------------- */ /** * Spreads (XORs) higher bits of hash to lower and also forces top bit to 0. Because the table * uses power-of-two masking, sets of hashes that vary only in bits above the current mask will * always collide. (Among known examples are sets of Float keys holding consecutive whole numbers * in small tables.) So we apply a transform that spreads the impact of higher bits downward. * There is a tradeoff between speed, utility, and quality of bit-spreading. Because many common * sets of hashes are already reasonably distributed (so don't benefit from spreading), and * because we use trees to handle large sets of collisions in bins, we just XOR some shifted bits * in the cheapest possible way to reduce systematic lossage, as well as to incorporate impact of * the highest bits that would otherwise never be used in index calculations because of table * bounds. */ static int spread(int h) { return (h ^ (h >>> 16)) & HASH_BITS; } /** * Returns a power of two table size for the given desired capacity. See Hackers Delight, sec 3.2 */ private static int tableSizeFor(int c) { int n = c - 1; n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16; return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1; } /* ---------------- Table element access -------------- */ /* * Volatile access methods are used for table elements as well as * elements of in-progress next table while resizing. All uses of * the tab arguments must be null checked by callers. All callers * also paranoically precheck that tab's length is not zero (or an * equivalent check), thus ensuring that any index argument taking * the form of a hash value anded with (length - 1) is a valid * index. Note that, to be correct wrt arbitrary concurrency * errors by users, these checks must operate on local variables, * which accounts for some odd-looking inline assignments below. * Note that calls to setTabAt always occur within locked regions, * and so in principle require only release ordering, not * full volatile semantics, but are currently coded as volatile * writes to be conservative. */ @SuppressWarnings("unchecked") static <V> Node<V> tabAt(Node<V>[] tab, int i) { try { Object o = theUnsafe.getObjectVolatile(tab, ((long) i << ASHIFT) + ABASE); return (Node<V>) o; } catch (Throwable throwable) { throw new RuntimeException(throwable); } } static <V> boolean casTabAt(Node<V>[] tab, int i, Node<V> c, Node<V> v) { try { return theUnsafe.compareAndSwapObject(tab, ((long) i << ASHIFT) + ABASE, c, v); } catch (Throwable throwable) { throw new RuntimeException(throwable); } } static <V> void setTabAt(Node<V>[] tab, int i, Node<V> v) { try { theUnsafe.putObjectVolatile((Object) tab, ((long) i << ASHIFT) + ABASE, (Object) v); } catch (Throwable throwable) { throw new RuntimeException(throwable); } } /* ---------------- Fields -------------- */ /** * The array of bins. Lazily initialized upon first insertion. Size is always a power of two. * Accessed directly by iterators. */ transient volatile Node<V>[] table; /** The next table to use; non-null only while resizing. */ private transient volatile Node<V>[] nextTable; /** * Base counter value, used mainly when there is no contention, but also as a fallback during * table initialization races. Updated via CAS. */ @SuppressWarnings("UnusedDeclaration") private transient volatile long baseCount; /** * Table initialization and resizing control. When negative, the table is being initialized or * resized: -1 for initialization, else -(1 + the number of active resizing threads). Otherwise, * when table is null, holds the initial table size to use upon creation, or 0 for default. After * initialization, holds the next element count value upon which to resize the table. */ private transient volatile int sizeCtl; /** The next table index (plus one) to split while resizing. */ private transient volatile int transferIndex; /** Spinlock (locked via CAS) used when resizing and/or creating CounterCells. */ private transient volatile int cellsBusy; /** * A padded cell for distributing counts. Adapted from LongAdder and Striped64. See their internal * docs for explanation. */ static final class CounterCell { volatile long p0; volatile long p1; volatile long p2; volatile long p3; volatile long p4; volatile long p5; volatile long p6; volatile long value; volatile long q0; volatile long q1; volatile long q2; volatile long q3; volatile long q4; volatile long q5; volatile long q6; CounterCell(long x) { value = x; } } /** Table of counter cells. When non-null, size is a power of 2. */ private transient volatile CounterCell[] counterCells; // views private transient ValuesView<V> values; private transient EntrySetView<V> entrySet; /* ---------------- Public operations -------------- */ /** Creates a new, empty map with the default initial table size (16). */ ConcurrentIntObjectHashMap() {} /** * Creates a new, empty map with an initial table size accommodating the specified number of * elements without the need to dynamically resize. * * @param initialCapacity The implementation performs internal sizing to accommodate this many * elements. * @throws IllegalArgumentException if the initial capacity of elements is negative */ ConcurrentIntObjectHashMap(int initialCapacity) { if (initialCapacity < 0) { throw new IllegalArgumentException(); } int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY : tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1)); sizeCtl = cap; } /** * Creates a new, empty map with an initial table size based on the given number of elements * ({@code initialCapacity}) and initial table density ({@code loadFactor}). * * @param initialCapacity the initial capacity. The implementation performs internal sizing to * accommodate this many elements, given the specified load factor. * @param loadFactor the load factor (table density) for establishing the initial table size * @throws IllegalArgumentException if the initial capacity of elements is negative or the load * factor is nonpositive */ ConcurrentIntObjectHashMap(int initialCapacity, float loadFactor) { this(initialCapacity, loadFactor, 1); } /** * Creates a new, empty map with an initial table size based on the given number of elements * ({@code initialCapacity}), table density ({@code loadFactor}), and number of concurrently * updating threads ({@code concurrencyLevel}). * * @param initialCapacity the initial capacity. The implementation performs internal sizing to * accommodate this many elements, given the specified load factor. * @param loadFactor the load factor (table density) for establishing the initial table size * @param concurrencyLevel the estimated number of concurrently updating threads. The * implementation may use this value as a sizing hint. * @throws IllegalArgumentException if the initial capacity is negative or the load factor or * concurrencyLevel are nonpositive */ ConcurrentIntObjectHashMap(int initialCapacity, float loadFactor, int concurrencyLevel) { if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0) { throw new IllegalArgumentException(); } if (initialCapacity < concurrencyLevel) // Use at least as many bins { initialCapacity = concurrencyLevel; // as estimated threads } long size = (long) (1.0 + (long) initialCapacity / loadFactor); int cap = (size >= (long) MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : tableSizeFor((int) size); sizeCtl = cap; } // Original (since JDK1.2) Map methods /** {@inheritDoc} */ @Override public int size() { long n = sumCount(); return ((n < 0L) ? 0 : (n > (long) Integer.MAX_VALUE) ? Integer.MAX_VALUE : (int) n); } /** {@inheritDoc} */ public boolean isEmpty() { return sumCount() <= 0L; // ignore transient negative values } /** * Returns the value to which the specified key is mapped, or {@code null} if this map contains no * mapping for the key. * * <p> * * <p>More formally, if this map contains a mapping from a key {@code k} to a value {@code v} such * that {@code key.equals(k)}, then this method returns {@code v}; otherwise it returns {@code * null}. (There can be at most one such mapping.) */ @Override public V get(int key) { Node<V>[] tab; Node<V> e; Node<V> p; int n, eh; int h = spread(key); if ((tab = table) != null && (n = tab.length) > 0 && (e = tabAt(tab, (n - 1) & h)) != null) { if ((eh = e.hash) == h) { if (e.key == key) { return e.val; } } else if (eh < 0) { return (p = e.find(h, key)) != null ? p.val : null; } while ((e = e.next) != null) { if (e.hash == h && (e.key == key)) { return e.val; } } } return null; } /** * Tests if the specified object is a key in this table. * * @param key possible key * @return {@code true} if and only if the specified object is a key in this table, as determined * by the {@code equals} method; {@code false} otherwise */ public boolean containsKey(int key) { return get(key) != null; } /** * Returns {@code true} if this map maps one or more keys to the specified value. Note: This * method may require a full traversal of the map, and is much slower than method {@code * containsKey}. * * @param value value whose presence in this map is to be tested * @return {@code true} if this map maps one or more keys to the specified value */ public boolean containsValue(@NonNull Object value) { Node<V>[] t; if ((t = table) != null) { Traverser<V> it = new Traverser<>(t, t.length, 0, t.length); for (Node<V> p; (p = it.advance()) != null; ) { V v; if ((v = p.val) == value || (v != null && value.equals(v))) { return true; } } } return false; } /** * Maps the specified key to the specified value in this table. Neither the key nor the value can * be null. * * <p> * * <p>The value can be retrieved by calling the {@code get} method with a key that is equal to the * original key. * * @param key key with which the specified value is to be associated * @param value value to be associated with the specified key * @return the previous value associated with {@code key}, or {@code null} if there was no mapping * for {@code key} */ @Override public V put(int key, @NonNull V value) { return putVal(key, value, false); } /** Implementation for put and putIfAbsent */ V putVal(int key, @NonNull V value, boolean onlyIfAbsent) { int hash = spread(key); int binCount = 0; for (Node<V>[] tab = table; ; ) { Node<V> f; int n, i, fh; if (tab == null || (n = tab.length) == 0) { tab = initTable(); } else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) { if (casTabAt(tab, i, null, new Node<>(hash, key, value, null))) { break; // no lock when adding to empty bin } } else if ((fh = f.hash) == MOVED) { tab = helpTransfer(tab, f); } else { V oldVal = null; synchronized (f) { if (tabAt(tab, i) == f) { if (fh >= 0) { binCount = 1; for (Node<V> e = f; ; ++binCount) { if ((e.key == key)) { oldVal = e.val; if (!onlyIfAbsent) { e.val = value; } break; } Node<V> pred = e; if ((e = e.next) == null) { pred.next = new Node<>(hash, key, value, null); break; } } } else if (f instanceof TreeBin) { Node<V> p; binCount = 2; if ((p = ((TreeBin<V>) f).putTreeVal(hash, key, value)) != null) { oldVal = p.val; if (!onlyIfAbsent) { p.val = value; } } } } } if (binCount != 0) { if (binCount >= TREEIFY_THRESHOLD) { treeifyBin(tab, i); } if (oldVal != null) { return oldVal; } break; } } } addCount(1L, binCount); return null; } /** * Removes the key (and its corresponding value) from this map. This method does nothing if the * key is not in the map. * * @param key the key that needs to be removed * @return the previous value associated with {@code key}, or {@code null} if there was no mapping * for {@code key} */ @Override public V remove(int key) { return replaceNode(key, null, null); } /** * Implementation for the four public remove/replace methods: Replaces node value with v, * conditional upon match of cv if non-null. If resulting value is null, delete. */ V replaceNode(int key, V value, Object cv) { int hash = spread(key); for (Node<V>[] tab = table; ; ) { Node<V> f; int n, i, fh; if (tab == null || (n = tab.length) == 0 || (f = tabAt(tab, i = (n - 1) & hash)) == null) { break; } else if ((fh = f.hash) == MOVED) { tab = helpTransfer(tab, f); } else { V oldVal = null; boolean validated = false; synchronized (f) { if (tabAt(tab, i) == f) { if (fh >= 0) { validated = true; for (Node<V> e = f, pred = null; ; ) { if ((e.key == key)) { V ev = e.val; if (cv == null || cv == ev || (ev != null && cv.equals(ev))) { oldVal = ev; if (value != null) { e.val = value; } else if (pred != null) { pred.next = e.next; } else { setTabAt(tab, i, e.next); } } break; } pred = e; if ((e = e.next) == null) { break; } } } else if (f instanceof TreeBin) { validated = true; TreeBin<V> t = (TreeBin<V>) f; TreeNode<V> r, p; if ((r = t.root) != null && (p = r.findTreeNode(hash, key)) != null) { V pv = p.val; if (cv == null || cv == pv || (pv != null && cv.equals(pv))) { oldVal = pv; if (value != null) { p.val = value; } else if (t.removeTreeNode(p)) { setTabAt(tab, i, untreeify(t.first)); } } } } } } if (validated) { if (oldVal != null) { if (value == null) { addCount(-1L, -1); } return oldVal; } break; } } } return null; } /** Removes all of the mappings from this map. */ public void clear() { long delta = 0L; // negative number of deletions int i = 0; Node<V>[] tab = table; while (tab != null && i < tab.length) { int fh; Node<V> f = tabAt(tab, i); if (f == null) { ++i; } else if ((fh = f.hash) == MOVED) { tab = helpTransfer(tab, f); i = 0; // restart } else { synchronized (f) { if (tabAt(tab, i) == f) { Node<V> p = (fh >= 0 ? f : (f instanceof TreeBin) ? ((TreeBin<V>) f).first : null); while (p != null) { --delta; p = p.next; } setTabAt(tab, i++, null); } } } } if (delta != 0L) { addCount(delta, -1); } } /** * Returns a {@link Collection} view of the values contained in this map. The collection is backed * by the map, so changes to the map are reflected in the collection, and vice-versa. The * collection supports element removal, which removes the corresponding mapping from this map, via * the {@code Iterator.remove}, {@code Collection.remove}, {@code removeAll}, {@code retainAll}, * and {@code clear} operations. It does not support the {@code add} or {@code addAll} operations. * * <p> * * <p>The view's iterators and spliterators are <a href="package-summary.html#Weakly"><i>weakly * consistent</i></a>. * * <p> * * @return the collection view */ @NonNull public Collection<V> values() { ValuesView<V> vs; return (vs = values) != null ? vs : (values = new ValuesView<>(this)); } /** * Returns a {@link Set} view of the mappings contained in this map. The set is backed by the map, * so changes to the map are reflected in the set, and vice-versa. The set supports element * removal, which removes the corresponding mapping from the map, via the {@code Iterator.remove}, * {@code Set.remove}, {@code removeAll}, {@code retainAll}, and {@code clear} operations. * * <p> * * <p>The view's iterators and spliterators are <a href="package-summary.html#Weakly"><i>weakly * consistent</i></a>. * * <p> * * @return the set view */ @Override @NonNull public Set<Entry<V>> entrySet() { EntrySetView<V> es; return (es = entrySet) != null ? es : (entrySet = new EntrySetView<>(this)); } /** * Returns the hash code value for this {@link Map}, i.e., the sum of, for each key-value pair in * the map, {@code key.hashCode() ^ value.hashCode()}. * * @return the hash code value for this map */ @Override public int hashCode() { int h = 0; Node<V>[] t; if ((t = table) != null) { Traverser<V> it = new Traverser<>(t, t.length, 0, t.length); for (Node<V> p; (p = it.advance()) != null; ) { h += p.key ^ p.val.hashCode(); } } return h; } /** * Returns a string representation of this map. The string representation consists of a list of * key-value mappings (in no particular order) enclosed in braces ("{@code {}}"). Adjacent * mappings are separated by the characters {@code ", "} (comma and space). Each key-value mapping * is rendered as the key followed by an equals sign ("{@code =}") followed by the associated * value. * * @return a string representation of this map */ @Override public String toString() { Node<V>[] t; int f = (t = table) == null ? 0 : t.length; Traverser<V> it = new Traverser<>(t, f, 0, f); StringBuilder sb = new StringBuilder(); sb.append('{'); Node<V> p; if ((p = it.advance()) != null) { for (; ; ) { int k = p.key; V v = p.val; sb.append(k); sb.append('='); sb.append(v == this ? "(this Map)" : v); if ((p = it.advance()) == null) { break; } sb.append(',').append(' '); } } return sb.append('}').toString(); } /** * Compares the specified object with this map for equality. Returns {@code true} if the given * object is a map with the same mappings as this map. This operation may return misleading * results if either map is concurrently modified during execution of this method. * * @param o object to be compared for equality with this map * @return {@code true} if the specified object is equal to this map */ @Override public boolean equals(Object o) { if (o != this) { if (!(o instanceof ConcurrentIntObjectMap)) { return false; } IntObjectMap<?> m = (IntObjectMap) o; Node<V>[] t; int f = (t = table) == null ? 0 : t.length; Traverser<V> it = new Traverser<>(t, f, 0, f); for (Node<V> p; (p = it.advance()) != null; ) { V val = p.val; Object v = m.get(p.key); if (v == null || (v != val && !v.equals(val))) { return false; } } for (Entry e : m.entrySet()) { int mk = e.getKey(); Object mv; Object v; if ((mv = e.getValue()) == null || (v = get(mk)) == null || (mv != v && !mv.equals(v))) { return false; } } } return true; } // ConcurrentMap methods /** * {@inheritDoc} * * @return the previous value associated with the specified key, or {@code null} if there was no * mapping for the key */ @Override public V putIfAbsent(int key, @NonNull V value) { return putVal(key, value, true); } /** {@inheritDoc} */ @Override public boolean remove(int key, @NonNull Object value) { return replaceNode(key, null, value) != null; } /** {@inheritDoc} */ @Override public boolean replace(int key, @NonNull V oldValue, @NonNull V newValue) { return replaceNode(key, newValue, oldValue) != null; } /** * {@inheritDoc} * * @return the previous value associated with the specified key, or {@code null} if there was no * mapping for the key */ public V replace(int key, @NonNull V value) { return replaceNode(key, value, null); } // Overrides of JDK8+ Map extension method defaults /** * Returns the value to which the specified key is mapped, or the given default value if this map * contains no mapping for the key. * * @param key the key whose associated value is to be returned * @param defaultValue the value to return if this map contains no mapping for the given key * @return the mapping for the key, if present; else the default value */ public V getOrDefault(int key, V defaultValue) { V v; return (v = get(key)) == null ? defaultValue : v; } // Hashtable legacy methods /** * Legacy method testing if some key maps into the specified value in this table. This method is * identical in functionality to {@link #containsValue(Object)}, and exists solely to ensure full * compatibility with class {@link Hashtable}, which supported this method prior to introduction * of the Java Collections framework. * * @param value a value to search for * @return {@code true} if and only if some key maps to the {@code value} argument in this table * as determined by the {@code equals} method; {@code false} otherwise */ public boolean contains(Object value) { return containsValue(value); } /** * Returns an enumeration of the keys in this table. * * @return an enumeration of the keys in this table */ public int[] keys() { Object[] entries = new EntrySetView<>(this).toArray(); int[] result = new int[entries.length]; for (int i = 0; i < entries.length; i++) { Entry<V> entry = (Entry<V>) entries[i]; result[i] = entry.getKey(); } return result; } /** * Returns an enumeration of the values in this table. * * @return an enumeration of the values in this table * @see #values() */ @NonNull @Override public Enumeration<V> elements() { Node<V>[] t; int f = (t = table) == null ? 0 : t.length; return new ValueIterator<>(t, f, 0, f, this); } // ConcurrentHashMap-only methods /** * Returns the number of mappings. This method should be used instead of {@link #size} because a * ConcurrentHashMap may contain more mappings than can be represented as an int. The value * returned is an estimate; the actual count may differ if there are concurrent insertions or * removals. * * @return the number of mappings */ public long mappingCount() { long n = sumCount(); return Math.max(n, 0L); // ignore transient negative values } /* ---------------- Special Nodes -------------- */ /** A node inserted at head of bins during transfer operations. */ static final class ForwardingNode<V> extends Node<V> { final Node<V>[] nextTable; ForwardingNode(Node<V>[] tab) { super(MOVED, 0, null, null); nextTable = tab; } @Override Node<V> find(int h, int k) { // loop to avoid arbitrarily deep recursion on forwarding nodes outer: for (Node<V>[] tab = nextTable; ; ) { Node<V> e; int n; if (tab == null || (n = tab.length) == 0 || (e = tabAt(tab, (n - 1) & h)) == null) { return null; } for (; ; ) { if ((e.key == k)) { return e; } if (e.hash < 0) { if (e instanceof ForwardingNode) { tab = ((ForwardingNode<V>) e).nextTable; continue outer; } else { return e.find(h, k); } } if ((e = e.next) == null) { return null; } } } } } /* ---------------- Table Initialization and Resizing -------------- */ /** * Returns the stamp bits for resizing a table of size n. Must be negative when shifted left by * RESIZE_STAMP_SHIFT. */ static int resizeStamp(int n) { return Integer.numberOfLeadingZeros(n) | (1 << (RESIZE_STAMP_BITS - 1)); } /** Initializes table, using the size recorded in sizeCtl. */ private Node<V>[] initTable() { Node<V>[] tab; int sc; while ((tab = table) == null || tab.length == 0) { if ((sc = sizeCtl) < 0) { Thread.yield(); // lost initialization race; just spin } else if (compareAndSwapInt(this, SIZECTL, sc, -1)) { try { if ((tab = table) == null || tab.length == 0) { int n = (sc > 0) ? sc : DEFAULT_CAPACITY; @SuppressWarnings("unchecked") Node<V>[] nt = (Node<V>[]) new Node<?>[n]; table = tab = nt; sc = n - (n >>> 2); } } finally { sizeCtl = sc; } break; } } return tab; } /** * Adds to count, and if table is too small and not already resizing, initiates transfer. If * already resizing, helps perform transfer if work is available. Rechecks occupancy after a * transfer to see if another resize is already needed because resizings are lagging additions. * * @param x the count to add * @param check if <0, don't check resize, if <= 1 only check if uncontended */ private void addCount(long x, int check) { CounterCell[] as; long b, s; if ((as = counterCells) != null || !compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) { CounterCell a; long v; int m; boolean uncontended = true; if (as == null || (m = as.length - 1) < 0 || (a = as[ThreadLocalRandom.getProbe() & m]) == null || !(uncontended = compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))) { fullAddCount(x, uncontended); return; } if (check <= 1) { return; } s = sumCount(); } if (check >= 0) { Node<V>[] tab, nt; int n, sc; while (s >= (long) (sc = sizeCtl) && (tab = table) != null && (n = tab.length) < MAXIMUM_CAPACITY) { int rs = resizeStamp(n); if (sc < 0) { if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 || sc == rs + MAX_RESIZERS || (nt = nextTable) == null || transferIndex <= 0) { break; } if (compareAndSwapInt(this, SIZECTL, sc, sc + 1)) { transfer(tab, nt); } } else if (compareAndSwapInt(this, SIZECTL, sc, (rs << RESIZE_STAMP_SHIFT) + 2)) { transfer(tab, null); } s = sumCount(); } } } /** Helps transfer if a resize is in progress. */ Node<V>[] helpTransfer(Node<V>[] tab, Node<V> f) { Node<V>[] nextTab; int sc; if (tab != null && (f instanceof ForwardingNode) && (nextTab = ((ForwardingNode<V>) f).nextTable) != null) { int rs = resizeStamp(tab.length); while (nextTab == nextTable && table == tab && (sc = sizeCtl) < 0) { if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 || sc == rs + MAX_RESIZERS || transferIndex <= 0) { break; } if (compareAndSwapInt(this, SIZECTL, sc, sc + 1)) { transfer(tab, nextTab); break; } } return nextTab; } return table; } /** * Tries to presize table to accommodate the given number of elements. * * @param size number of elements (doesn't need to be perfectly accurate) */ private void tryPresize(int size) { int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY : tableSizeFor(size + (size >>> 1) + 1); int sc; while ((sc = sizeCtl) >= 0) { Node<V>[] tab = table; int n; if (tab == null || (n = tab.length) == 0) { n = Math.max(sc, c); if (compareAndSwapInt(this, SIZECTL, sc, -1)) { try { if (table == tab) { @SuppressWarnings("unchecked") Node<V>[] nt = (Node<V>[]) new Node<?>[n]; table = nt; sc = n - (n >>> 2); } } finally { sizeCtl = sc; } } } else if (c <= sc || n >= MAXIMUM_CAPACITY) { break; } else if (tab == table) { int rs = resizeStamp(n); if (sc < 0) { Node<V>[] nt; if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 || sc == rs + MAX_RESIZERS || (nt = nextTable) == null || transferIndex <= 0) { break; } if (compareAndSwapInt(this, SIZECTL, sc, sc + 1)) { transfer(tab, nt); } } else if (compareAndSwapInt(this, SIZECTL, sc, (rs << RESIZE_STAMP_SHIFT) + 2)) { transfer(tab, null); } } } } /** Moves and/or copies the nodes in each bin to new table. See above for explanation. */ private void transfer(Node<V>[] tab, Node<V>[] nextTab) { int n = tab.length, stride; if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE) { stride = MIN_TRANSFER_STRIDE; // subdivide range } if (nextTab == null) { // initiating try { @SuppressWarnings("unchecked") Node<V>[] nt = (Node<V>[]) new Node<?>[n << 1]; nextTab = nt; } catch (Throwable ex) { // try to cope with OOME sizeCtl = Integer.MAX_VALUE; return; } nextTable = nextTab; transferIndex = n; } int nextn = nextTab.length; ForwardingNode<V> fwd = new ForwardingNode<>(nextTab); boolean advance = true; boolean finishing = false; // to ensure sweep before committing nextTab for (int i = 0, bound = 0; ; ) { Node<V> f; int fh; while (advance) { int nextIndex, nextBound; if (--i >= bound || finishing) { advance = false; } else if ((nextIndex = transferIndex) <= 0) { i = -1; advance = false; } else if (compareAndSwapInt( this, TRANSFERINDEX, nextIndex, nextBound = (nextIndex > stride ? nextIndex - stride : 0))) { bound = nextBound; i = nextIndex - 1; advance = false; } } if (i < 0 || i >= n || i + n >= nextn) { int sc; if (finishing) { nextTable = null; table = nextTab; sizeCtl = (n << 1) - (n >>> 1); return; } if (compareAndSwapInt(this, SIZECTL, sc = sizeCtl, sc - 1)) { if ((sc - 2) != resizeStamp(n) << RESIZE_STAMP_SHIFT) { return; } finishing = advance = true; i = n; // recheck before commit } } else if ((f = tabAt(tab, i)) == null) { advance = casTabAt(tab, i, null, fwd); } else if ((fh = f.hash) == MOVED) { advance = true; // already processed } else { synchronized (f) { if (tabAt(tab, i) == f) { Node<V> ln, hn; if (fh >= 0) { int runBit = fh & n; Node<V> lastRun = f; for (Node<V> p = f.next; p != null; p = p.next) { int b = p.hash & n; if (b != runBit) { runBit = b; lastRun = p; } } if (runBit == 0) { ln = lastRun; hn = null; } else { hn = lastRun; ln = null; } for (Node<V> p = f; p != lastRun; p = p.next) { int ph = p.hash; int pk = p.key; V pv = p.val; if ((ph & n) == 0) { ln = new Node<>(ph, pk, pv, ln); } else { hn = new Node<>(ph, pk, pv, hn); } } setTabAt(nextTab, i, ln); setTabAt(nextTab, i + n, hn); setTabAt(tab, i, fwd); advance = true; } else if (f instanceof TreeBin) { TreeBin<V> t = (TreeBin<V>) f; TreeNode<V> lo = null, loTail = null; TreeNode<V> hi = null, hiTail = null; int lc = 0, hc = 0; for (Node<V> e = t.first; e != null; e = e.next) { int h = e.hash; TreeNode<V> p = new TreeNode<>(h, e.key, e.val, null, null); if ((h & n) == 0) { if ((p.prev = loTail) == null) { lo = p; } else { loTail.next = p; } loTail = p; ++lc; } else { if ((p.prev = hiTail) == null) { hi = p; } else { hiTail.next = p; } hiTail = p; ++hc; } } ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) : (hc != 0) ? new TreeBin<>(lo) : t; hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) : (lc != 0) ? new TreeBin<>(hi) : t; setTabAt(nextTab, i, ln); setTabAt(nextTab, i + n, hn); setTabAt(tab, i, fwd); advance = true; } } } } } } /* ---------------- Counter support -------------- */ long sumCount() { CounterCell[] as = counterCells; CounterCell a; long sum = baseCount; if (as != null) { for (int i = 0; i < as.length; ++i) { if ((a = as[i]) != null) { sum += a.value; } } } return sum; } // See LongAdder version for explanation private void fullAddCount(long x, boolean wasUncontended) { int h; if ((h = ThreadLocalRandom.getProbe()) == 0) { ThreadLocalRandom.localInit(); // force initialization h = ThreadLocalRandom.getProbe(); wasUncontended = true; } boolean collide = false; // True if last slot nonempty for (; ; ) { CounterCell[] as; CounterCell a; int n; long v; if ((as = counterCells) != null && (n = as.length) > 0) { if ((a = as[(n - 1) & h]) == null) { if (cellsBusy == 0) { // Try to attach new Cell CounterCell r = new CounterCell(x); // Optimistic create if (cellsBusy == 0 && compareAndSwapInt(this, CELLSBUSY, 0, 1)) { boolean created = false; try { // Recheck under lock CounterCell[] rs; int m, j; if ((rs = counterCells) != null && (m = rs.length) > 0 && rs[j = (m - 1) & h] == null) { rs[j] = r; created = true; } } finally { cellsBusy = 0; } if (created) { break; } continue; // Slot is now non-empty } } collide = false; } else if (!wasUncontended) // CAS already known to fail { wasUncontended = true; // Continue after rehash } else if (compareAndSwapLong(a, CELLVALUE, v = a.value, v + x)) { break; } else if (counterCells != as || n >= NCPU) { collide = false; // At max size or stale } else if (!collide) { collide = true; } else if (cellsBusy == 0 && compareAndSwapInt(this, CELLSBUSY, 0, 1)) { try { if (counterCells == as) { // Expand table unless stale CounterCell[] rs = new CounterCell[n << 1]; for (int i = 0; i < n; ++i) { rs[i] = as[i]; } counterCells = rs; } } finally { cellsBusy = 0; } collide = false; continue; // Retry with expanded table } h = ThreadLocalRandom.advanceProbe(h); } else if (cellsBusy == 0 && counterCells == as && compareAndSwapInt(this, CELLSBUSY, 0, 1)) { boolean init = false; try { // Initialize table if (counterCells == as) { CounterCell[] rs = new CounterCell[2]; rs[h & 1] = new CounterCell(x); counterCells = rs; init = true; } } finally { cellsBusy = 0; } if (init) { break; } } else if (compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x)) { break; // Fall back on using base } } } /* ---------------- Conversion from/to TreeBins -------------- */ /** * Replaces all linked nodes in bin at given index unless table is too small, in which case * resizes instead. */ private void treeifyBin(Node<V>[] tab, int index) { Node<V> b; int n, sc; if (tab != null) { if ((n = tab.length) < MIN_TREEIFY_CAPACITY) { tryPresize(n << 1); } else if ((b = tabAt(tab, index)) != null && b.hash >= 0) { synchronized (b) { if (tabAt(tab, index) == b) { TreeNode<V> hd = null, tl = null; for (Node<V> e = b; e != null; e = e.next) { TreeNode<V> p = new TreeNode<>(e.hash, e.key, e.val, null, null); if ((p.prev = tl) == null) { hd = p; } else { tl.next = p; } tl = p; } setTabAt(tab, index, new TreeBin<>(hd)); } } } } } /** Returns a list on non-TreeNodes replacing those in given list. */ static <V> Node<V> untreeify(Node<V> b) { Node<V> hd = null, tl = null; for (Node<V> q = b; q != null; q = q.next) { Node<V> p = new Node<>(q.hash, q.key, q.val, null); if (tl == null) { hd = p; } else { tl.next = p; } tl = p; } return hd; } /* ---------------- TreeNodes -------------- */ /** Nodes for use in TreeBins */ static final class TreeNode<V> extends Node<V> { TreeNode<V> parent; // red-black tree links TreeNode<V> left; TreeNode<V> right; TreeNode<V> prev; // needed to unlink next upon deletion boolean red; TreeNode(int hash, int key, V val, Node<V> next, TreeNode<V> parent) { super(hash, key, val, next); this.parent = parent; } @Override Node<V> find(int h, int k) { return findTreeNode(h, k); } /** Returns the TreeNode (or null if not found) for the given key starting at given root. */ TreeNode<V> findTreeNode(int h, int k) { TreeNode<V> p = this; do { int ph; TreeNode<V> q; TreeNode<V> pl = p.left; TreeNode<V> pr = p.right; if ((ph = p.hash) > h) { p = pl; } else if (ph < h) { p = pr; } else if (p.key == k) { return p; } else if (pl == null) { p = pr; } else if (pr == null) { p = pl; } else if ((q = pr.findTreeNode(h, k)) != null) { return q; } else { p = pl; } } while (p != null); return null; } } /* ---------------- TreeBins -------------- */ /** * TreeNodes used at the heads of bins. TreeBins do not hold user keys or values, but instead * point to list of TreeNodes and their root. They also maintain a parasitic read-write lock * forcing writers (who hold bin lock) to wait for readers (who do not) to complete before tree * restructuring operations. */ static final class TreeBin<V> extends Node<V> { TreeNode<V> root; volatile TreeNode<V> first; volatile Thread waiter; volatile int lockState; // values for lockState static final int WRITER = 1; // set while holding write lock static final int WAITER = 2; // set when waiting for write lock static final int READER = 4; // increment value for setting read lock /** Creates bin with initial set of nodes headed by b. */ TreeBin(TreeNode<V> b) { super(TREEBIN, 0, null, null); first = b; TreeNode<V> r = null; for (TreeNode<V> x = b, next; x != null; x = next) { next = (TreeNode<V>) x.next; x.left = x.right = null; if (r == null) { x.parent = null; x.red = false; r = x; } else { int h = x.hash; for (TreeNode<V> p = r; ; ) { int dir, ph; if ((ph = p.hash) > h) { dir = -1; } else if (ph < h) { dir = 1; } else { dir = 0; } TreeNode<V> xp = p; if ((p = (dir <= 0) ? p.left : p.right) == null) { x.parent = xp; if (dir <= 0) { xp.left = x; } else { xp.right = x; } r = balanceInsertion(r, x); break; } } } } root = r; assert checkInvariants(root); } /** Acquires write lock for tree restructuring. */ private void lockRoot() { if (!compareAndSwapInt(this, LOCKSTATE, 0, WRITER)) { contendedLock(); // offload to separate method } } /** Releases write lock for tree restructuring. */ private void unlockRoot() { lockState = 0; } /** Possibly blocks awaiting root lock. */ private void contendedLock() { boolean waiting = false; for (int s; ; ) { if (((s = lockState) & ~WAITER) == 0) { if (compareAndSwapInt(this, LOCKSTATE, s, WRITER)) { if (waiting) { waiter = null; } return; } } else if ((s & WAITER) == 0) { if (compareAndSwapInt(this, LOCKSTATE, s, s | WAITER)) { waiting = true; waiter = Thread.currentThread(); } } else if (waiting) { LockSupport.park(this); } } } /** * Returns matching node or null if none. Tries to search using tree comparisons from root, but * continues linear search when lock not available. */ @Override Node<V> find(int h, int k) { for (Node<V> e = first; e != null; ) { int s; if (((s = lockState) & (WAITER | WRITER)) != 0) { if ((e.key == k)) { return e; } e = e.next; } else if (compareAndSwapInt(this, LOCKSTATE, s, s + READER)) { TreeNode<V> r; TreeNode<V> p; try { p = ((r = root) == null ? null : r.findTreeNode(h, k)); } finally { Thread w; if (getAndAddInt(this, LOCKSTATE, -READER) == (READER | WAITER) && (w = waiter) != null) { LockSupport.unpark(w); } } return p; } } return null; } private static int getAndAddInt(Object object, long offset, int v) { try { return theUnsafe.getAndAddInt(object, offset, v); } catch (Throwable t) { throw new RuntimeException(t); } } /** * Finds or adds a node. * * @return null if added */ TreeNode<V> putTreeVal(int h, int k, V v) { boolean searched = false; for (TreeNode<V> p = root; ; ) { int dir, ph; if (p == null) { first = root = new TreeNode<>(h, k, v, null, null); break; } else if ((ph = p.hash) > h) { dir = -1; } else if (ph < h) { dir = 1; } else if (p.key == k) { return p; } else { if (!searched) { TreeNode<V> q, ch; searched = true; if (((ch = p.left) != null && (q = ch.findTreeNode(h, k)) != null) || ((ch = p.right) != null && (q = ch.findTreeNode(h, k)) != null)) { return q; } } dir = 0; } TreeNode<V> xp = p; if ((p = (dir <= 0) ? p.left : p.right) == null) { TreeNode<V> x, f = first; first = x = new TreeNode<>(h, k, v, f, xp); if (f != null) { f.prev = x; } if (dir <= 0) { xp.left = x; } else { xp.right = x; } if (!xp.red) { x.red = true; } else { lockRoot(); try { root = balanceInsertion(root, x); } finally { unlockRoot(); } } break; } } assert checkInvariants(root); return null; } /** * Removes the given node, that must be present before this call. This is messier than typical * red-black deletion code because we cannot swap the contents of an interior node with a leaf * successor that is pinned by "next" pointers that are accessible independently of lock. So * instead we swap the tree linkages. * * @return true if now too small, so should be untreeified */ boolean removeTreeNode(TreeNode<V> p) { TreeNode<V> next = (TreeNode<V>) p.next; TreeNode<V> pred = p.prev; // unlink traversal pointers TreeNode<V> r, rl; if (pred == null) { first = next; } else { pred.next = next; } if (next != null) { next.prev = pred; } if (first == null) { root = null; return true; } if ((r = root) == null || r.right == null || // too small (rl = r.left) == null || rl.left == null) { return true; } lockRoot(); try { TreeNode<V> replacement; TreeNode<V> pl = p.left; TreeNode<V> pr = p.right; if (pl != null && pr != null) { TreeNode<V> s = pr, sl; while ((sl = s.left) != null) // find successor { s = sl; } boolean c = s.red; s.red = p.red; p.red = c; // swap colors TreeNode<V> sr = s.right; TreeNode<V> pp = p.parent; if (s == pr) { // p was s's direct parent p.parent = s; s.right = p; } else { TreeNode<V> sp = s.parent; if ((p.parent = sp) != null) { if (s == sp.left) { sp.left = p; } else { sp.right = p; } } if ((s.right = pr) != null) { pr.parent = s; } } p.left = null; if ((p.right = sr) != null) { sr.parent = p; } if ((s.left = pl) != null) { pl.parent = s; } if ((s.parent = pp) == null) { r = s; } else if (p == pp.left) { pp.left = s; } else { pp.right = s; } if (sr != null) { replacement = sr; } else { replacement = p; } } else if (pl != null) { replacement = pl; } else if (pr != null) { replacement = pr; } else { replacement = p; } if (replacement != p) { TreeNode<V> pp = replacement.parent = p.parent; if (pp == null) { r = replacement; } else if (p == pp.left) { pp.left = replacement; } else { pp.right = replacement; } p.left = p.right = p.parent = null; } root = (p.red) ? r : balanceDeletion(r, replacement); if (p == replacement) { // detach pointers TreeNode<V> pp; if ((pp = p.parent) != null) { if (p == pp.left) { pp.left = null; } else if (p == pp.right) { pp.right = null; } p.parent = null; } } } finally { unlockRoot(); } assert checkInvariants(root); return false; } /* ------------------------------------------------------------ */ // Red-black tree methods, all adapted from CLR static <V> TreeNode<V> rotateLeft(TreeNode<V> root, TreeNode<V> p) { TreeNode<V> r, pp, rl; if (p != null && (r = p.right) != null) { if ((rl = p.right = r.left) != null) { rl.parent = p; } if ((pp = r.parent = p.parent) == null) { (root = r).red = false; } else if (pp.left == p) { pp.left = r; } else { pp.right = r; } r.left = p; p.parent = r; } return root; } static <V> TreeNode<V> rotateRight(TreeNode<V> root, TreeNode<V> p) { TreeNode<V> l, pp, lr; if (p != null && (l = p.left) != null) { if ((lr = p.left = l.right) != null) { lr.parent = p; } if ((pp = l.parent = p.parent) == null) { (root = l).red = false; } else if (pp.right == p) { pp.right = l; } else { pp.left = l; } l.right = p; p.parent = l; } return root; } static <V> TreeNode<V> balanceInsertion(TreeNode<V> root, TreeNode<V> x) { x.red = true; for (TreeNode<V> xp, xpp, xppl, xppr; ; ) { if ((xp = x.parent) == null) { x.red = false; return x; } else if (!xp.red || (xpp = xp.parent) == null) { return root; } if (xp == (xppl = xpp.left)) { if ((xppr = xpp.right) != null && xppr.red) { xppr.red = false; xp.red = false; xpp.red = true; x = xpp; } else { if (x == xp.right) { root = rotateLeft(root, x = xp); xpp = (xp = x.parent) == null ? null : xp.parent; } if (xp != null) { xp.red = false; if (xpp != null) { xpp.red = true; root = rotateRight(root, xpp); } } } } else { if (xppl != null && xppl.red) { xppl.red = false; xp.red = false; xpp.red = true; x = xpp; } else { if (x == xp.left) { root = rotateRight(root, x = xp); xpp = (xp = x.parent) == null ? null : xp.parent; } if (xp != null) { xp.red = false; if (xpp != null) { xpp.red = true; root = rotateLeft(root, xpp); } } } } } } static <V> TreeNode<V> balanceDeletion(TreeNode<V> root, TreeNode<V> x) { for (TreeNode<V> xp, xpl, xpr; ; ) { if (x == null || x == root) { return root; } else if ((xp = x.parent) == null) { x.red = false; return x; } else if (x.red) { x.red = false; return root; } else if ((xpl = xp.left) == x) { if ((xpr = xp.right) != null && xpr.red) { xpr.red = false; xp.red = true; root = rotateLeft(root, xp); xpr = (xp = x.parent) == null ? null : xp.right; } if (xpr == null) { x = xp; } else { TreeNode<V> sl = xpr.left, sr = xpr.right; if ((sr == null || !sr.red) && (sl == null || !sl.red)) { xpr.red = true; x = xp; } else { if (sr == null || !sr.red) { if (sl != null) { sl.red = false; } xpr.red = true; root = rotateRight(root, xpr); xpr = (xp = x.parent) == null ? null : xp.right; } if (xpr != null) { xpr.red = (xp == null) ? false : xp.red; if ((sr = xpr.right) != null) { sr.red = false; } } if (xp != null) { xp.red = false; root = rotateLeft(root, xp); } x = root; } } } else { // symmetric if (xpl != null && xpl.red) { xpl.red = false; xp.red = true; root = rotateRight(root, xp); xpl = (xp = x.parent) == null ? null : xp.left; } if (xpl == null) { x = xp; } else { TreeNode<V> sl = xpl.left, sr = xpl.right; if ((sl == null || !sl.red) && (sr == null || !sr.red)) { xpl.red = true; x = xp; } else { if (sl == null || !sl.red) { if (sr != null) { sr.red = false; } xpl.red = true; root = rotateLeft(root, xpl); xpl = (xp = x.parent) == null ? null : xp.left; } if (xpl != null) { xpl.red = (xp == null) ? false : xp.red; if ((sl = xpl.left) != null) { sl.red = false; } } if (xp != null) { xp.red = false; root = rotateRight(root, xp); } x = root; } } } } } /** Recursive invariant check */ static <V> boolean checkInvariants(TreeNode<V> t) { TreeNode<V> tp = t.parent, tl = t.left, tr = t.right, tb = t.prev, tn = (TreeNode<V>) t.next; if (tb != null && tb.next != t) { return false; } if (tn != null && tn.prev != t) { return false; } if (tp != null && t != tp.left && t != tp.right) { return false; } if (tl != null && (tl.parent != t || tl.hash > t.hash)) { return false; } if (tr != null && (tr.parent != t || tr.hash < t.hash)) { return false; } if (t.red && tl != null && tl.red && tr != null && tr.red) { return false; } if (tl != null && !checkInvariants(tl)) { return false; } if (tr != null && !checkInvariants(tr)) { return false; } return true; } private static final long LOCKSTATE; static { try { Unsafe unsafe = UnsafeUtil.findUnsafe(); Class<?> k = TreeBin.class; LOCKSTATE = unsafe.objectFieldOffset(k.getDeclaredField("lockState")); } catch (Throwable t) { throw new Error(t); } } } /* ----------------Table Traversal -------------- */ /** * Records the table, its length, and current traversal index for a traverser that must process a * region of a forwarded table before proceeding with current table. */ static final class TableStack<V> { int length; int index; Node<V>[] tab; TableStack<V> next; } /** * Encapsulates traversal for methods such as containsValue; also serves as a base class for other * iterators and spliterators. * * <p>Method advance visits once each still-valid node that was reachable upon iterator * construction. It might miss some that were added to a bin after the bin was visited, which is * OK wrt consistency guarantees. Maintaining this property in the face of possible ongoing * resizes requires a fair amount of bookkeeping state that is difficult to optimize away amidst * volatile accesses. Even so, traversal maintains reasonable throughput. * * <p>Normally, iteration proceeds bin-by-bin traversing lists. However, if the table has been * resized, then all future steps must traverse both the bin at the current index as well as at * (index + baseSize); and so on for further resizings. To paranoically cope with potential * sharing by users of iterators across threads, iteration terminates if a bounds checks fails for * a table read. */ static class Traverser<V> { Node<V>[] tab; // current table; updated if resized Node<V> next; // the next entry to use TableStack<V> stack; TableStack<V> spare; // to save/restore on ForwardingNodes int index; // index of bin to use next int baseIndex; // current index of initial table int baseLimit; // index bound for initial table final int baseSize; // initial table size Traverser(Node<V>[] tab, int size, int index, int limit) { this.tab = tab; baseSize = size; baseIndex = this.index = index; baseLimit = limit; next = null; } /** Advances if possible, returning next valid node, or null if none. */ final Node<V> advance() { Node<V> e; if ((e = next) != null) { e = e.next; } for (; ; ) { Node<V>[] t; int i; // must use locals in checks int n; if (e != null) { return next = e; } if (baseIndex >= baseLimit || (t = tab) == null || (n = t.length) <= (i = index) || i < 0) { return next = null; } if ((e = tabAt(t, i)) != null && e.hash < 0) { if (e instanceof ForwardingNode) { tab = ((ForwardingNode<V>) e).nextTable; e = null; pushState(t, i, n); continue; } else if (e instanceof TreeBin) { e = ((TreeBin<V>) e).first; } else { e = null; } } if (stack != null) { recoverState(n); } else if ((index = i + baseSize) >= n) { index = ++baseIndex; // visit upper slots if present } } } /** Saves traversal state upon encountering a forwarding node. */ private void pushState(Node<V>[] t, int i, int n) { TableStack<V> s = spare; // reuse if possible if (s != null) { spare = s.next; } else { s = new TableStack<>(); } s.tab = t; s.length = n; s.index = i; s.next = stack; stack = s; } /** * Possibly pops traversal state. * * @param n length of current table */ private void recoverState(int n) { TableStack<V> s; int len; while ((s = stack) != null && (index += (len = s.length)) >= n) { n = len; index = s.index; tab = s.tab; s.tab = null; TableStack<V> next = s.next; s.next = spare; // save for reuse stack = next; spare = s; } if (s == null && (index += baseSize) >= n) { index = ++baseIndex; } } } /** * Base of key, value, and entry Iterators. Adds fields to Traverser to support iterator.remove. */ static class BaseIterator<V> extends Traverser<V> { final ConcurrentIntObjectHashMap<V> map; Node<V> lastReturned; BaseIterator(Node<V>[] tab, int size, int index, int limit, ConcurrentIntObjectHashMap<V> map) { super(tab, size, index, limit); this.map = map; advance(); } public final boolean hasNext() { return next != null; } public final boolean hasMoreElements() { return next != null; } public final void remove() { Node<V> p; if ((p = lastReturned) == null) { throw new IllegalStateException(); } lastReturned = null; // IJ patched: // see https://bugs.java.com/bugdatabase/view_bug.do?bug_id=8078645 map.replaceNode(p.key, null, p.val); } } static final class ValueIterator<V> extends BaseIterator<V> implements Iterator<V>, Enumeration<V> { ValueIterator( Node<V>[] tab, int index, int size, int limit, ConcurrentIntObjectHashMap<V> map) { super(tab, index, size, limit, map); } @Override public V next() { Node<V> p; if ((p = next) == null) { throw new NoSuchElementException(); } V v = p.val; lastReturned = p; advance(); return v; } @Override public V nextElement() { return next(); } } static final class EntryIterator<V> extends BaseIterator<V> implements Iterator<Entry<V>> { EntryIterator( Node<V>[] tab, int index, int size, int limit, ConcurrentIntObjectHashMap<V> map) { super(tab, index, size, limit, map); } @Override public Entry<V> next() { Node<V> p; if ((p = next) == null) { throw new NoSuchElementException(); } final int k = p.key; final V v = p.val; lastReturned = p; advance(); return new SimpleEntry<>(k, v); } } // Parallel bulk operations /* ----------------Views -------------- */ /** Base class for views. */ abstract static class CollectionView<V, E> implements Collection<E> { final ConcurrentIntObjectHashMap<V> map; CollectionView(ConcurrentIntObjectHashMap<V> map) { this.map = map; } /** * Returns the map backing this view. * * @return the map backing this view */ public ConcurrentIntObjectHashMap<V> getMap() { return map; } /** * Removes all of the elements from this view, by removing all the mappings from the map backing * this view. */ @Override public final void clear() { map.clear(); } @Override public final int size() { return map.size(); } @Override public final boolean isEmpty() { return map.isEmpty(); } // implementations below rely on concrete classes supplying these // abstract methods /** * Returns an iterator over the elements in this collection. * * <p> * * <p>The returned iterator is <a href="package-summary.html#Weakly"><i>weakly * consistent</i></a>. * * @return an iterator over the elements in this collection */ @NonNull @Override public abstract Iterator<E> iterator(); @Override public abstract boolean contains(Object o); @Override public abstract boolean remove(Object o); private static final String oomeMsg = "Required array size too large"; @Override public final Object[] toArray() { long sz = map.mappingCount(); if (sz > MAX_ARRAY_SIZE) { throw new OutOfMemoryError(oomeMsg); } int n = (int) sz; Object[] r = new Object[n]; int i = 0; for (E e : this) { if (i == n) { if (n >= MAX_ARRAY_SIZE) { throw new OutOfMemoryError(oomeMsg); } if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1) { n = MAX_ARRAY_SIZE; } else { n += (n >>> 1) + 1; } r = Arrays.copyOf(r, n); } r[i++] = e; } return (i == n) ? r : Arrays.copyOf(r, i); } @Override @SuppressWarnings("unchecked") public final <T> T[] toArray(@NonNull T[] a) { long sz = map.mappingCount(); if (sz > MAX_ARRAY_SIZE) { throw new OutOfMemoryError(oomeMsg); } int m = (int) sz; T[] r = (a.length >= m) ? a : (T[]) java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), m); int n = r.length; int i = 0; for (E e : this) { if (i == n) { if (n >= MAX_ARRAY_SIZE) { throw new OutOfMemoryError(oomeMsg); } if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1) { n = MAX_ARRAY_SIZE; } else { n += (n >>> 1) + 1; } r = Arrays.copyOf(r, n); } r[i++] = (T) e; } if (a == r && i < n) { r[i] = null; // null-terminate return r; } return (i == n) ? r : Arrays.copyOf(r, i); } /** * Returns a string representation of this collection. The string representation consists of the * string representations of the collection's elements in the order they are returned by its * iterator, enclosed in square brackets ({@code "[]"}). Adjacent elements are separated by the * characters {@code ", "} (comma and space). Elements are converted to strings as by {@link * String#valueOf(Object)}. * * @return a string representation of this collection */ @Override public final String toString() { StringBuilder sb = new StringBuilder(); sb.append('['); Iterator<E> it = iterator(); if (it.hasNext()) { for (; ; ) { Object e = it.next(); sb.append(e == this ? "(this Collection)" : e); if (!it.hasNext()) { break; } sb.append(',').append(' '); } } return sb.append(']').toString(); } @Override public final boolean containsAll(@NonNull Collection<?> c) { if (c != this) { for (Object e : c) { if (e == null || !contains(e)) { return false; } } } return true; } @Override public final boolean removeAll(@NonNull Collection<?> c) { boolean modified = false; for (Iterator<E> it = iterator(); it.hasNext(); ) { if (c.contains(it.next())) { it.remove(); modified = true; } } return modified; } @Override public final boolean retainAll(@NonNull Collection<?> c) { boolean modified = false; for (Iterator<E> it = iterator(); it.hasNext(); ) { if (!c.contains(it.next())) { it.remove(); modified = true; } } return modified; } } /** * A view of a ConcurrentHashMap as a {@link Collection} of values, in which additions are * disabled. This class cannot be directly instantiated. See {@link #values()}. */ static final class ValuesView<V> extends CollectionView<V, V> implements Collection<V> { ValuesView(ConcurrentIntObjectHashMap<V> map) { super(map); } @Override public boolean contains(Object o) { return map.containsValue(o); } @Override public boolean remove(Object o) { if (o != null) { for (Iterator<V> it = iterator(); it.hasNext(); ) { if (o.equals(it.next())) { it.remove(); return true; } } } return false; } @NonNull @Override public Iterator<V> iterator() { ConcurrentIntObjectHashMap<V> m = map; Node<V>[] t; int f = (t = m.table) == null ? 0 : t.length; return new ValueIterator<>(t, f, 0, f, m); } @Override public boolean add(V e) { throw new UnsupportedOperationException(); } @Override public boolean addAll(@NonNull Collection<? extends V> c) { throw new UnsupportedOperationException(); } } /** * A view of a ConcurrentHashMap as a {@link Set} of (key, value) entries. This class cannot be * directly instantiated. See {@link #entrySet()}. */ static final class EntrySetView<V> extends CollectionView<V, Entry<V>> implements Set<Entry<V>> { EntrySetView(ConcurrentIntObjectHashMap<V> map) { super(map); } @Override public boolean contains(Object o) { Object v; Object r; Entry<?> e; return ((o instanceof IntObjectMap.Entry) && (r = map.get((e = (Entry) o).getKey())) != null && (v = e.getValue()) != null && (v == r || v.equals(r))); } @Override public boolean remove(Object o) { Object v; Entry<?> e; return ((o instanceof Map.Entry) && (e = (Entry<?>) o) != null && (v = e.getValue()) != null && map.remove(e.getKey(), v)); } /** * @return an iterator over the entries of the backing map */ @NonNull @Override public Iterator<Entry<V>> iterator() { ConcurrentIntObjectHashMap<V> m = map; Node<V>[] t; int f = (t = m.table) == null ? 0 : t.length; return new EntryIterator<>(t, f, 0, f, m); } @Override public boolean add(Entry<V> e) { return map.putVal(e.getKey(), e.getValue(), false) == null; } @Override public boolean addAll(Collection<? extends Entry<V>> c) { boolean added = false; for (Entry<V> e : c) { if (add(e)) { added = true; } } return added; } @Override public int hashCode() { int h = 0; Node<V>[] t; if ((t = map.table) != null) { Traverser<V> it = new Traverser<>(t, t.length, 0, t.length); for (Node<V> p; (p = it.advance()) != null; ) { h += p.hashCode(); } } return h; } @Override public boolean equals(Object o) { Set<?> c; return ((o instanceof Set) && ((c = (Set<?>) o) == this || (containsAll(c) && c.containsAll(this)))); } } // ------------------------------------------------------- // Unsafe mechanics private static final long SIZECTL; private static final long TRANSFERINDEX; private static final long BASECOUNT; private static final long CELLSBUSY; private static final long CELLVALUE; private static final long ABASE; private static final int ASHIFT; private static Unsafe theUnsafe; static { try { theUnsafe = UnsafeUtil.findUnsafe(); Class<?> k = ConcurrentIntObjectHashMap.class; SIZECTL = theUnsafe.objectFieldOffset(k.getDeclaredField("sizeCtl")); TRANSFERINDEX = theUnsafe.objectFieldOffset(k.getDeclaredField("transferIndex")); BASECOUNT = theUnsafe.objectFieldOffset(k.getDeclaredField("baseCount")); CELLSBUSY = theUnsafe.objectFieldOffset(k.getDeclaredField("cellsBusy")); Class<?> ck = CounterCell.class; CELLVALUE = theUnsafe.objectFieldOffset(ck.getDeclaredField("value")); Class<?> ak = Node[].class; ABASE = theUnsafe.arrayBaseOffset(ak); int scale = theUnsafe.arrayIndexScale(ak); if ((scale & (scale - 1)) != 0) { throw new Error("data type scale not a power of two"); } ASHIFT = 31 - Integer.numberOfLeadingZeros(scale); } catch (Throwable e) { throw new RuntimeException(e); } } private static boolean compareAndSwapInt(Object object, long offset, int expected, int value) { try { return theUnsafe.compareAndSwapInt(object, offset, expected, value); } catch (Throwable throwable) { throw new RuntimeException(throwable); } } private static boolean compareAndSwapLong(Object object, long offset, long expected, long value) { try { return theUnsafe.compareAndSwapLong(object, offset, expected, value); } catch (Throwable throwable) { throw new RuntimeException(throwable); } } /** * @return value if there is no entry in the map, or corresponding value if entry already exists */ @Override @NonNull public V cacheOrGet(final int key, @NonNull final V defaultValue) { V v = get(key); if (v != null) return v; V prev = putIfAbsent(key, defaultValue); return prev == null ? defaultValue : prev; } }
78,512
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
ConcurrentLongObjectHashMap.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/kotlinc/src/main/java/org/jetbrains/kotlin/com/intellij/util/containers/ConcurrentLongObjectHashMap.java
package org.jetbrains.kotlin.com.intellij.util.containers; // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the // Apache 2.0 license that can be found in the LICENSE file. import androidx.annotation.NonNull; import java.util.Arrays; import java.util.Collection; import java.util.Enumeration; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.concurrent.locks.LockSupport; import sun.misc.Unsafe; /** * Adapted from Doug Lea ConcurrentHashMap (see * http://gee.cs.oswego.edu/dl/concurrency-interest/index.html) to long keys with following * additions/changes: - added hashing strategy argument - added cacheOrGet convenience method - Null * values are NOT allowed * * @author Doug Lea * @param <V> the type of mapped values * @deprecated Use {@link ConcurrentCollectionFactory#createConcurrentLongObjectMap()} instead */ @Deprecated final class ConcurrentLongObjectHashMap<V> implements ConcurrentLongObjectMap<V> { /* ---------------- Constants -------------- */ /** * The largest possible table capacity. This value must be exactly 1<<30 to stay within Java array * allocation and indexing bounds for power of two table sizes, and is further required because * the top two bits of 32bit hash fields are used for control purposes. */ private static final int MAXIMUM_CAPACITY = 1 << 30; /** * The default initial table capacity. Must be a power of 2 (i.e., at least 1) and at most * MAXIMUM_CAPACITY. */ private static final int DEFAULT_CAPACITY = 16; /** The largest possible (non-power of two) array size. Needed by toArray and related methods. */ static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; /** * The bin count threshold for using a tree rather than list for a bin. Bins are converted to * trees when adding an element to a bin with at least this many nodes. The value must be greater * than 2, and should be at least 8 to mesh with assumptions in tree removal about conversion back * to plain bins upon shrinkage. */ static final int TREEIFY_THRESHOLD = 8; /** * The bin count threshold for untreeifying a (split) bin during a resize operation. Should be * less than TREEIFY_THRESHOLD, and at most 6 to mesh with shrinkage detection under removal. */ static final int UNTREEIFY_THRESHOLD = 6; /** * The smallest table capacity for which bins may be treeified. (Otherwise the table is resized if * too many nodes in a bin.) The value should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts * between resizing and treeification thresholds. */ static final int MIN_TREEIFY_CAPACITY = 64; /** * Minimum number of rebinnings per transfer step. Ranges are subdivided to allow multiple resizer * threads. This value serves as a lower bound to avoid resizers encountering excessive memory * contention. The value should be at least DEFAULT_CAPACITY. */ private static final int MIN_TRANSFER_STRIDE = 16; /** * The number of bits used for generation stamp in sizeCtl. Must be at least 6 for 32bit arrays. */ private static final int RESIZE_STAMP_BITS = 16; /** * The maximum number of threads that can help resize. Must fit in 32 - RESIZE_STAMP_BITS bits. */ private static final int MAX_RESIZERS = (1 << (32 - RESIZE_STAMP_BITS)) - 1; /** The bit shift for recording size stamp in sizeCtl. */ private static final int RESIZE_STAMP_SHIFT = 32 - RESIZE_STAMP_BITS; /* * Encodings for Node hash fields. See above for explanation. */ static final int MOVED = -1; // hash for forwarding nodes static final int TREEBIN = -2; // hash for roots of trees static final int RESERVED = -3; // hash for transient reservations static final int HASH_BITS = 0x7fffffff; // usable bits of normal node hash /** Number of CPUS, to place bounds on some sizings */ static final int NCPU = Runtime.getRuntime().availableProcessors(); /* ---------------- Nodes -------------- */ /** * Key-value entry. This class is never exported out as a user-mutable Map.Entry (i.e., one * supporting setValue; see MapEntry below), but can be used for read-only traversals used in bulk * tasks. Subclasses of Node with a negative hash field are special, and contain null keys and * values (but are never exported). Otherwise, keys and vals are never null. */ static class Node<V> implements LongEntry<V> { final int hash; final long key; volatile V val; volatile Node<V> next; Node(int hash, long key, V val, Node<V> next) { this.hash = hash; this.key = key; this.val = val; this.next = next; } @Override public final long getKey() { return key; } @NonNull @Override public final V getValue() { return val; } @Override public final int hashCode() { return (int) (key ^ val.hashCode()); } @Override public final String toString() { return key + "=" + val; } @Override public final boolean equals(Object o) { Object v; Object u; LongEntry<?> e; return ((o instanceof LongEntry) && (e = (LongEntry<?>) o).getKey() == key && (v = e.getValue()) != null && (v == (u = val) || v.equals(u))); } /** Virtualized support for map.get(); overridden in subclasses. */ Node<V> find(int h, long k) { Node<V> e = this; do { if ((e.key == k)) { return e; } } while ((e = e.next) != null); return null; } } /* ---------------- Static utilities -------------- */ /** * Spreads (XORs) higher bits of hash to lower and also forces top bit to 0. Because the table * uses power-of-two masking, sets of hashes that vary only in bits above the current mask will * always collide. (Among known examples are sets of Float keys holding consecutive whole numbers * in small tables.) So we apply a transform that spreads the impact of higher bits downward. * There is a tradeoff between speed, utility, and quality of bit-spreading. Because many common * sets of hashes are already reasonably distributed (so don't benefit from spreading), and * because we use trees to handle large sets of collisions in bins, we just XOR some shifted bits * in the cheapest possible way to reduce systematic lossage, as well as to incorporate impact of * the highest bits that would otherwise never be used in index calculations because of table * bounds. */ static int spread(long h) { return (int) ((h ^ (h >>> 16)) & HASH_BITS); } /** * Returns a power of two table size for the given desired capacity. See Hackers Delight, sec 3.2 */ private static int tableSizeFor(int c) { int n = c - 1; n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16; return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1; } /* ---------------- Table element access -------------- */ /* * Volatile access methods are used for table elements as well as * elements of in-progress next table while resizing. All uses of * the tab arguments must be null checked by callers. All callers * also paranoically precheck that tab's length is not zero (or an * equivalent check), thus ensuring that any index argument taking * the form of a hash value anded with (length - 1) is a valid * index. Note that, to be correct wrt arbitrary concurrency * errors by users, these checks must operate on local variables, * which accounts for some odd-looking inline assignments below. * Note that calls to setTabAt always occur within locked regions, * and so in principle require only release ordering, not * full volatile semantics, but are currently coded as volatile * writes to be conservative. */ @SuppressWarnings("unchecked") static <V> Node<V> tabAt(Node<V>[] tab, int i) { try { Object o = theUnsafe.getObjectVolatile(tab, ((long) i << ASHIFT) + ABASE); return (Node<V>) o; } catch (Throwable throwable) { throw new RuntimeException(throwable); } } static <V> boolean casTabAt(Node<V>[] tab, int i, Node<V> c, @NonNull Node<V> v) { try { return theUnsafe.compareAndSwapObject( (Object) tab, ((long) i << ASHIFT) + ABASE, (Object) c, (Object) v); } catch (Throwable throwable) { throw new RuntimeException(throwable); } } static <V> void setTabAt(Node<V>[] tab, int i, Node<V> v) { try { theUnsafe.putObjectVolatile((Object) tab, ((long) i << ASHIFT) + ABASE, (Object) v); } catch (Throwable throwable) { throw new RuntimeException(throwable); } } /* ---------------- Fields -------------- */ /** * The array of bins. Lazily initialized upon first insertion. Size is always a power of two. * Accessed directly by iterators. */ transient volatile Node<V>[] table; /** The next table to use; non-null only while resizing. */ private transient volatile Node<V>[] nextTable; /** * Base counter value, used mainly when there is no contention, but also as a fallback during * table initialization races. Updated via CAS. */ @SuppressWarnings("UnusedDeclaration") private transient volatile long baseCount; /** * Table initialization and resizing control. When negative, the table is being initialized or * resized: -1 for initialization, else -(1 + the number of active resizing threads). Otherwise, * when table is null, holds the initial table size to use upon creation, or 0 for default. After * initialization, holds the next element count value upon which to resize the table. */ private transient volatile int sizeCtl; /** The next table index (plus one) to split while resizing. */ private transient volatile int transferIndex; /** Spinlock (locked via CAS) used when resizing and/or creating CounterCells. */ private transient volatile int cellsBusy; /** Table of counter cells. When non-null, size is a power of 2. */ private transient volatile ConcurrentIntObjectHashMap.CounterCell[] counterCells; // views private transient ValuesView<V> values; private transient EntrySetView<V> entrySet; /* ---------------- Public operations -------------- */ /** Creates a new, empty map with the default initial table size (16). */ ConcurrentLongObjectHashMap() {} /** * Creates a new, empty map with an initial table size accommodating the specified number of * elements without the need to dynamically resize. * * @param initialCapacity The implementation performs internal sizing to accommodate this many * elements. * @throws IllegalArgumentException if the initial capacity of elements is negative */ ConcurrentLongObjectHashMap(int initialCapacity) { if (initialCapacity < 0) { throw new IllegalArgumentException(); } int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY : tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1)); sizeCtl = cap; } /** * Creates a new, empty map with an initial table size based on the given number of elements * ({@code initialCapacity}) and initial table density ({@code loadFactor}). * * @param initialCapacity the initial capacity. The implementation performs internal sizing to * accommodate this many elements, given the specified load factor. * @param loadFactor the load factor (table density) for establishing the initial table size * @throws IllegalArgumentException if the initial capacity of elements is negative or the load * factor is nonpositive */ ConcurrentLongObjectHashMap(int initialCapacity, float loadFactor) { this(initialCapacity, loadFactor, 1); } /** * Creates a new, empty map with an initial table size based on the given number of elements * ({@code initialCapacity}), table density ({@code loadFactor}), and number of concurrently * updating threads ({@code concurrencyLevel}). * * @param initialCapacity the initial capacity. The implementation performs internal sizing to * accommodate this many elements, given the specified load factor. * @param loadFactor the load factor (table density) for establishing the initial table size * @param concurrencyLevel the estimated number of concurrently updating threads. The * implementation may use this value as a sizing hint. * @throws IllegalArgumentException if the initial capacity is negative or the load factor or * concurrencyLevel are nonpositive */ ConcurrentLongObjectHashMap(int initialCapacity, float loadFactor, int concurrencyLevel) { if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0) { throw new IllegalArgumentException(); } if (initialCapacity < concurrencyLevel) // Use at least as many bins { initialCapacity = concurrencyLevel; // as estimated threads } long size = (long) (1.0 + (long) initialCapacity / loadFactor); int cap = (size >= (long) MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : tableSizeFor((int) size); sizeCtl = cap; } // Original (since JDK1.2) Map methods /** {@inheritDoc} */ public int size() { long n = sumCount(); return ((n < 0L) ? 0 : (n > (long) Integer.MAX_VALUE) ? Integer.MAX_VALUE : (int) n); } /** {@inheritDoc} */ public boolean isEmpty() { return sumCount() <= 0L; // ignore transient negative values } /** * Returns the value to which the specified key is mapped, or {@code null} if this map contains no * mapping for the key. * * <p> * * <p>More formally, if this map contains a mapping from a key {@code k} to a value {@code v} such * that {@code key.equals(k)}, then this method returns {@code v}; otherwise it returns {@code * null}. (There can be at most one such mapping.) */ @Override public V get(long key) { Node<V>[] tab; Node<V> e; Node<V> p; int n, eh; int h = spread(key); if ((tab = table) != null && (n = tab.length) > 0 && (e = tabAt(tab, (n - 1) & h)) != null) { if ((eh = e.hash) == h) { if (e.key == key) { return e.val; } } else if (eh < 0) { return (p = e.find(h, key)) != null ? p.val : null; } while ((e = e.next) != null) { if (e.hash == h && (e.key == key)) { return e.val; } } } return null; } /** * Tests if the specified object is a key in this table. * * @param key possible key * @return {@code true} if and only if the specified object is a key in this table, as determined * by the {@code equals} method; {@code false} otherwise */ public boolean containsKey(long key) { return get(key) != null; } /** * Returns {@code true} if this map maps one or more keys to the specified value. Note: This * method may require a full traversal of the map, and is much slower than method {@code * containsKey}. * * @param value value whose presence in this map is to be tested * @return {@code true} if this map maps one or more keys to the specified value */ public boolean containsValue(@NonNull Object value) { Node<V>[] t; if ((t = table) != null) { Traverser<V> it = new Traverser<>(t, t.length, 0, t.length); for (Node<V> p; (p = it.advance()) != null; ) { V v; if ((v = p.val) == value || (value.equals(v))) { return true; } } } return false; } /** * Maps the specified key to the specified value in this table. Neither the key nor the value can * be null. * * <p> * * <p>The value can be retrieved by calling the {@code get} method with a key that is equal to the * original key. * * @param key key with which the specified value is to be associated * @param value value to be associated with the specified key * @return the previous value associated with {@code key}, or {@code null} if there was no mapping * for {@code key} */ @Override public V put(long key, @NonNull V value) { return putVal(key, value, false); } /** Implementation for put and putIfAbsent */ V putVal(long key, @NonNull V value, boolean onlyIfAbsent) { int hash = spread(key); int binCount = 0; for (Node<V>[] tab = table; ; ) { Node<V> f; int n, i, fh; if (tab == null || (n = tab.length) == 0) { tab = initTable(); } else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) { if (casTabAt(tab, i, null, new Node<>(hash, key, value, null))) { break; // no lock when adding to empty bin } } else if ((fh = f.hash) == MOVED) { tab = helpTransfer(tab, f); } else { V oldVal = null; synchronized (f) { if (tabAt(tab, i) == f) { if (fh >= 0) { binCount = 1; for (Node<V> e = f; ; ++binCount) { if ((e.key == key)) { oldVal = e.val; if (!onlyIfAbsent) { e.val = value; } break; } Node<V> pred = e; if ((e = e.next) == null) { pred.next = new Node<>(hash, key, value, null); break; } } } else if (f instanceof TreeBin) { Node<V> p; binCount = 2; if ((p = ((TreeBin<V>) f).putTreeVal(hash, key, value)) != null) { oldVal = p.val; if (!onlyIfAbsent) { p.val = value; } } } } } if (binCount != 0) { if (binCount >= TREEIFY_THRESHOLD) { treeifyBin(tab, i); } if (oldVal != null) { return oldVal; } break; } } } addCount(1L, binCount); return null; } /** * Removes the key (and its corresponding value) from this map. This method does nothing if the * key is not in the map. * * @param key the key that needs to be removed * @return the previous value associated with {@code key}, or {@code null} if there was no mapping * for {@code key} */ @Override public V remove(long key) { return replaceNode(key, null, null); } /** * Implementation for the four public remove/replace methods: Replaces node value with v, * conditional upon match of cv if non-null. If resulting value is null, delete. */ V replaceNode(long key, V value, Object cv) { int hash = spread(key); for (Node<V>[] tab = table; ; ) { Node<V> f; int n, i, fh; if (tab == null || (n = tab.length) == 0 || (f = tabAt(tab, i = (n - 1) & hash)) == null) { break; } else if ((fh = f.hash) == MOVED) { tab = helpTransfer(tab, f); } else { V oldVal = null; boolean validated = false; synchronized (f) { if (tabAt(tab, i) == f) { if (fh >= 0) { validated = true; for (Node<V> e = f, pred = null; ; ) { if ((e.key == key)) { V ev = e.val; if (cv == null || cv == ev || (ev != null && cv.equals(ev))) { oldVal = ev; if (value != null) { e.val = value; } else if (pred != null) { pred.next = e.next; } else { setTabAt(tab, i, e.next); } } break; } pred = e; if ((e = e.next) == null) { break; } } } else if (f instanceof TreeBin) { validated = true; TreeBin<V> t = (TreeBin<V>) f; TreeNode<V> r, p; if ((r = t.root) != null && (p = r.findTreeNode(hash, key)) != null) { V pv = p.val; if (cv == null || cv == pv || (pv != null && cv.equals(pv))) { oldVal = pv; if (value != null) { p.val = value; } else if (t.removeTreeNode(p)) { setTabAt(tab, i, untreeify(t.first)); } } } } } } if (validated) { if (oldVal != null) { if (value == null) { addCount(-1L, -1); } return oldVal; } break; } } } return null; } /** Removes all of the mappings from this map. */ public void clear() { long delta = 0L; // negative number of deletions int i = 0; Node<V>[] tab = table; while (tab != null && i < tab.length) { int fh; Node<V> f = tabAt(tab, i); if (f == null) { ++i; } else if ((fh = f.hash) == MOVED) { tab = helpTransfer(tab, f); i = 0; // restart } else { synchronized (f) { if (tabAt(tab, i) == f) { Node<V> p = (fh >= 0 ? f : (f instanceof TreeBin) ? ((TreeBin<V>) f).first : null); while (p != null) { --delta; p = p.next; } setTabAt(tab, i++, null); } } } } if (delta != 0L) { addCount(delta, -1); } } /** * Returns a {@link Collection} view of the values contained in this map. The collection is backed * by the map, so changes to the map are reflected in the collection, and vice-versa. The * collection supports element removal, which removes the corresponding mapping from this map, via * the {@code Iterator.remove}, {@code Collection.remove}, {@code removeAll}, {@code retainAll}, * and {@code clear} operations. It does not support the {@code add} or {@code addAll} operations. * * <p> * * <p>The view's iterators and spliterators are <a href="package-summary.html#Weakly"><i>weakly * consistent</i></a>. * * <p> * * @return the collection view */ @NonNull public Collection<V> values() { ValuesView<V> vs; return (vs = values) != null ? vs : (values = new ValuesView<>(this)); } /** * Returns a {@link Set} view of the mappings contained in this map. The set is backed by the map, * so changes to the map are reflected in the set, and vice-versa. The set supports element * removal, which removes the corresponding mapping from the map, via the {@code Iterator.remove}, * {@code Set.remove}, {@code removeAll}, {@code retainAll}, and {@code clear} operations. * * <p> * * <p>The view's iterators and spliterators are <a href="package-summary.html#Weakly"><i>weakly * consistent</i></a>. * * <p> * * @return the set view */ public Set<LongEntry<V>> entrySet() { EntrySetView<V> es; return (es = entrySet) != null ? es : (entrySet = new EntrySetView<>(this)); } /** * Returns the hash code value for this {@link Map}, i.e., the sum of, for each key-value pair in * the map, {@code key.hashCode() ^ value.hashCode()}. * * @return the hash code value for this map */ @Override public int hashCode() { int h = 0; Node<V>[] t; if ((t = table) != null) { Traverser<V> it = new Traverser<>(t, t.length, 0, t.length); for (Node<V> p; (p = it.advance()) != null; ) { h += p.key ^ p.val.hashCode(); } } return h; } /** * Returns a string representation of this map. The string representation consists of a list of * key-value mappings (in no particular order) enclosed in braces ("{@code {}}"). Adjacent * mappings are separated by the characters {@code ", "} (comma and space). Each key-value mapping * is rendered as the key followed by an equals sign ("{@code =}") followed by the associated * value. * * @return a string representation of this map */ @Override public String toString() { Node<V>[] t; int f = (t = table) == null ? 0 : t.length; Traverser<V> it = new Traverser<>(t, f, 0, f); StringBuilder sb = new StringBuilder(); sb.append('{'); Node<V> p; if ((p = it.advance()) != null) { for (; ; ) { long k = p.key; V v = p.val; sb.append(k); sb.append('='); sb.append(v == this ? "(this Map)" : v); if ((p = it.advance()) == null) { break; } sb.append(',').append(' '); } } return sb.append('}').toString(); } /** * Compares the specified object with this map for equality. Returns {@code true} if the given * object is a map with the same mappings as this map. This operation may return misleading * results if either map is concurrently modified during execution of this method. * * @param o object to be compared for equality with this map * @return {@code true} if the specified object is equal to this map */ @Override public boolean equals(Object o) { if (o != this) { if (!(o instanceof ConcurrentLongObjectMap)) { return false; } ConcurrentLongObjectMap<?> m = (ConcurrentLongObjectMap) o; Node<V>[] t; int f = (t = table) == null ? 0 : t.length; Traverser<V> it = new Traverser<>(t, f, 0, f); for (Node<V> p; (p = it.advance()) != null; ) { V val = p.val; Object v = m.get(p.key); if (v == null || (v != val && !v.equals(val))) { return false; } } for (LongEntry e : m.entries()) { long mk = e.getKey(); Object mv; Object v; if ((mv = e.getValue()) == null || (v = get(mk)) == null || (mv != v && !mv.equals(v))) { return false; } } } return true; } // ConcurrentMap methods /** * {@inheritDoc} * * @return the previous value associated with the specified key, or {@code null} if there was no * mapping for the key */ @Override public V putIfAbsent(long key, @NonNull V value) { return putVal(key, value, true); } /** {@inheritDoc} */ public boolean remove(long key, @NonNull Object value) { return replaceNode(key, null, value) != null; } /** {@inheritDoc} */ public boolean replace(long key, @NonNull V oldValue, @NonNull V newValue) { return replaceNode(key, newValue, oldValue) != null; } /** * {@inheritDoc} * * @return the previous value associated with the specified key, or {@code null} if there was no * mapping for the key */ public V replace(long key, @NonNull V value) { return replaceNode(key, value, null); } // Overrides of JDK8+ Map extension method defaults /** * Returns the value to which the specified key is mapped, or the given default value if this map * contains no mapping for the key. * * @param key the key whose associated value is to be returned * @param defaultValue the value to return if this map contains no mapping for the given key * @return the mapping for the key, if present; else the default value */ public V getOrDefault(long key, V defaultValue) { V v; return (v = get(key)) == null ? defaultValue : v; } // Hashtable legacy methods /** * Legacy method testing if some key maps into the specified value in this table. This method is * identical in functionality to {@link #containsValue(Object)}, and exists solely to ensure full * compatibility with class {@link Hashtable}, which supported this method prior to introduction * of the Java Collections framework. * * @param value a value to search for * @return {@code true} if and only if some key maps to the {@code value} argument in this table * as determined by the {@code equals} method; {@code false} otherwise */ public boolean contains(Object value) { return containsValue(value); } /** * Returns an enumeration of the keys in this table. * * @return an enumeration of the keys in this table */ public long[] keys() { Object[] entries = new EntrySetView<>(this).toArray(); long[] result = new long[entries.length]; for (int i = 0; i < entries.length; i++) { LongEntry<V> entry = (LongEntry<V>) entries[i]; result[i] = entry.getKey(); } return result; } /** * Returns an enumeration of the values in this table. * * @return an enumeration of the values in this table * @see #values() */ @NonNull public Enumeration<V> elements() { Node<V>[] t; int f = (t = table) == null ? 0 : t.length; return new ValueIterator<>(t, f, 0, f, this); } // ConcurrentHashMap-only methods /** * Returns the number of mappings. This method should be used instead of {@link #size} because a * ConcurrentHashMap may contain more mappings than can be represented as an int. The value * returned is an estimate; the actual count may differ if there are concurrent insertions or * removals. * * @return the number of mappings */ public long mappingCount() { long n = sumCount(); return Math.max(n, 0L); // ignore transient negative values } /* ---------------- Special Nodes -------------- */ /** A node inserted at head of bins during transfer operations. */ static final class ForwardingNode<V> extends Node<V> { final Node<V>[] nextTable; ForwardingNode(Node<V>[] tab) { super(MOVED, 0, null, null); nextTable = tab; } @Override Node<V> find(int h, long k) { // loop to avoid arbitrarily deep recursion on forwarding nodes outer: for (Node<V>[] tab = nextTable; ; ) { Node<V> e; int n; if (tab == null || (n = tab.length) == 0 || (e = tabAt(tab, (n - 1) & h)) == null) { return null; } for (; ; ) { if ((e.key == k)) { return e; } if (e.hash < 0) { if (e instanceof ForwardingNode) { tab = ((ForwardingNode<V>) e).nextTable; continue outer; } else { return e.find(h, k); } } if ((e = e.next) == null) { return null; } } } } } /* ---------------- Table Initialization and Resizing -------------- */ /** * Returns the stamp bits for resizing a table of size n. Must be negative when shifted left by * RESIZE_STAMP_SHIFT. */ static int resizeStamp(int n) { return Integer.numberOfLeadingZeros(n) | (1 << (RESIZE_STAMP_BITS - 1)); } /** Initializes table, using the size recorded in sizeCtl. */ private Node<V>[] initTable() { Node<V>[] tab; int sc; while ((tab = table) == null || tab.length == 0) { if ((sc = sizeCtl) < 0) { Thread.yield(); // lost initialization race; just spin } else if (compareAndSwapInt(this, SIZECTL, sc, -1)) { try { if ((tab = table) == null || tab.length == 0) { int n = (sc > 0) ? sc : DEFAULT_CAPACITY; @SuppressWarnings("unchecked") Node<V>[] nt = (Node<V>[]) new Node<?>[n]; table = tab = nt; sc = n - (n >>> 2); } } finally { sizeCtl = sc; } break; } } return tab; } /** * Adds to count, and if table is too small and not already resizing, initiates transfer. If * already resizing, helps perform transfer if work is available. Rechecks occupancy after a * transfer to see if another resize is already needed because resizings are lagging additions. * * @param x the count to add * @param check if <0, don't check resize, if <= 1 only check if uncontended */ private void addCount(long x, int check) { ConcurrentIntObjectHashMap.CounterCell[] as; long b, s; if ((as = counterCells) != null || !compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) { ConcurrentIntObjectHashMap.CounterCell a; long v; int m; boolean uncontended = true; if (as == null || (m = as.length - 1) < 0 || (a = as[ThreadLocalRandom.getProbe() & m]) == null || !(uncontended = compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))) { fullAddCount(x, uncontended); return; } if (check <= 1) { return; } s = sumCount(); } if (check >= 0) { Node<V>[] tab, nt; int n, sc; while (s >= (long) (sc = sizeCtl) && (tab = table) != null && (n = tab.length) < MAXIMUM_CAPACITY) { int rs = resizeStamp(n); if (sc < 0) { if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 || sc == rs + MAX_RESIZERS || (nt = nextTable) == null || transferIndex <= 0) { break; } if (compareAndSwapInt(this, SIZECTL, sc, sc + 1)) { transfer(tab, nt); } } else if (compareAndSwapInt(this, SIZECTL, sc, (rs << RESIZE_STAMP_SHIFT) + 2)) { transfer(tab, null); } s = sumCount(); } } } /** Helps transfer if a resize is in progress. */ Node<V>[] helpTransfer(Node<V>[] tab, Node<V> f) { Node<V>[] nextTab; int sc; if (tab != null && (f instanceof ForwardingNode) && (nextTab = ((ForwardingNode<V>) f).nextTable) != null) { int rs = resizeStamp(tab.length); while (nextTab == nextTable && table == tab && (sc = sizeCtl) < 0) { if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 || sc == rs + MAX_RESIZERS || transferIndex <= 0) { break; } if (compareAndSwapInt(this, SIZECTL, sc, sc + 1)) { transfer(tab, nextTab); break; } } return nextTab; } return table; } /** * Tries to presize table to accommodate the given number of elements. * * @param size number of elements (doesn't need to be perfectly accurate) */ private void tryPresize(int size) { int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY : tableSizeFor(size + (size >>> 1) + 1); int sc; while ((sc = sizeCtl) >= 0) { Node<V>[] tab = table; int n; if (tab == null || (n = tab.length) == 0) { n = Math.max(sc, c); if (compareAndSwapInt(this, SIZECTL, sc, -1)) { try { if (table == tab) { @SuppressWarnings("unchecked") Node<V>[] nt = (Node<V>[]) new Node<?>[n]; table = nt; sc = n - (n >>> 2); } } finally { sizeCtl = sc; } } } else if (c <= sc || n >= MAXIMUM_CAPACITY) { break; } else if (tab == table) { int rs = resizeStamp(n); if (sc < 0) { Node<V>[] nt; if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 || sc == rs + MAX_RESIZERS || (nt = nextTable) == null || transferIndex <= 0) { break; } if (compareAndSwapInt(this, SIZECTL, sc, sc + 1)) { transfer(tab, nt); } } else if (compareAndSwapInt(this, SIZECTL, sc, (rs << RESIZE_STAMP_SHIFT) + 2)) { transfer(tab, null); } } } } /** Moves and/or copies the nodes in each bin to new table. See above for explanation. */ private void transfer(Node<V>[] tab, Node<V>[] nextTab) { int n = tab.length, stride; if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE) { stride = MIN_TRANSFER_STRIDE; // subdivide range } if (nextTab == null) { // initiating try { @SuppressWarnings("unchecked") Node<V>[] nt = (Node<V>[]) new Node<?>[n << 1]; nextTab = nt; } catch (Throwable ex) { // try to cope with OOME sizeCtl = Integer.MAX_VALUE; return; } nextTable = nextTab; transferIndex = n; } int nextn = nextTab.length; ForwardingNode<V> fwd = new ForwardingNode<>(nextTab); boolean advance = true; boolean finishing = false; // to ensure sweep before committing nextTab for (int i = 0, bound = 0; ; ) { Node<V> f; int fh; while (advance) { int nextIndex, nextBound; if (--i >= bound || finishing) { advance = false; } else if ((nextIndex = transferIndex) <= 0) { i = -1; advance = false; } else if (compareAndSwapInt( this, TRANSFERINDEX, nextIndex, nextBound = (nextIndex > stride ? nextIndex - stride : 0))) { bound = nextBound; i = nextIndex - 1; advance = false; } } if (i < 0 || i >= n || i + n >= nextn) { int sc; if (finishing) { nextTable = null; table = nextTab; sizeCtl = (n << 1) - (n >>> 1); return; } if (compareAndSwapInt(this, SIZECTL, sc = sizeCtl, sc - 1)) { if ((sc - 2) != resizeStamp(n) << RESIZE_STAMP_SHIFT) { return; } finishing = advance = true; i = n; // recheck before commit } } else if ((f = tabAt(tab, i)) == null) { advance = casTabAt(tab, i, null, fwd); } else if ((fh = f.hash) == MOVED) { advance = true; // already processed } else { synchronized (f) { if (tabAt(tab, i) == f) { Node<V> ln, hn; if (fh >= 0) { int runBit = fh & n; Node<V> lastRun = f; for (Node<V> p = f.next; p != null; p = p.next) { int b = p.hash & n; if (b != runBit) { runBit = b; lastRun = p; } } if (runBit == 0) { ln = lastRun; hn = null; } else { hn = lastRun; ln = null; } for (Node<V> p = f; p != lastRun; p = p.next) { int ph = p.hash; long pk = p.key; V pv = p.val; if ((ph & n) == 0) { ln = new Node<>(ph, pk, pv, ln); } else { hn = new Node<>(ph, pk, pv, hn); } } setTabAt(nextTab, i, ln); setTabAt(nextTab, i + n, hn); setTabAt(tab, i, fwd); advance = true; } else if (f instanceof TreeBin) { TreeBin<V> t = (TreeBin<V>) f; TreeNode<V> lo = null, loTail = null; TreeNode<V> hi = null, hiTail = null; int lc = 0, hc = 0; for (Node<V> e = t.first; e != null; e = e.next) { int h = e.hash; TreeNode<V> p = new TreeNode<>(h, e.key, e.val, null, null); if ((h & n) == 0) { if ((p.prev = loTail) == null) { lo = p; } else { loTail.next = p; } loTail = p; ++lc; } else { if ((p.prev = hiTail) == null) { hi = p; } else { hiTail.next = p; } hiTail = p; ++hc; } } ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) : (hc != 0) ? new TreeBin<>(lo) : t; hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) : (lc != 0) ? new TreeBin<>(hi) : t; setTabAt(nextTab, i, ln); setTabAt(nextTab, i + n, hn); setTabAt(tab, i, fwd); advance = true; } } } } } } /* ---------------- Counter support -------------- */ long sumCount() { ConcurrentIntObjectHashMap.CounterCell[] as = counterCells; ConcurrentIntObjectHashMap.CounterCell a; long sum = baseCount; if (as != null) { for (int i = 0; i < as.length; ++i) { if ((a = as[i]) != null) { sum += a.value; } } } return sum; } // See LongAdder version for explanation private void fullAddCount(long x, boolean wasUncontended) { int h; if ((h = ThreadLocalRandom.getProbe()) == 0) { ThreadLocalRandom.localInit(); // force initialization h = ThreadLocalRandom.getProbe(); wasUncontended = true; } boolean collide = false; // True if last slot nonempty for (; ; ) { ConcurrentIntObjectHashMap.CounterCell[] as; ConcurrentIntObjectHashMap.CounterCell a; int n; long v; if ((as = counterCells) != null && (n = as.length) > 0) { if ((a = as[(n - 1) & h]) == null) { if (cellsBusy == 0) { // Try to attach new Cell ConcurrentIntObjectHashMap.CounterCell r = new ConcurrentIntObjectHashMap.CounterCell(x); // Optimistic create if (cellsBusy == 0 && compareAndSwapInt(this, CELLSBUSY, 0, 1)) { boolean created = false; try { // Recheck under lock ConcurrentIntObjectHashMap.CounterCell[] rs; int m, j; if ((rs = counterCells) != null && (m = rs.length) > 0 && rs[j = (m - 1) & h] == null) { rs[j] = r; created = true; } } finally { cellsBusy = 0; } if (created) { break; } continue; // Slot is now non-empty } } collide = false; } else if (!wasUncontended) // CAS already known to fail { wasUncontended = true; // Continue after rehash } else if (compareAndSwapLong(a, CELLVALUE, v = a.value, v + x)) { break; } else if (counterCells != as || n >= NCPU) { collide = false; // At max size or stale } else if (!collide) { collide = true; } else if (cellsBusy == 0 && compareAndSwapInt(this, CELLSBUSY, 0, 1)) { try { if (counterCells == as) { // Expand table unless stale ConcurrentIntObjectHashMap.CounterCell[] rs = new ConcurrentIntObjectHashMap.CounterCell[n << 1]; for (int i = 0; i < n; ++i) { rs[i] = as[i]; } counterCells = rs; } } finally { cellsBusy = 0; } collide = false; continue; // Retry with expanded table } h = ThreadLocalRandom.advanceProbe(h); } else if (cellsBusy == 0 && counterCells == as && compareAndSwapInt(this, CELLSBUSY, 0, 1)) { boolean init = false; try { // Initialize table if (counterCells == as) { ConcurrentIntObjectHashMap.CounterCell[] rs = new ConcurrentIntObjectHashMap.CounterCell[2]; rs[h & 1] = new ConcurrentIntObjectHashMap.CounterCell(x); counterCells = rs; init = true; } } finally { cellsBusy = 0; } if (init) { break; } } else if (compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x)) { break; // Fall back on using base } } } /* ---------------- Conversion from/to TreeBins -------------- */ /** * Replaces all linked nodes in bin at given index unless table is too small, in which case * resizes instead. */ private void treeifyBin(Node<V>[] tab, int index) { Node<V> b; int n, sc; if (tab != null) { if ((n = tab.length) < MIN_TREEIFY_CAPACITY) { tryPresize(n << 1); } else if ((b = tabAt(tab, index)) != null && b.hash >= 0) { synchronized (b) { if (tabAt(tab, index) == b) { TreeNode<V> hd = null, tl = null; for (Node<V> e = b; e != null; e = e.next) { TreeNode<V> p = new TreeNode<>(e.hash, e.key, e.val, null, null); if ((p.prev = tl) == null) { hd = p; } else { tl.next = p; } tl = p; } setTabAt(tab, index, new TreeBin<>(hd)); } } } } } /** Returns a list on non-TreeNodes replacing those in given list. */ static <V> Node<V> untreeify(Node<V> b) { Node<V> hd = null, tl = null; for (Node<V> q = b; q != null; q = q.next) { Node<V> p = new Node<>(q.hash, q.key, q.val, null); if (tl == null) { hd = p; } else { tl.next = p; } tl = p; } return hd; } /* ---------------- TreeNodes -------------- */ /** Nodes for use in TreeBins */ static final class TreeNode<V> extends Node<V> { TreeNode<V> parent; // red-black tree links TreeNode<V> left; TreeNode<V> right; TreeNode<V> prev; // needed to unlink next upon deletion boolean red; TreeNode(int hash, long key, V val, Node<V> next, TreeNode<V> parent) { super(hash, key, val, next); this.parent = parent; } @Override Node<V> find(int h, long k) { return findTreeNode(h, k); } /** Returns the TreeNode (or null if not found) for the given key starting at given root. */ TreeNode<V> findTreeNode(int h, long k) { TreeNode<V> p = this; do { int ph; TreeNode<V> q; TreeNode<V> pl = p.left; TreeNode<V> pr = p.right; if ((ph = p.hash) > h) { p = pl; } else if (ph < h) { p = pr; } else if (p.key == k) { return p; } else if (pl == null) { p = pr; } else if (pr == null) { p = pl; } else if ((q = pr.findTreeNode(h, k)) != null) { return q; } else { p = pl; } } while (p != null); return null; } } /* ---------------- TreeBins -------------- */ /** * TreeNodes used at the heads of bins. TreeBins do not hold user keys or values, but instead * point to list of TreeNodes and their root. They also maintain a parasitic read-write lock * forcing writers (who hold bin lock) to wait for readers (who do not) to complete before tree * restructuring operations. */ static final class TreeBin<V> extends Node<V> { TreeNode<V> root; volatile TreeNode<V> first; volatile Thread waiter; volatile int lockState; // values for lockState static final int WRITER = 1; // set while holding write lock static final int WAITER = 2; // set when waiting for write lock static final int READER = 4; // increment value for setting read lock /** Creates bin with initial set of nodes headed by b. */ TreeBin(TreeNode<V> b) { super(TREEBIN, 0, null, null); first = b; TreeNode<V> r = null; for (TreeNode<V> x = b, next; x != null; x = next) { next = (TreeNode<V>) x.next; x.left = x.right = null; if (r == null) { x.parent = null; x.red = false; r = x; } else { int h = x.hash; for (TreeNode<V> p = r; ; ) { int dir, ph; if ((ph = p.hash) > h) { dir = -1; } else if (ph < h) { dir = 1; } else { dir = 0; } TreeNode<V> xp = p; if ((p = (dir <= 0) ? p.left : p.right) == null) { x.parent = xp; if (dir <= 0) { xp.left = x; } else { xp.right = x; } r = balanceInsertion(r, x); break; } } } } root = r; assert checkInvariants(root); } /** Acquires write lock for tree restructuring. */ private void lockRoot() { if (!compareAndSwapInt(this, LOCKSTATE, 0, WRITER)) { contendedLock(); // offload to separate method } } /** Releases write lock for tree restructuring. */ private void unlockRoot() { lockState = 0; } /** Possibly blocks awaiting root lock. */ private void contendedLock() { boolean waiting = false; for (int s; ; ) { if (((s = lockState) & ~WAITER) == 0) { if (compareAndSwapInt(this, LOCKSTATE, s, WRITER)) { if (waiting) { waiter = null; } return; } } else if ((s & WAITER) == 0) { if (compareAndSwapInt(this, LOCKSTATE, s, s | WAITER)) { waiting = true; waiter = Thread.currentThread(); } } else if (waiting) { LockSupport.park(this); } } } /** * Returns matching node or null if none. Tries to search using tree comparisons from root, but * continues linear search when lock not available. */ @Override Node<V> find(int h, long k) { for (Node<V> e = first; e != null; ) { int s; if (((s = lockState) & (WAITER | WRITER)) != 0) { if ((e.key == k)) { return e; } e = e.next; } else if (compareAndSwapInt(this, LOCKSTATE, s, s + READER)) { TreeNode<V> r; TreeNode<V> p; try { p = ((r = root) == null ? null : r.findTreeNode(h, k)); } finally { Thread w; if (getAndAddInt(this, LOCKSTATE, -READER) == (READER | WAITER) && (w = waiter) != null) { LockSupport.unpark(w); } } return p; } } return null; } private static int getAndAddInt(Object object, long offset, int v) { try { return theUnsafe.getAndAddInt(object, offset, v); } catch (Throwable t) { throw new RuntimeException(t); } } /** * Finds or adds a node. * * @return null if added */ TreeNode<V> putTreeVal(int h, long k, V v) { boolean searched = false; for (TreeNode<V> p = root; ; ) { int dir, ph; if (p == null) { first = root = new TreeNode<>(h, k, v, null, null); break; } else if ((ph = p.hash) > h) { dir = -1; } else if (ph < h) { dir = 1; } else if (p.key == k) { return p; } else { if (!searched) { TreeNode<V> q, ch; searched = true; if (((ch = p.left) != null && (q = ch.findTreeNode(h, k)) != null) || ((ch = p.right) != null && (q = ch.findTreeNode(h, k)) != null)) { return q; } } dir = 0; } TreeNode<V> xp = p; if ((p = (dir <= 0) ? p.left : p.right) == null) { TreeNode<V> x, f = first; first = x = new TreeNode<>(h, k, v, f, xp); if (f != null) { f.prev = x; } if (dir <= 0) { xp.left = x; } else { xp.right = x; } if (!xp.red) { x.red = true; } else { lockRoot(); try { root = balanceInsertion(root, x); } finally { unlockRoot(); } } break; } } assert checkInvariants(root); return null; } /** * Removes the given node, that must be present before this call. This is messier than typical * red-black deletion code because we cannot swap the contents of an interior node with a leaf * successor that is pinned by "next" pointers that are accessible independently of lock. So * instead we swap the tree linkages. * * @return true if now too small, so should be untreeified */ boolean removeTreeNode(TreeNode<V> p) { TreeNode<V> next = (TreeNode<V>) p.next; TreeNode<V> pred = p.prev; // unlink traversal pointers TreeNode<V> r, rl; if (pred == null) { first = next; } else { pred.next = next; } if (next != null) { next.prev = pred; } if (first == null) { root = null; return true; } if ((r = root) == null || r.right == null || // too small (rl = r.left) == null || rl.left == null) { return true; } lockRoot(); try { TreeNode<V> replacement; TreeNode<V> pl = p.left; TreeNode<V> pr = p.right; if (pl != null && pr != null) { TreeNode<V> s = pr, sl; while ((sl = s.left) != null) // find successor { s = sl; } boolean c = s.red; s.red = p.red; p.red = c; // swap colors TreeNode<V> sr = s.right; TreeNode<V> pp = p.parent; if (s == pr) { // p was s's direct parent p.parent = s; s.right = p; } else { TreeNode<V> sp = s.parent; if ((p.parent = sp) != null) { if (s == sp.left) { sp.left = p; } else { sp.right = p; } } if ((s.right = pr) != null) { pr.parent = s; } } p.left = null; if ((p.right = sr) != null) { sr.parent = p; } if ((s.left = pl) != null) { pl.parent = s; } if ((s.parent = pp) == null) { r = s; } else if (p == pp.left) { pp.left = s; } else { pp.right = s; } if (sr != null) { replacement = sr; } else { replacement = p; } } else if (pl != null) { replacement = pl; } else if (pr != null) { replacement = pr; } else { replacement = p; } if (replacement != p) { TreeNode<V> pp = replacement.parent = p.parent; if (pp == null) { r = replacement; } else if (p == pp.left) { pp.left = replacement; } else { pp.right = replacement; } p.left = p.right = p.parent = null; } root = (p.red) ? r : balanceDeletion(r, replacement); if (p == replacement) { // detach pointers TreeNode<V> pp; if ((pp = p.parent) != null) { if (p == pp.left) { pp.left = null; } else if (p == pp.right) { pp.right = null; } p.parent = null; } } } finally { unlockRoot(); } assert checkInvariants(root); return false; } /* ------------------------------------------------------------ */ // Red-black tree methods, all adapted from CLR static <V> TreeNode<V> rotateLeft(TreeNode<V> root, TreeNode<V> p) { TreeNode<V> r, pp, rl; if (p != null && (r = p.right) != null) { if ((rl = p.right = r.left) != null) { rl.parent = p; } if ((pp = r.parent = p.parent) == null) { (root = r).red = false; } else if (pp.left == p) { pp.left = r; } else { pp.right = r; } r.left = p; p.parent = r; } return root; } static <V> TreeNode<V> rotateRight(TreeNode<V> root, TreeNode<V> p) { TreeNode<V> l, pp, lr; if (p != null && (l = p.left) != null) { if ((lr = p.left = l.right) != null) { lr.parent = p; } if ((pp = l.parent = p.parent) == null) { (root = l).red = false; } else if (pp.right == p) { pp.right = l; } else { pp.left = l; } l.right = p; p.parent = l; } return root; } static <V> TreeNode<V> balanceInsertion(TreeNode<V> root, TreeNode<V> x) { x.red = true; for (TreeNode<V> xp, xpp, xppl, xppr; ; ) { if ((xp = x.parent) == null) { x.red = false; return x; } else if (!xp.red || (xpp = xp.parent) == null) { return root; } if (xp == (xppl = xpp.left)) { if ((xppr = xpp.right) != null && xppr.red) { xppr.red = false; xp.red = false; xpp.red = true; x = xpp; } else { if (x == xp.right) { root = rotateLeft(root, x = xp); xpp = (xp = x.parent) == null ? null : xp.parent; } if (xp != null) { xp.red = false; if (xpp != null) { xpp.red = true; root = rotateRight(root, xpp); } } } } else { if (xppl != null && xppl.red) { xppl.red = false; xp.red = false; xpp.red = true; x = xpp; } else { if (x == xp.left) { root = rotateRight(root, x = xp); xpp = (xp = x.parent) == null ? null : xp.parent; } if (xp != null) { xp.red = false; if (xpp != null) { xpp.red = true; root = rotateLeft(root, xpp); } } } } } } static <V> TreeNode<V> balanceDeletion(TreeNode<V> root, TreeNode<V> x) { for (TreeNode<V> xp, xpl, xpr; ; ) { if (x == null || x == root) { return root; } else if ((xp = x.parent) == null) { x.red = false; return x; } else if (x.red) { x.red = false; return root; } else if ((xpl = xp.left) == x) { if ((xpr = xp.right) != null && xpr.red) { xpr.red = false; xp.red = true; root = rotateLeft(root, xp); xpr = (xp = x.parent) == null ? null : xp.right; } if (xpr == null) { x = xp; } else { TreeNode<V> sl = xpr.left, sr = xpr.right; if ((sr == null || !sr.red) && (sl == null || !sl.red)) { xpr.red = true; x = xp; } else { if (sr == null || !sr.red) { if (sl != null) { sl.red = false; } xpr.red = true; root = rotateRight(root, xpr); xpr = (xp = x.parent) == null ? null : xp.right; } if (xpr != null) { xpr.red = (xp == null) ? false : xp.red; if ((sr = xpr.right) != null) { sr.red = false; } } if (xp != null) { xp.red = false; root = rotateLeft(root, xp); } x = root; } } } else { // symmetric if (xpl != null && xpl.red) { xpl.red = false; xp.red = true; root = rotateRight(root, xp); xpl = (xp = x.parent) == null ? null : xp.left; } if (xpl == null) { x = xp; } else { TreeNode<V> sl = xpl.left, sr = xpl.right; if ((sl == null || !sl.red) && (sr == null || !sr.red)) { xpl.red = true; x = xp; } else { if (sl == null || !sl.red) { if (sr != null) { sr.red = false; } xpl.red = true; root = rotateLeft(root, xpl); xpl = (xp = x.parent) == null ? null : xp.left; } if (xpl != null) { xpl.red = (xp == null) ? false : xp.red; if ((sl = xpl.left) != null) { sl.red = false; } } if (xp != null) { xp.red = false; root = rotateRight(root, xp); } x = root; } } } } } /** Recursive invariant check */ static <V> boolean checkInvariants(TreeNode<V> t) { TreeNode<V> tp = t.parent, tl = t.left, tr = t.right, tb = t.prev, tn = (TreeNode<V>) t.next; if (tb != null && tb.next != t) { return false; } if (tn != null && tn.prev != t) { return false; } if (tp != null && t != tp.left && t != tp.right) { return false; } if (tl != null && (tl.parent != t || tl.hash > t.hash)) { return false; } if (tr != null && (tr.parent != t || tr.hash < t.hash)) { return false; } if (t.red && tl != null && tl.red && tr != null && tr.red) { return false; } if (tl != null && !checkInvariants(tl)) { return false; } if (tr != null && !checkInvariants(tr)) { return false; } return true; } private static final long LOCKSTATE; static { try { Unsafe unsafe = UnsafeUtil.findUnsafe(); Class<?> k = TreeBin.class; LOCKSTATE = unsafe.objectFieldOffset(k.getDeclaredField("lockState")); } catch (Throwable t) { throw new Error(t); } } } /* ----------------Table Traversal -------------- */ /** * Records the table, its length, and current traversal index for a traverser that must process a * region of a forwarded table before proceeding with current table. */ static final class TableStack<V> { int length; int index; Node<V>[] tab; TableStack<V> next; } /** * Encapsulates traversal for methods such as containsValue; also serves as a base class for other * iterators and spliterators. * * <p>Method advance visits once each still-valid node that was reachable upon iterator * construction. It might miss some that were added to a bin after the bin was visited, which is * OK wrt consistency guarantees. Maintaining this property in the face of possible ongoing * resizes requires a fair amount of bookkeeping state that is difficult to optimize away amidst * volatile accesses. Even so, traversal maintains reasonable throughput. * * <p>Normally, iteration proceeds bin-by-bin traversing lists. However, if the table has been * resized, then all future steps must traverse both the bin at the current index as well as at * (index + baseSize); and so on for further resizings. To paranoically cope with potential * sharing by users of iterators across threads, iteration terminates if a bounds checks fails for * a table read. */ static class Traverser<V> { Node<V>[] tab; // current table; updated if resized Node<V> next; // the next entry to use TableStack<V> stack; TableStack<V> spare; // to save/restore on ForwardingNodes int index; // index of bin to use next int baseIndex; // current index of initial table int baseLimit; // index bound for initial table final int baseSize; // initial table size Traverser(Node<V>[] tab, int size, int index, int limit) { this.tab = tab; baseSize = size; baseIndex = this.index = index; baseLimit = limit; next = null; } /** Advances if possible, returning next valid node, or null if none. */ final Node<V> advance() { Node<V> e; if ((e = next) != null) { e = e.next; } for (; ; ) { Node<V>[] t; int i; // must use locals in checks int n; if (e != null) { return next = e; } if (baseIndex >= baseLimit || (t = tab) == null || (n = t.length) <= (i = index) || i < 0) { return next = null; } if ((e = tabAt(t, i)) != null && e.hash < 0) { if (e instanceof ForwardingNode) { tab = ((ForwardingNode<V>) e).nextTable; e = null; pushState(t, i, n); continue; } else if (e instanceof TreeBin) { e = ((TreeBin<V>) e).first; } else { e = null; } } if (stack != null) { recoverState(n); } else if ((index = i + baseSize) >= n) { index = ++baseIndex; // visit upper slots if present } } } /** Saves traversal state upon encountering a forwarding node. */ private void pushState(Node<V>[] t, int i, int n) { TableStack<V> s = spare; // reuse if possible if (s != null) { spare = s.next; } else { s = new TableStack<>(); } s.tab = t; s.length = n; s.index = i; s.next = stack; stack = s; } /** * Possibly pops traversal state. * * @param n length of current table */ private void recoverState(int n) { TableStack<V> s; int len; while ((s = stack) != null && (index += (len = s.length)) >= n) { n = len; index = s.index; tab = s.tab; s.tab = null; TableStack<V> next = s.next; s.next = spare; // save for reuse stack = next; spare = s; } if (s == null && (index += baseSize) >= n) { index = ++baseIndex; } } } /** * Base of key, value, and entry Iterators. Adds fields to Traverser to support iterator.remove. */ static class BaseIterator<V> extends Traverser<V> { final ConcurrentLongObjectHashMap<V> map; Node<V> lastReturned; BaseIterator( Node<V>[] tab, int size, int index, int limit, ConcurrentLongObjectHashMap<V> map) { super(tab, size, index, limit); this.map = map; advance(); } public final boolean hasNext() { return next != null; } public final boolean hasMoreElements() { return next != null; } public final void remove() { Node<V> p; if ((p = lastReturned) == null) { throw new IllegalStateException(); } lastReturned = null; map.replaceNode(p.key, null, null); } } static final class ValueIterator<V> extends BaseIterator<V> implements Iterator<V>, Enumeration<V> { ValueIterator( Node<V>[] tab, int index, int size, int limit, ConcurrentLongObjectHashMap<V> map) { super(tab, index, size, limit, map); } @Override public V next() { Node<V> p; if ((p = next) == null) { throw new NoSuchElementException(); } V v = p.val; lastReturned = p; advance(); return v; } @Override public V nextElement() { return next(); } } static final class EntryIterator<V> extends BaseIterator<V> implements Iterator<LongEntry<V>> { EntryIterator( Node<V>[] tab, int index, int size, int limit, ConcurrentLongObjectHashMap<V> map) { super(tab, index, size, limit, map); } @Override public LongEntry<V> next() { Node<V> p; if ((p = next) == null) { throw new NoSuchElementException(); } final long k = p.key; final V v = p.val; lastReturned = p; advance(); return new LongEntry<V>() { @Override public long getKey() { return k; } @NonNull @Override public V getValue() { return v; } }; } } // Parallel bulk operations /* ----------------Views -------------- */ /** Base class for views. */ abstract static class CollectionView<V, E> implements Collection<E> { final ConcurrentLongObjectHashMap<V> map; CollectionView(ConcurrentLongObjectHashMap<V> map) { this.map = map; } /** * Returns the map backing this view. * * @return the map backing this view */ public ConcurrentLongObjectHashMap<V> getMap() { return map; } /** * Removes all of the elements from this view, by removing all the mappings from the map backing * this view. */ @Override public final void clear() { map.clear(); } @Override public final int size() { return map.size(); } @Override public final boolean isEmpty() { return map.isEmpty(); } // implementations below rely on concrete classes supplying these // abstract methods /** * Returns an iterator over the elements in this collection. * * <p> * * <p>The returned iterator is <a href="package-summary.html#Weakly"><i>weakly * consistent</i></a>. * * @return an iterator over the elements in this collection */ @NonNull @Override public abstract Iterator<E> iterator(); @Override public abstract boolean contains(Object o); @Override public abstract boolean remove(Object o); private static final String oomeMsg = "Required array size too large"; @Override public final Object[] toArray() { long sz = map.mappingCount(); if (sz > MAX_ARRAY_SIZE) { throw new OutOfMemoryError(oomeMsg); } int n = (int) sz; Object[] r = new Object[n]; int i = 0; for (E e : this) { if (i == n) { if (n >= MAX_ARRAY_SIZE) { throw new OutOfMemoryError(oomeMsg); } if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1) { n = MAX_ARRAY_SIZE; } else { n += (n >>> 1) + 1; } r = Arrays.copyOf(r, n); } r[i++] = e; } return (i == n) ? r : Arrays.copyOf(r, i); } @Override @SuppressWarnings("unchecked") public final <T> T[] toArray(T[] a) { long sz = map.mappingCount(); if (sz > MAX_ARRAY_SIZE) { throw new OutOfMemoryError(oomeMsg); } int m = (int) sz; T[] r = (a.length >= m) ? a : (T[]) java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), m); int n = r.length; int i = 0; for (E e : this) { if (i == n) { if (n >= MAX_ARRAY_SIZE) { throw new OutOfMemoryError(oomeMsg); } if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1) { n = MAX_ARRAY_SIZE; } else { n += (n >>> 1) + 1; } r = Arrays.copyOf(r, n); } r[i++] = (T) e; } if (a == r && i < n) { r[i] = null; // null-terminate return r; } return (i == n) ? r : Arrays.copyOf(r, i); } /** * Returns a string representation of this collection. The string representation consists of the * string representations of the collection's elements in the order they are returned by its * iterator, enclosed in square brackets ({@code "[]"}). Adjacent elements are separated by the * characters {@code ", "} (comma and space). Elements are converted to strings as by {@link * String#valueOf(Object)}. * * @return a string representation of this collection */ @Override public final String toString() { StringBuilder sb = new StringBuilder(); sb.append('['); Iterator<E> it = iterator(); if (it.hasNext()) { for (; ; ) { Object e = it.next(); sb.append(e == this ? "(this Collection)" : e); if (!it.hasNext()) { break; } sb.append(',').append(' '); } } return sb.append(']').toString(); } @Override public final boolean containsAll(@NonNull Collection<?> c) { if (c != this) { for (Object e : c) { if (e == null || !contains(e)) { return false; } } } return true; } @Override public final boolean removeAll(@NonNull Collection<?> c) { boolean modified = false; for (Iterator<E> it = iterator(); it.hasNext(); ) { if (c.contains(it.next())) { it.remove(); modified = true; } } return modified; } @Override public final boolean retainAll(@NonNull Collection<?> c) { boolean modified = false; for (Iterator<E> it = iterator(); it.hasNext(); ) { if (!c.contains(it.next())) { it.remove(); modified = true; } } return modified; } } /** * A view of a ConcurrentHashMap as a {@link Collection} of values, in which additions are * disabled. This class cannot be directly instantiated. See {@link #values()}. */ static final class ValuesView<V> extends CollectionView<V, V> implements Collection<V> { ValuesView(ConcurrentLongObjectHashMap<V> map) { super(map); } @Override public boolean contains(Object o) { return map.containsValue(o); } @Override public boolean remove(Object o) { if (o != null) { for (Iterator<V> it = iterator(); it.hasNext(); ) { if (o.equals(it.next())) { it.remove(); return true; } } } return false; } @NonNull @Override public Iterator<V> iterator() { ConcurrentLongObjectHashMap<V> m = map; Node<V>[] t; int f = (t = m.table) == null ? 0 : t.length; return new ValueIterator<>(t, f, 0, f, m); } @Override public boolean add(V e) { throw new UnsupportedOperationException(); } @Override public boolean addAll(@NonNull Collection<? extends V> c) { throw new UnsupportedOperationException(); } } @NonNull @Override public Iterable<LongEntry<V>> entries() { return new EntrySetView<>(this); } /** * A view of a ConcurrentHashMap as a {@link Set} of (key, value) entries. This class cannot be * directly instantiated. See {@link #entrySet()}. */ static final class EntrySetView<V> extends CollectionView<V, LongEntry<V>> implements Set<LongEntry<V>> { EntrySetView(ConcurrentLongObjectHashMap<V> map) { super(map); } @Override public boolean contains(Object o) { Object v; Object r; LongEntry<?> e; return ((o instanceof LongEntry) && (r = map.get((e = (LongEntry) o).getKey())) != null && (v = e.getValue()) != null && (v == r || v.equals(r))); } @Override public boolean remove(Object o) { Object v; LongEntry<?> e; return ((o instanceof Map.Entry) && (e = (LongEntry<?>) o) != null && (v = e.getValue()) != null && map.remove(e.getKey(), v)); } /** * @return an iterator over the entries of the backing map */ @NonNull @Override public Iterator<LongEntry<V>> iterator() { ConcurrentLongObjectHashMap<V> m = map; Node<V>[] t; int f = (t = m.table) == null ? 0 : t.length; return new EntryIterator<>(t, f, 0, f, m); } @Override public boolean add(LongEntry<V> e) { return map.putVal(e.getKey(), e.getValue(), false) == null; } @Override public boolean addAll(Collection<? extends LongEntry<V>> c) { boolean added = false; for (LongEntry<V> e : c) { if (add(e)) { added = true; } } return added; } @Override public int hashCode() { int h = 0; Node<V>[] t; if ((t = map.table) != null) { Traverser<V> it = new Traverser<>(t, t.length, 0, t.length); for (Node<V> p; (p = it.advance()) != null; ) { h += p.hashCode(); } } return h; } @Override public boolean equals(Object o) { Set<?> c; return ((o instanceof Set) && ((c = (Set<?>) o) == this || (containsAll(c) && c.containsAll(this)))); } } // ------------------------------------------------------- // Unsafe mechanics private static final long SIZECTL; private static final long TRANSFERINDEX; private static final long BASECOUNT; private static final long CELLSBUSY; private static final long CELLVALUE; private static final long ABASE; private static final int ASHIFT; private static final Unsafe theUnsafe; static { try { theUnsafe = UnsafeUtil.findUnsafe(); Class<?> k = ConcurrentLongObjectHashMap.class; SIZECTL = theUnsafe.objectFieldOffset(k.getDeclaredField("sizeCtl")); TRANSFERINDEX = theUnsafe.objectFieldOffset(k.getDeclaredField("transferIndex")); BASECOUNT = theUnsafe.objectFieldOffset(k.getDeclaredField("baseCount")); CELLSBUSY = theUnsafe.objectFieldOffset(k.getDeclaredField("cellsBusy")); Class<?> ck = ConcurrentIntObjectHashMap.CounterCell.class; CELLVALUE = theUnsafe.objectFieldOffset(ck.getDeclaredField("value")); Class<?> ak = Node[].class; ABASE = theUnsafe.arrayBaseOffset(ak); int scale = theUnsafe.arrayIndexScale(ak); if ((scale & (scale - 1)) != 0) { throw new Error("data type scale not a power of two"); } ASHIFT = 31 - Integer.numberOfLeadingZeros(scale); } catch (Throwable t) { throw new Error(t); } } private static boolean compareAndSwapInt( @NonNull Object object, long offset, int expected, int value) { try { return theUnsafe.compareAndSwapInt(object, offset, expected, value); } catch (Throwable throwable) { throw new RuntimeException(throwable); } } private static boolean compareAndSwapLong( @NonNull Object object, long offset, long expected, long value) { try { return theUnsafe.compareAndSwapLong(object, offset, expected, value); } catch (Throwable throwable) { throw new RuntimeException(throwable); } } /** * @return value if there is no entry in the map, or corresponding value if entry already exists */ @NonNull public V cacheOrGet(final long key, @NonNull final V defaultValue) { V v = get(key); if (v != null) return v; V prev = putIfAbsent(key, defaultValue); return prev == null ? defaultValue : prev; } }
78,809
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
UnsafeUtil.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/kotlinc/src/main/java/org/jetbrains/kotlin/com/intellij/util/containers/UnsafeUtil.java
package org.jetbrains.kotlin.com.intellij.util.containers; import android.annotation.SuppressLint; import java.lang.reflect.Field; import java.security.AccessController; import java.security.PrivilegedAction; import sun.misc.Unsafe; public class UnsafeUtil { public static Unsafe findUnsafe() { try { return Unsafe.getUnsafe(); } catch (SecurityException se) { return AccessController.doPrivileged( (PrivilegedAction<Unsafe>) () -> { try { Class<Unsafe> type = Unsafe.class; try { @SuppressLint("DiscouragedPrivateApi") Field field = type.getDeclaredField("theUnsafe"); field.setAccessible(true); return type.cast(field.get(type)); } catch (Exception e) { for (Field field : type.getDeclaredFields()) { if (type.isAssignableFrom(field.getType())) { field.setAccessible(true); return type.cast(field.get(type)); } } } } catch (Exception e) { throw new RuntimeException("Unsafe unavailable", e); } throw new RuntimeException("Unsafe unavailable"); }); } } }
1,391
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
JavaVersion.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/kotlinc/src/main/java/org/jetbrains/kotlin/com/intellij/util/lang/JavaVersion.java
// // Source code recreated from a .class file by IntelliJ IDEA // (powered by FernFlower decompiler) // package org.jetbrains.kotlin.com.intellij.util.lang; public final class JavaVersion implements Comparable<JavaVersion> { public final int feature; public final int minor; public final int update; public final int build; public final boolean ea; private static JavaVersion current; private JavaVersion(int feature, int minor, int update, int build, boolean ea) { this.feature = feature; this.minor = minor; this.update = update; this.build = build; this.ea = ea; } public int compareTo(JavaVersion o) { int diff = this.feature - o.feature; if (diff != 0) { return diff; } else { diff = this.minor - o.minor; if (diff != 0) { return diff; } else { diff = this.update - o.update; if (diff != 0) { return diff; } else { diff = this.build - o.build; return diff != 0 ? diff : (this.ea ? 0 : 1) - (o.ea ? 0 : 1); } } } } public boolean equals(Object o) { if (this == o) { return true; } else if (!(o instanceof JavaVersion)) { return false; } else { JavaVersion other = (JavaVersion) o; return this.feature == other.feature && this.minor == other.minor && this.update == other.update && this.build == other.build && this.ea == other.ea; } } public int hashCode() { int hash = this.feature; hash = 31 * hash + this.minor; hash = 31 * hash + this.update; hash = 31 * hash + this.build; hash = 31 * hash + (this.ea ? 1231 : 1237); return hash; } public String toString() { return this.formatVersionTo(false, false); } private String formatVersionTo(boolean upToFeature, boolean upToUpdate) { StringBuilder sb = new StringBuilder(); if (this.feature > 8) { sb.append(this.feature); if (!upToFeature) { if (this.minor > 0 || this.update > 0) { sb.append('.').append(this.minor); } if (this.update > 0) { sb.append('.').append(this.update); } if (!upToUpdate) { if (this.ea) { sb.append("-ea"); } if (this.build > 0) { sb.append('+').append(this.build); } } } } else { sb.append("1.").append(this.feature); if (!upToFeature) { if (this.minor > 0 || this.update > 0 || this.ea || this.build > 0) { sb.append('.').append(this.minor); } if (this.update > 0) { sb.append('_').append(this.update); } if (!upToUpdate) { if (this.ea) { sb.append("-ea"); } if (this.build > 0) { sb.append("-b").append(this.build); } } } } return sb.toString(); } public static JavaVersion compose(int feature, int minor, int update, int build, boolean ea) throws IllegalArgumentException { if (feature < 0) { throw new IllegalArgumentException(); } else if (minor < 0) { throw new IllegalArgumentException(); } else if (update < 0) { throw new IllegalArgumentException(); } else if (build < 0) { throw new IllegalArgumentException(); } else { return new JavaVersion(feature, minor, update, build, ea); } } public static JavaVersion compose(int feature) { return compose(feature, 0, 0, 0, false); } public static JavaVersion current() { if (current == null) { JavaVersion fallback = parse(System.getProperty("java.version")); JavaVersion rt = rtVersion(); if (rt == null) { try { rt = parse(System.getProperty("java.runtime.version")); } catch (Throwable var3) { } } current = rt != null && rt.feature == fallback.feature && rt.minor == fallback.minor ? rt : fallback; } JavaVersion var10000 = current; return var10000; } private static JavaVersion rtVersion() { try { Object version = Runtime.class.getMethod("version").invoke((Object) null); int major = (Integer) version.getClass().getMethod("major").invoke(version); int minor = (Integer) version.getClass().getMethod("minor").invoke(version); int security = (Integer) version.getClass().getMethod("security").invoke(version); Object buildOpt = version.getClass().getMethod("build").invoke(version); int build = (Integer) buildOpt.getClass().getMethod("orElse", Object.class).invoke(buildOpt, 0); Object preOpt = version.getClass().getMethod("pre").invoke(version); boolean ea = (Boolean) preOpt.getClass().getMethod("isPresent").invoke(preOpt); return new JavaVersion(major, minor, security, build, ea); } catch (Throwable var8) { return null; } } public static JavaVersion parse(String versionString) throws IllegalArgumentException { return new JavaVersion(8, 0, 0, 69, false); } private static boolean startsWithWord(String s, String word) { return s.startsWith(word) && (s.length() == word.length() || !Character.isLetterOrDigit(s.charAt(word.length()))); } }
5,316
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
CompletionPrefixMatcher.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/completion-api/src/main/java/com/tyron/completion/CompletionPrefixMatcher.java
package com.tyron.completion; import me.xdrop.fuzzywuzzy.FuzzySearch; /** Logic of matching a completion name with a given completion prefix */ public class CompletionPrefixMatcher { /** The minimum score needed for a candidate to be considered as partial match. */ private static final int MINIMUM_SCORE = 70; /** * How well does the candidate name match the completion prefix. * * <p>THe ordinal values of the enum values imply the match level. The greater the ordinal value * is the better the candidate matches. It can be a safe key for sorting the matched candidates. * New value should be added to the right place to keep the ordinal value in order. */ public enum MatchLevel { NOT_MATCH, PARTIAL_MATCH, CASE_INSENSITIVE_PREFIX, CASE_SENSITIVE_PREFIX, CASE_INSENSITIVE_EQUAL, CASE_SENSITIVE_EQUAL } public static MatchLevel computeMatchLevel(String candidateName, String completionPrefix) { if (candidateName.startsWith(completionPrefix)) { return candidateName.length() == completionPrefix.length() ? MatchLevel.CASE_SENSITIVE_EQUAL : MatchLevel.CASE_SENSITIVE_PREFIX; } if (candidateName.toLowerCase().startsWith(completionPrefix.toLowerCase())) { return candidateName.length() == completionPrefix.length() ? MatchLevel.CASE_INSENSITIVE_EQUAL : MatchLevel.CASE_INSENSITIVE_PREFIX; } int score = FuzzySearch.ratio(candidateName, completionPrefix); if (score > MINIMUM_SCORE) { return MatchLevel.PARTIAL_MATCH; } return MatchLevel.NOT_MATCH; } }
1,605
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
InsertHandler.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/completion-api/src/main/java/com/tyron/completion/InsertHandler.java
package com.tyron.completion; import com.tyron.editor.Editor; /** Interface for customizing the how the completion item inserts the text */ public interface InsertHandler { void handleInsert(Editor editor); }
214
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
CompletionParameters.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/completion-api/src/main/java/com/tyron/completion/CompletionParameters.java
package com.tyron.completion; import com.tyron.builder.project.Project; import com.tyron.builder.project.api.Module; import com.tyron.editor.Editor; import java.io.File; /** Contains useful information about the current completion request */ public class CompletionParameters { private final Project mProject; private final Module mModule; private final File mFile; private final String mContents; private final String mPrefix; private final int mLine; private final int mColumn; private final long mIndex; private final Editor mEditor; public static Builder builder() { return new Builder(); } private CompletionParameters( Project project, Module module, Editor editor, File file, String contents, String prefix, int line, int column, long index) { mProject = project; mModule = module; mEditor = editor; mFile = file; mContents = contents; mPrefix = prefix; mLine = line; mColumn = column; mIndex = index; } public Project getProject() { return mProject; } public Module getModule() { return mModule; } public File getFile() { return mFile; } public String getContents() { return mContents; } public String getPrefix() { return mPrefix; } public int getLine() { return mLine; } public int getColumn() { return mColumn; } public long getIndex() { return mIndex; } public Editor getEditor() { return mEditor; } @Override public String toString() { return "CompletionParameters{" + "mProject=" + mProject + ", mModule=" + mModule + ", mFile=" + mFile + '\'' + ", mPrefix='" + mPrefix + '\'' + ", mLine=" + mLine + ", mColumn=" + mColumn + ", mIndex=" + mIndex + ", mEditor=" + mEditor + '}'; } public static final class Builder { private Project project; private Module module; private File file; private String contents; private String prefix; private int line; private int column; private long index; private Editor editor; private Builder() {} public Builder setProject(Project project) { this.project = project; return this; } public Builder setModule(Module module) { this.module = module; return this; } public Builder setFile(File file) { this.file = file; return this; } public Builder setContents(String contents) { this.contents = contents; return this; } public Builder setPrefix(String prefix) { this.prefix = prefix; return this; } public Builder setLine(int line) { this.line = line; return this; } public Builder setColumn(int column) { this.column = column; return this; } public Builder setIndex(long index) { this.index = index; return this; } public Builder setEditor(Editor editor) { this.editor = editor; return this; } public CompletionParameters build() { return new CompletionParameters( project, module, editor, file, contents, prefix, line, column, index); } } }
3,319
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
DefaultInsertHandler.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/completion-api/src/main/java/com/tyron/completion/DefaultInsertHandler.java
package com.tyron.completion; import com.tyron.completion.model.CompletionItem; import com.tyron.completion.util.CompletionUtils; import com.tyron.editor.Caret; import com.tyron.editor.CharPosition; import com.tyron.editor.Editor; import java.util.function.Predicate; public class DefaultInsertHandler implements InsertHandler { private final Predicate<Character> predicate; protected final CompletionItem item; public DefaultInsertHandler(CompletionItem item) { this(CompletionUtils.JAVA_PREDICATE, item); } public DefaultInsertHandler(Predicate<Character> predicate, CompletionItem item) { this.predicate = predicate; this.item = item; } protected String getPrefix(String line, CharPosition position) { return CompletionUtils.computePrefix(line, position, predicate); } protected void deletePrefix(Editor editor) { Caret caret = editor.getCaret(); String lineString = editor.getContent().getLineString(caret.getStartLine()); String prefix = getPrefix(lineString, getCharPosition(caret)); int length = prefix.length(); if (prefix.contains(".")) { length -= prefix.lastIndexOf('.') + 1; } editor.delete( caret.getStartLine(), caret.getStartColumn() - length, caret.getStartLine(), caret.getStartColumn()); } @Override public void handleInsert(Editor editor) { deletePrefix(editor); insert(item.commitText, editor, false); } protected void insert(String string, Editor editor, boolean calcSpace) { Caret caret = editor.getCaret(); if (string.contains("\n")) { editor.insertMultilineString(caret.getStartLine(), caret.getStartColumn(), string); } else { if (calcSpace) { if (isEndOfLine(caret.getStartLine(), caret.getStartColumn(), editor)) { string += " "; } } editor.insert(caret.getStartLine(), caret.getStartColumn(), string); } } protected void insert(String string, Editor editor) { insert(string, editor, true); } protected CharPosition getCharPosition(Caret caret) { return new CharPosition(caret.getStartLine(), caret.getEndColumn()); } public boolean isEndOfLine(int line, int column, Editor editor) { String lineString = editor.getContent().getLineString(line); String substring = lineString.substring(column); return substring.trim().isEmpty(); } }
2,390
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
CompletionProvider.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/completion-api/src/main/java/com/tyron/completion/CompletionProvider.java
package com.tyron.completion; import android.annotation.SuppressLint; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.Multimap; import com.tyron.completion.model.CompletionList; import com.tyron.completion.progress.ProgressManager; import com.tyron.language.api.Language; import com.tyron.language.fileTypes.FileTypeManager; import com.tyron.language.fileTypes.LanguageFileType; import java.io.File; import java.util.Collection; import org.jetbrains.annotations.NotNull; /** * Subclass this to provide completions on the given file. * * <p>Be sure to frequently call {@link ProgressManager#checkCanceled()} for the user to have a * smooth experience because the user may be typing fast and operations may be cancelled at that * time. */ public abstract class CompletionProvider { private static final Multimap<Language, CompletionProvider> sRegisteredCompletionProviders = ArrayListMultimap.create(); public abstract boolean accept(File file); public abstract CompletionList complete(CompletionParameters parameters); @SuppressLint("NewApi") public static ImmutableList<CompletionProvider> forParameters( @NotNull CompletionParameters parameters) { File file = parameters.getFile(); LanguageFileType fileType = FileTypeManager.getInstance().findFileType(file); if (fileType == null) { return ImmutableList.of(); } Collection<CompletionProvider> providers = sRegisteredCompletionProviders.get(fileType.getLanguage()); if (providers == null) { return ImmutableList.of(); } return providers.stream() .filter(it -> it.accept(file)) .collect(ImmutableList.toImmutableList()); } public static ImmutableList<CompletionProvider> forLanguage(@NotNull Language language) { return ImmutableList.copyOf(sRegisteredCompletionProviders.get(language)); } public static void registerCompletionProvider( @NotNull Language language, CompletionProvider provider) { if (sRegisteredCompletionProviders.containsEntry(language, provider)) { return; } sRegisteredCompletionProviders.put(language, provider); } }
2,215
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
ProgressManager.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/completion-api/src/main/java/com/tyron/completion/progress/ProgressManager.java
package com.tyron.completion.progress; import android.app.ProgressDialog; import android.content.Context; import android.os.Handler; import android.os.Looper; import com.google.common.util.concurrent.AsyncCallable; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import java.util.Map; import java.util.WeakHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.function.Consumer; public class ProgressManager { private static ProgressManager sInstance = null; public static ProgressManager getInstance() { if (sInstance == null) { sInstance = new ProgressManager(); } return sInstance; } public static void checkCanceled() { getInstance().doCheckCanceled(); } private final ExecutorService mPool = Executors.newFixedThreadPool(32); private final Handler mMainHandler = new Handler(Looper.getMainLooper()); private final Map<Thread, ProgressIndicator> mThreadToIndicator; public ProgressManager() { mThreadToIndicator = new WeakHashMap<>(); } /** * Run a cancelable asynchronous task. * * @param runnable The task to run * @param cancelConsumer The code to run when this task has been canceled, called from background * thread * @param indicator The class used to control this task's execution */ public void runAsync( Runnable runnable, Consumer<ProgressIndicator> cancelConsumer, ProgressIndicator indicator) { mPool.execute( () -> { Thread currentThread = Thread.currentThread(); try { mThreadToIndicator.put(currentThread, indicator); indicator.setRunning(true); runnable.run(); } catch (ProcessCanceledException e) { cancelConsumer.accept(indicator); } finally { indicator.setRunning(false); mThreadToIndicator.remove(currentThread); } }); } public void runAsync(Context uiContext, Runnable runnable, ProgressIndicator indicator) { ProgressDialog dialog = new ProgressDialog(uiContext); dialog.show(); runAsync( runnable, i -> { dialog.dismiss(); }, indicator); } /** * Run a non cancelable task in the background. If the task has been running for more than two * seconds, The loadingRunnable will be run. If the task has finished before 2000, the * loadingRunnable will not be called. * * @param taskToRun The task to run * @param loadingRunnable The runnable to run if the task has been running for more than 2 seconds * @param finishRunnable The task to run after the task has finished */ public void runNonCancelableAsync( Runnable taskToRun, Runnable loadingRunnable, Runnable finishRunnable) { runNonCancelableAsync( () -> { taskToRun.run(); cancelRunLater(loadingRunnable); finishRunnable.run(); }); runLater(loadingRunnable, 2000); } /** * Run an asynchronous operation that is not cancelable. * * @param runnable The code to run */ public void runNonCancelableAsync(Runnable runnable) { mPool.execute(runnable); } public <T> ListenableFuture<T> computeNonCancelableAsync(AsyncCallable<T> callable) { return Futures.submitAsync(callable, mPool); } /** * Posts the runnable into the UI thread to be run later. * * @param runnable The code to run */ public void runLater(Runnable runnable) { mMainHandler.post(runnable); } /** * Posts the runnable into the UI thread to be run later. * * @param runnable The code to run */ public void runLater(Runnable runnable, long delay) { mMainHandler.postDelayed(runnable, delay); } public void cancelRunLater(Runnable runnable) { mMainHandler.removeCallbacks(runnable); } public void cancelThread(Thread thread) { ProgressIndicator indicator = mThreadToIndicator.get(thread); if (indicator == null) { indicator = new ProgressIndicator(); } indicator.cancel(); mThreadToIndicator.put(thread, indicator); } private void doCheckCanceled() { ProgressIndicator indicator = mThreadToIndicator.get(Thread.currentThread()); if (indicator != null) { if (indicator.isCanceled()) { mThreadToIndicator.remove(Thread.currentThread()); throw new ProcessCanceledException(); } } } }
4,482
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
ProgressIndicator.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/completion-api/src/main/java/com/tyron/completion/progress/ProgressIndicator.java
package com.tyron.completion.progress; public class ProgressIndicator { private volatile boolean mCanceled; private volatile boolean mRunning; public ProgressIndicator() {} public void setCanceled(boolean cancel) { mCanceled = cancel; } public void cancel() { setCanceled(true); } public boolean isCanceled() { return mCanceled; } public void setRunning(boolean b) { mRunning = b; } public boolean isRunning() { return mRunning; } }
487
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
ProcessCanceledException.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/completion-api/src/main/java/com/tyron/completion/progress/ProcessCanceledException.java
package com.tyron.completion.progress; /** Thrown when a certain process must be canceled. */ public class ProcessCanceledException extends RuntimeException { public ProcessCanceledException() { super(); } public ProcessCanceledException(Throwable cause) { super(cause); if (cause instanceof ProcessCanceledException) { throw new IllegalArgumentException("Must not self-wrap ProcessCanceledException."); } } }
443
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
CompletionEngine.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/completion-api/src/main/java/com/tyron/completion/main/CompletionEngine.java
package com.tyron.completion.main; import com.google.common.base.Throwables; import com.tyron.builder.project.Project; import com.tyron.builder.project.api.Module; import com.tyron.common.logging.IdeLog; import com.tyron.completion.CompletionParameters; import com.tyron.completion.CompletionProvider; import com.tyron.completion.model.CompletionList; import com.tyron.completion.progress.ProcessCanceledException; import com.tyron.editor.Editor; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; /** Main entry point for the completions api. */ public class CompletionEngine { private static CompletionEngine sInstance = null; public static CompletionEngine getInstance() { if (sInstance == null) { sInstance = new CompletionEngine(); } return sInstance; } private final Logger logger = IdeLog.getCurrentLogger(this); public CompletionEngine() {} public CompletionList complete( Project project, Module module, Editor editor, File file, String contents, String prefix, int line, int column, long index) { if (project.isCompiling() || project.isIndexing()) { return CompletionList.EMPTY; } CompletionList list = new CompletionList(); list.items = new ArrayList<>(); CompletionParameters parameters = CompletionParameters.builder() .setProject(project) .setModule(module) .setEditor(editor) .setFile(file) .setContents(contents) .setPrefix(prefix) .setLine(line) .setColumn(column) .setIndex(index) .build(); List<CompletionProvider> providers = CompletionProvider.forParameters(parameters); for (CompletionProvider provider : providers) { try { CompletionList complete = provider.complete(parameters); if (complete != null) { list.items.addAll(complete.items); } } catch (Throwable e) { if (e instanceof ProcessCanceledException) { throw e; } String message = "Failed to complete: \n" + "index: " + index + "\n" + "prefix: " + prefix + "\n" + "File: " + file.getName() + "\n" + "Stack trace: " + Throwables.getStackTraceAsString(e); logger.severe(message); } } return list; } }
2,581
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
CompilerService.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/completion-api/src/main/java/com/tyron/completion/index/CompilerService.java
package com.tyron.completion.index; import com.tyron.builder.project.Project; import com.tyron.builder.project.api.Module; import java.util.LinkedHashMap; import java.util.Map; public class CompilerService { private static CompilerService sInstance = null; public static CompilerService getInstance() { if (sInstance == null) { sInstance = new CompilerService(); } return sInstance; } private final Map<String, CompilerProvider<?>> mIndexProviders; public CompilerService() { mIndexProviders = new LinkedHashMap<>(); } public <T> void registerIndexProvider(String key, CompilerProvider<T> provider) { mIndexProviders.put(key, provider); } public <T> T getIndex(String key) { //noinspection unchecked return (T) mIndexProviders.get(key); } public void index(Project project, Module module) { for (CompilerProvider<?> provider : mIndexProviders.values()) { provider.get(project, module); } } public void clear() { mIndexProviders.clear(); } public boolean isEmpty() { return mIndexProviders.isEmpty(); } }
1,103
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
CompilerProvider.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/completion-api/src/main/java/com/tyron/completion/index/CompilerProvider.java
package com.tyron.completion.index; import com.tyron.builder.project.Project; import com.tyron.builder.project.api.Module; public abstract class CompilerProvider<T> { public abstract T get(Project project, Module module); }
229
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
CompletionUtils.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/completion-api/src/main/java/com/tyron/completion/util/CompletionUtils.java
package com.tyron.completion.util; import com.tyron.editor.CharPosition; import java.util.function.Predicate; public class CompletionUtils { public static final Predicate<Character> JAVA_PREDICATE = it -> Character.isJavaIdentifierPart(it) || it == '.'; public static String computePrefix( CharSequence line, CharPosition position, Predicate<Character> predicate) { int begin = position.getColumn(); for (; begin > 0; begin--) { if (!predicate.test(line.charAt(begin - 1))) { break; } } return String.valueOf(line.subSequence(begin, position.getColumn())); } }
619
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
RewriteUtil.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/completion-api/src/main/java/com/tyron/completion/util/RewriteUtil.java
package com.tyron.completion.util; import com.google.common.base.Throwables; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.tyron.common.logging.IdeLog; import com.tyron.common.util.ThreadUtil; import com.tyron.completion.model.Range; import com.tyron.completion.model.Rewrite; import com.tyron.completion.model.TextEdit; import com.tyron.completion.progress.ProgressManager; import com.tyron.editor.CharPosition; import com.tyron.editor.Editor; import java.io.File; import java.nio.file.Path; import java.util.Map; import java.util.logging.Logger; import org.checkerframework.checker.nullness.qual.Nullable; public class RewriteUtil { private static final Logger sLogger = IdeLog.getCurrentLogger(RewriteUtil.class); public static <T> void performRewrite( Editor editor, File file, T neededClass, Rewrite<T> rewrite) { ListenableFuture<Map<Path, TextEdit[]>> future = ProgressManager.getInstance() .computeNonCancelableAsync( () -> { Map<Path, TextEdit[]> edits = rewrite.rewrite(neededClass); if (edits == Rewrite.CANCELLED) { throw new RuntimeException("Rewrite cancelled."); } return Futures.immediateFuture(edits); }); Futures.addCallback( future, new FutureCallback<Map<Path, TextEdit[]>>() { @Override public void onSuccess(@Nullable Map<Path, TextEdit[]> result) { if (result == null) { return; } TextEdit[] textEdits = result.get(file.toPath()); if (textEdits == null) { return; } editor.beginBatchEdit(); for (TextEdit textEdit : textEdits) { applyTextEdit(editor, textEdit); } editor.endBatchEdit(); } @Override public void onFailure(Throwable t) { // TODO: Handle errors sLogger.severe("Failed to perform rewrite, " + Throwables.getStackTraceAsString(t)); } }, ThreadUtil::runOnUiThread); } public static void applyTextEdit(Editor editor, TextEdit edit) { int startFormat; int endFormat; Range range = edit.range; if (range.start.line == -1 && range.start.column == -1 || (range.end.line == -1 && range.end.column == -1)) { CharPosition startChar = editor.getCharPosition((int) range.start.start); CharPosition endChar = editor.getCharPosition((int) range.end.end); if (range.start.start == range.end.end) { editor.insert(startChar.getLine(), startChar.getColumn(), edit.newText); } else { editor.replace( startChar.getLine(), startChar.getColumn(), endChar.getLine(), endChar.getColumn(), edit.newText); } startFormat = (int) range.start.start; } else { if (range.start.equals(range.end)) { editor.insert(range.start.line, range.start.column, edit.newText); } else { editor.replace( range.start.line, range.start.column, range.end.line, range.end.column, edit.newText); } startFormat = editor.getCharIndex(range.start.line, range.start.column); } endFormat = startFormat + edit.newText.length(); if (startFormat < endFormat) { if (edit.needFormat) { editor.formatCodeAsync(startFormat, endFormat); } } } }
3,620
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
CompletionList.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/completion-api/src/main/java/com/tyron/completion/model/CompletionList.java
package com.tyron.completion.model; import com.google.common.collect.Ordering; import com.google.errorprone.annotations.Immutable; import com.tyron.completion.CompletionPrefixMatcher; import com.tyron.completion.CompletionPrefixMatcher.MatchLevel; import com.tyron.completion.CompletionProvider; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; /** Represents a list of completion items to be return from a {@link CompletionProvider} */ @Immutable public class CompletionList { public static final Ordering<CompletionItem> ITEM_ORDERING = Ordering.from(CompletionItem.COMPARATOR); public static Builder builder(String prefix) { return new Builder(prefix); } public static final CompletionList EMPTY = new CompletionList(); public boolean isIncomplete = false; public List<CompletionItem> items = new ArrayList<>(); /** * For performance reasons, the completion items are limited to a certain amount. A completion * provider may indicate that its results are incomplete so next as the user is typing the prefix * the completion system will not cache this results. * * @return whether the list is incomplete */ public boolean isIncomplete() { return isIncomplete; } public void setIncomplete(boolean incomplete) { isIncomplete = incomplete; } public List<CompletionItem> getItems() { return items; } public static CompletionList copy(CompletionList old, String newPrefix) { Builder builder = CompletionList.builder(newPrefix); if (old.isIncomplete) { builder.incomplete(); } builder.addItems(old.getItems()); return builder.build(); } public static class Builder { private final List<CompletionItem> items; private boolean incomplete; private final String completionPrefix; public Builder(String completionPrefix) { items = new ArrayList<>(); this.completionPrefix = completionPrefix; } public String getPrefix() { return completionPrefix; } public Builder addItems(Collection<CompletionItem> items) { for (CompletionItem item : items) { addItem(item); } return this; } public Builder addItems(Collection<CompletionItem> items, String sortText) { for (CompletionItem item : items) { item.setSortText(sortText); addItem(item); } return this; } public Builder addItem(CompletionItem item) { List<MatchLevel> matchLevels = new ArrayList<>(); for (String filterText : item.getFilterTexts()) { MatchLevel matchLevel = CompletionPrefixMatcher.computeMatchLevel(filterText, completionPrefix); if (matchLevel == MatchLevel.NOT_MATCH) { continue; } matchLevels.add(matchLevel); } if (matchLevels.isEmpty()) { return this; } Collections.sort(matchLevels); MatchLevel matchLevel = matchLevels.get(matchLevels.size() - 1); item.setMatchLevel(matchLevel); items.add(item); return this; } public int getItemCount() { return items.size(); } public void incomplete() { this.incomplete = true; } public boolean isIncomplete() { return incomplete; } @SuppressWarnings("NewApi") public CompletionList build() { CompletionList list = new CompletionList(); list.isIncomplete = this.incomplete; list.items = ITEM_ORDERING.immutableSortedCopy(items); return list; } } }
3,558
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
TextEdit.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/completion-api/src/main/java/com/tyron/completion/model/TextEdit.java
package com.tyron.completion.model; /** Class that represents an edit that should be applied on the target file */ public class TextEdit { public Range range; public String newText; public boolean needFormat; public TextEdit() {} public TextEdit(Range range, String newText) { this.range = range; this.newText = newText; this.needFormat = false; } public TextEdit(Range range, String newText, boolean needFormat) { this.range = range; this.newText = newText; this.needFormat = needFormat; } @Override public String toString() { return range + "/" + newText; } public static final TextEdit NONE = new TextEdit(Range.NONE, ""); }
686
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
DrawableKind.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/completion-api/src/main/java/com/tyron/completion/model/DrawableKind.java
package com.tyron.completion.model; public enum DrawableKind { Attribute("A", 0xffcc7832), Method("m", 0xffe92e2e), Interface("I", 0xffcc7832), Field("F", 0xffcc7832), Class("C", 0xff1c9344), Keyword("K", 0xffcc7832), Package("P", 0xffcc7832), Lambda("λ", 0xff36b9da), Snippet("S", 0xffcc7832), LocalVariable("V", 0xffcc7832); private final int color; private final String prefix; DrawableKind(String prefix, int color) { this.prefix = prefix; this.color = color; } public String getValue() { return prefix; } public int getColor() { return color; } }
610
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
Position.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/completion-api/src/main/java/com/tyron/completion/model/Position.java
package com.tyron.completion.model; /** Represents the position in the editor in terms of lines and columns */ public class Position { public static final Position NONE = new Position(-1, -1); public int line; public int column; public long start; public long end; public Position(long start, long end) { this.start = start; this.end = end; line = -1; column = -1; } public Position(int line, int column) { this.line = line; this.column = column; start = -1; column = -1; } @Override public boolean equals(Object object) { if (!(object instanceof Position)) { return false; } Position that = (Position) object; return (this.line == that.line && this.column == that.column); } @Override public int hashCode() { return line + column; } }
833
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
Range.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/completion-api/src/main/java/com/tyron/completion/model/Range.java
package com.tyron.completion.model; public class Range { public Position start, end; public Range(long startPosition, long endPosition) { start = new Position(startPosition, startPosition); end = new Position(endPosition, endPosition); } public Range(Position start, Position end) { this.start = start; this.end = end; } @Override public String toString() { return start + "-" + end; } public static final Range NONE = new Range(Position.NONE, Position.NONE); }
505
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
CachedCompletion.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/completion-api/src/main/java/com/tyron/completion/model/CachedCompletion.java
package com.tyron.completion.model; import java.io.File; public class CachedCompletion { private final File file; private final int line; private final int column; private final String prefix; private final CompletionList completionList; public CachedCompletion( File file, int line, int column, String prefix, CompletionList completionList) { this.file = file; this.line = line; this.column = column; this.prefix = prefix; this.completionList = completionList; } public File getFile() { return file; } public int getLine() { return line; } public int getColumn() { return column; } public String getPrefix() { return prefix; } public CompletionList getCompletionList() { return completionList; } }
787
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
CompletionItem.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/completion-api/src/main/java/com/tyron/completion/model/CompletionItem.java
package com.tyron.completion.model; import com.google.common.collect.ImmutableList; import com.tyron.completion.CompletionPrefixMatcher; import com.tyron.completion.DefaultInsertHandler; import com.tyron.completion.InsertHandler; import com.tyron.completion.util.CompletionUtils; import com.tyron.editor.Editor; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Objects; /** A class representing the completion item shown in the user list */ public class CompletionItem implements Comparable<CompletionItem> { @SuppressWarnings("NewApi") public static final Comparator<CompletionItem> COMPARATOR = Comparator.comparing( (CompletionItem item) -> item.getMatchLevel().ordinal(), Comparator.reverseOrder()) .thenComparing(CompletionItem::getSortText) .thenComparing( it -> it.getFilterTexts().isEmpty() ? it.getLabel() : it.getFilterTexts().get(0)); public static CompletionItem create(String label, String detail, String commitText) { return create(label, detail, commitText, null); } public static CompletionItem create( String label, String detail, String commitText, DrawableKind kind) { CompletionItem completionItem = new CompletionItem(label, detail, commitText, kind); completionItem.sortText = ""; completionItem.matchLevel = CompletionPrefixMatcher.MatchLevel.NOT_MATCH; return completionItem; } private InsertHandler insertHandler; public String label; public String detail; public String commitText; public Kind action = Kind.NORMAL; public DrawableKind iconKind = DrawableKind.Method; public int cursorOffset = -1; public List<TextEdit> additionalTextEdits; public String data = ""; private String sortText; private List<String> filterTexts = new ArrayList<>(1); private CompletionPrefixMatcher.MatchLevel matchLevel; public CompletionItem() { this.insertHandler = new DefaultInsertHandler(CompletionUtils.JAVA_PREDICATE, this); this.sortText = ""; } public CompletionItem(String label, String details, String commitText, DrawableKind kind) { this.label = label; this.detail = details; this.commitText = commitText; this.cursorOffset = commitText.length(); this.iconKind = kind; this.insertHandler = new DefaultInsertHandler(CompletionUtils.JAVA_PREDICATE, this); this.sortText = ""; } public CompletionItem(String label) { this.label = label; } public void setSortText(String sortText) { this.sortText = sortText; } public ImmutableList<String> getFilterTexts() { if (filterTexts.isEmpty()) { return ImmutableList.of(label); } return ImmutableList.copyOf(filterTexts); } public void addFilterText(String text) { filterTexts.add(text); } public String getSortText() { return sortText; } public CompletionPrefixMatcher.MatchLevel getMatchLevel() { return matchLevel; } public String getLabel() { return label; } public void setMatchLevel(CompletionPrefixMatcher.MatchLevel matchLevel) { this.matchLevel = matchLevel; } public enum Kind { OVERRIDE, IMPORT, NORMAL } public void setInsertHandler(InsertHandler handler) { this.insertHandler = handler; } @Override public String toString() { return label; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof CompletionItem)) { return false; } CompletionItem that = (CompletionItem) o; return cursorOffset == that.cursorOffset && Objects.equals(label, that.label) && Objects.equals(detail, that.detail) && Objects.equals(commitText, that.commitText) && action == that.action && iconKind == that.iconKind && Objects.equals(additionalTextEdits, that.additionalTextEdits) && Objects.equals(data, that.data); } @Override public int hashCode() { return Objects.hash( label, detail, commitText, action, iconKind, cursorOffset, additionalTextEdits, data); } @Override public int compareTo(CompletionItem o) { return COMPARATOR.compare(this, o); } public void handleInsert(Editor editor) { insertHandler.handleInsert(editor); } }
4,298
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
Rewrite.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/completion-api/src/main/java/com/tyron/completion/model/Rewrite.java
package com.tyron.completion.model; import java.nio.file.Path; import java.util.Collections; import java.util.Map; /** * An interface for calculating text edits in the editor. * * @param <T> The class needed for this rewrite to calculate its edits. */ public interface Rewrite<T> { /** Convenience field to use when a rewrite has been cancelled */ Map<Path, TextEdit[]> CANCELLED = Collections.emptyMap(); /** * Calculate the rewrites needed to a file * * @param t The needed class to calculate this rewrite * @return map of path and the text edits that should be applied on that file. */ Map<Path, TextEdit[]> rewrite(T t); }
658
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
MaterialAlertDialogBuilder.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/android-stubs/src/main/java/com/google/android/material/dialog/MaterialAlertDialogBuilder.java
/* * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.material.dialog; import android.content.Context; import android.content.DialogInterface.OnCancelListener; import android.content.DialogInterface.OnClickListener; import android.content.DialogInterface.OnDismissListener; import android.content.DialogInterface.OnKeyListener; import android.content.DialogInterface.OnMultiChoiceClickListener; import android.database.Cursor; import android.graphics.drawable.Drawable; import android.view.View; import android.widget.AdapterView; import android.widget.ListAdapter; import androidx.annotation.ArrayRes; import androidx.annotation.AttrRes; import androidx.annotation.DrawableRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.Px; import androidx.annotation.StringRes; import androidx.appcompat.app.AlertDialog; /** * An extension of {@link AlertDialog.Builder} for use with a Material theme (e.g., * Theme.MaterialComponents). * * <p>This Builder must be used in order for AlertDialog objects to respond to color and shape * theming provided by Material themes. * * <p>The type of dialog returned is still an {@link AlertDialog}; there is no specific Material * implementation of {@link AlertDialog}. */ public class MaterialAlertDialogBuilder extends AlertDialog.Builder { public MaterialAlertDialogBuilder(@NonNull Context context) { throw new RuntimeException("Stub!"); } public MaterialAlertDialogBuilder(@NonNull Context context, int overrideThemeResId) { throw new RuntimeException("Stub!"); } @NonNull @Override public AlertDialog create() { throw new RuntimeException("Stub!"); } @Nullable public Drawable getBackground() { throw new RuntimeException("Stub!"); } @NonNull public MaterialAlertDialogBuilder setBackground(@Nullable Drawable background) { throw new RuntimeException("Stub!"); } @NonNull public MaterialAlertDialogBuilder setBackgroundInsetStart(@Px int backgroundInsetStart) { throw new RuntimeException("Stub!"); } @NonNull public MaterialAlertDialogBuilder setBackgroundInsetTop(@Px int backgroundInsetTop) { throw new RuntimeException("Stub!"); } @NonNull public MaterialAlertDialogBuilder setBackgroundInsetEnd(@Px int backgroundInsetEnd) { throw new RuntimeException("Stub!"); } @NonNull public MaterialAlertDialogBuilder setBackgroundInsetBottom(@Px int backgroundInsetBottom) { throw new RuntimeException("Stub!"); } // The following methods are all pass-through methods used to specify the return type for the // builder chain. @NonNull @Override public MaterialAlertDialogBuilder setTitle(@StringRes int titleId) { throw new RuntimeException("Stub!"); } @NonNull @Override public MaterialAlertDialogBuilder setTitle(@Nullable CharSequence title) { throw new RuntimeException("Stub!"); } @NonNull @Override public MaterialAlertDialogBuilder setCustomTitle(@Nullable View customTitleView) { throw new RuntimeException("Stub!"); } @NonNull @Override public MaterialAlertDialogBuilder setMessage(@StringRes int messageId) { throw new RuntimeException("Stub!"); } @NonNull @Override public MaterialAlertDialogBuilder setMessage(@Nullable CharSequence message) { throw new RuntimeException("Stub!"); } @NonNull @Override public MaterialAlertDialogBuilder setIcon(@DrawableRes int iconId) { throw new RuntimeException("Stub!"); } @NonNull @Override public MaterialAlertDialogBuilder setIcon(@Nullable Drawable icon) { throw new RuntimeException("Stub!"); } @NonNull @Override public MaterialAlertDialogBuilder setIconAttribute(@AttrRes int attrId) { throw new RuntimeException("Stub!"); } @NonNull @Override public MaterialAlertDialogBuilder setPositiveButton( @StringRes int textId, @Nullable final OnClickListener listener) { throw new RuntimeException("Stub!"); } @NonNull @Override public MaterialAlertDialogBuilder setPositiveButton( @Nullable CharSequence text, @Nullable final OnClickListener listener) { return (MaterialAlertDialogBuilder) super.setPositiveButton(text, listener); } @NonNull @Override public MaterialAlertDialogBuilder setPositiveButtonIcon(@Nullable Drawable icon) { throw new RuntimeException("Stub!"); } @NonNull @Override public MaterialAlertDialogBuilder setNegativeButton( @StringRes int textId, @Nullable final OnClickListener listener) { throw new RuntimeException("Stub!"); } @NonNull @Override public MaterialAlertDialogBuilder setNegativeButton( @Nullable CharSequence text, @Nullable final OnClickListener listener) { throw new RuntimeException("Stub!"); } @NonNull @Override public MaterialAlertDialogBuilder setNegativeButtonIcon(@Nullable Drawable icon) { throw new RuntimeException("Stub!"); } @NonNull @Override public MaterialAlertDialogBuilder setNeutralButton( @StringRes int textId, @Nullable final OnClickListener listener) { throw new RuntimeException("Stub!"); } @NonNull @Override public MaterialAlertDialogBuilder setNeutralButton( @Nullable CharSequence text, @Nullable final OnClickListener listener) { return (MaterialAlertDialogBuilder) super.setNeutralButton(text, listener); } @NonNull @Override public MaterialAlertDialogBuilder setNeutralButtonIcon(@Nullable Drawable icon) { throw new RuntimeException("Stub!"); } @NonNull @Override public MaterialAlertDialogBuilder setCancelable(boolean cancelable) { throw new RuntimeException("Stub!"); } @NonNull @Override public MaterialAlertDialogBuilder setOnCancelListener( @Nullable OnCancelListener onCancelListener) { throw new RuntimeException("Stub!"); } @NonNull @Override public MaterialAlertDialogBuilder setOnDismissListener( @Nullable OnDismissListener onDismissListener) { throw new RuntimeException("Stub!"); } @NonNull @Override public MaterialAlertDialogBuilder setOnKeyListener(@Nullable OnKeyListener onKeyListener) { throw new RuntimeException("Stub!"); } @NonNull @Override public MaterialAlertDialogBuilder setItems( @ArrayRes int itemsId, @Nullable final OnClickListener listener) { throw new RuntimeException("Stub!"); } @NonNull @Override public MaterialAlertDialogBuilder setItems( @Nullable CharSequence[] items, @Nullable final OnClickListener listener) { throw new RuntimeException("Stub!"); } @NonNull @Override public MaterialAlertDialogBuilder setAdapter( @Nullable final ListAdapter adapter, @Nullable final OnClickListener listener) { throw new RuntimeException("Stub!"); } @NonNull @Override public MaterialAlertDialogBuilder setCursor( @Nullable final Cursor cursor, @Nullable final OnClickListener listener, @NonNull String labelColumn) { throw new RuntimeException("Stub!"); } @NonNull @Override public MaterialAlertDialogBuilder setMultiChoiceItems( @ArrayRes int itemsId, @Nullable boolean[] checkedItems, @Nullable final OnMultiChoiceClickListener listener) { throw new RuntimeException("Stub!"); } @NonNull @Override public MaterialAlertDialogBuilder setMultiChoiceItems( @Nullable CharSequence[] items, @Nullable boolean[] checkedItems, @Nullable final OnMultiChoiceClickListener listener) { throw new RuntimeException("Stub!"); } @NonNull @Override public MaterialAlertDialogBuilder setMultiChoiceItems( @Nullable Cursor cursor, @NonNull String isCheckedColumn, @NonNull String labelColumn, @Nullable final OnMultiChoiceClickListener listener) { throw new RuntimeException("Stub!"); } @NonNull @Override public MaterialAlertDialogBuilder setSingleChoiceItems( @ArrayRes int itemsId, int checkedItem, @Nullable final OnClickListener listener) { throw new RuntimeException("Stub!"); } @NonNull @Override public MaterialAlertDialogBuilder setSingleChoiceItems( @Nullable Cursor cursor, int checkedItem, @NonNull String labelColumn, @Nullable final OnClickListener listener) { throw new RuntimeException("Stub!"); } @NonNull @Override public MaterialAlertDialogBuilder setSingleChoiceItems( @Nullable CharSequence[] items, int checkedItem, @Nullable final OnClickListener listener) { throw new RuntimeException("Stub!"); } @NonNull @Override public MaterialAlertDialogBuilder setSingleChoiceItems( @Nullable ListAdapter adapter, int checkedItem, @Nullable final OnClickListener listener) { throw new RuntimeException("Stub!"); } @NonNull @Override public MaterialAlertDialogBuilder setOnItemSelectedListener( @Nullable final AdapterView.OnItemSelectedListener listener) { throw new RuntimeException("Stub!"); } @NonNull @Override public MaterialAlertDialogBuilder setView(int layoutResId) { throw new RuntimeException("Stub!"); } @NonNull @Override public MaterialAlertDialogBuilder setView(@Nullable View view) { throw new RuntimeException("Stub!"); } }
9,820
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
LiveData.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/android-stubs/src/main/java/androidx/lifecycle/LiveData.java
package androidx.lifecycle; public class LiveData<T> { public T getValue() { throw new RuntimeException("Stub"); } }
127
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
MutableLiveData.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/android-stubs/src/main/java/androidx/lifecycle/MutableLiveData.java
package androidx.lifecycle; public class MutableLiveData<T> extends LiveData<T> { public MutableLiveData(T objects) { super(); } public void setValue(T value) { throw new RuntimeException("Stub!"); } }
221
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
Toolbar.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/android-stubs/src/main/java/androidx/appcompat/widget/Toolbar.java
package androidx.appcompat.widget; import android.content.Context; import android.util.AttributeSet; import android.view.ViewGroup; public class Toolbar extends ViewGroup { public Toolbar(Context context) { super(context); } public Toolbar(Context context, AttributeSet attrs) { super(context, attrs); } public Toolbar(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public Toolbar(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } @Override protected void onLayout(boolean b, int i, int i1, int i2, int i3) {} }
679
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
AlertDialog.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/android-stubs/src/main/java/androidx/appcompat/app/AlertDialog.java
package androidx.appcompat.app; import android.content.DialogInterface; import android.database.Cursor; import android.graphics.drawable.Drawable; import android.view.View; import android.widget.AdapterView; import android.widget.ListAdapter; import androidx.annotation.ArrayRes; import androidx.annotation.AttrRes; import androidx.annotation.DrawableRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.StringRes; public class AlertDialog { public void dismiss() { throw new RuntimeException("Stub!"); } public static class Builder { @NonNull public AlertDialog create() { throw new RuntimeException("Stub!"); } @NonNull public AlertDialog.Builder setTitle(@StringRes int titleId) { throw new RuntimeException("Stub!"); } @NonNull public AlertDialog.Builder setTitle(@Nullable CharSequence title) { throw new RuntimeException("Stub!"); } @NonNull public AlertDialog.Builder setCustomTitle(@Nullable View customTitleView) { throw new RuntimeException("Stub!"); } @NonNull public AlertDialog.Builder setMessage(@StringRes int messageId) { throw new RuntimeException("Stub!"); } @NonNull public AlertDialog.Builder setMessage(@Nullable CharSequence message) { throw new RuntimeException("Stub!"); } @NonNull public AlertDialog.Builder setIcon(@DrawableRes int iconId) { throw new RuntimeException("Stub!"); } @NonNull public AlertDialog.Builder setIcon(@Nullable Drawable icon) { throw new RuntimeException("Stub!"); } @NonNull public AlertDialog.Builder setIconAttribute(@AttrRes int attrId) { throw new RuntimeException("Stub!"); } @NonNull public AlertDialog.Builder setPositiveButton( @StringRes int textId, @Nullable final DialogInterface.OnClickListener listener) { throw new RuntimeException("Stub!"); } @NonNull public AlertDialog.Builder setPositiveButton( @Nullable CharSequence text, @Nullable final DialogInterface.OnClickListener listener) { throw new RuntimeException("Stub!"); } @NonNull public AlertDialog.Builder setPositiveButtonIcon(@Nullable Drawable icon) { throw new RuntimeException("Stub!"); } @NonNull public AlertDialog.Builder setNegativeButton( @StringRes int textId, @Nullable final DialogInterface.OnClickListener listener) { throw new RuntimeException("Stub!"); } @NonNull public AlertDialog.Builder setNegativeButton( @Nullable CharSequence text, @Nullable final DialogInterface.OnClickListener listener) { throw new RuntimeException("Stub!"); } @NonNull public AlertDialog.Builder setNegativeButtonIcon(@Nullable Drawable icon) { throw new RuntimeException("Stub!"); } @NonNull public AlertDialog.Builder setNeutralButton( @StringRes int textId, @Nullable final DialogInterface.OnClickListener listener) { throw new RuntimeException("Stub!"); } @NonNull public AlertDialog.Builder setNeutralButton( @Nullable CharSequence text, @Nullable final DialogInterface.OnClickListener listener) { throw new RuntimeException("Stub!"); } @NonNull public AlertDialog.Builder setNeutralButtonIcon(@Nullable Drawable icon) { throw new RuntimeException("Stub!"); } @NonNull public AlertDialog.Builder setCancelable(boolean cancelable) { throw new RuntimeException("Stub!"); } @NonNull public AlertDialog.Builder setOnCancelListener( @Nullable DialogInterface.OnCancelListener onCancelListener) { throw new RuntimeException("Stub!"); } @NonNull public AlertDialog.Builder setOnDismissListener( @Nullable DialogInterface.OnDismissListener onDismissListener) { throw new RuntimeException("Stub!"); } @NonNull public AlertDialog.Builder setOnKeyListener( @Nullable DialogInterface.OnKeyListener onKeyListener) { throw new RuntimeException("Stub!"); } @NonNull public AlertDialog.Builder setItems( @ArrayRes int itemsId, @Nullable final DialogInterface.OnClickListener listener) { throw new RuntimeException("Stub!"); } @NonNull public AlertDialog.Builder setItems( @Nullable CharSequence[] items, @Nullable final DialogInterface.OnClickListener listener) { throw new RuntimeException("Stub!"); } @NonNull public AlertDialog.Builder setAdapter( @Nullable final ListAdapter adapter, @Nullable final DialogInterface.OnClickListener listener) { throw new RuntimeException("Stub!"); } @NonNull public AlertDialog.Builder setCursor( @Nullable final Cursor cursor, @Nullable final DialogInterface.OnClickListener listener, @NonNull String labelColumn) { throw new RuntimeException("Stub!"); } @NonNull public AlertDialog.Builder setMultiChoiceItems( @ArrayRes int itemsId, @Nullable boolean[] checkedItems, @Nullable final DialogInterface.OnMultiChoiceClickListener listener) { throw new RuntimeException("Stub!"); } @NonNull public AlertDialog.Builder setMultiChoiceItems( @Nullable CharSequence[] items, @Nullable boolean[] checkedItems, @Nullable final DialogInterface.OnMultiChoiceClickListener listener) { throw new RuntimeException("Stub!"); } @NonNull public AlertDialog.Builder setMultiChoiceItems( @Nullable Cursor cursor, @NonNull String isCheckedColumn, @NonNull String labelColumn, @Nullable final DialogInterface.OnMultiChoiceClickListener listener) { throw new RuntimeException("Stub!"); } @NonNull public AlertDialog.Builder setSingleChoiceItems( @ArrayRes int itemsId, int checkedItem, @Nullable final DialogInterface.OnClickListener listener) { throw new RuntimeException("Stub!"); } @NonNull public AlertDialog.Builder setSingleChoiceItems( @Nullable Cursor cursor, int checkedItem, @NonNull String labelColumn, @Nullable final DialogInterface.OnClickListener listener) { throw new RuntimeException("Stub!"); } @NonNull public AlertDialog.Builder setSingleChoiceItems( @Nullable CharSequence[] items, int checkedItem, @Nullable final DialogInterface.OnClickListener listener) { throw new RuntimeException("Stub!"); } @NonNull public AlertDialog.Builder setSingleChoiceItems( @Nullable ListAdapter adapter, int checkedItem, @Nullable final DialogInterface.OnClickListener listener) { throw new RuntimeException("Stub!"); } @NonNull public AlertDialog.Builder setOnItemSelectedListener( @Nullable final AdapterView.OnItemSelectedListener listener) { throw new RuntimeException("Stub!"); } @NonNull public AlertDialog.Builder setView(int layoutResId) { throw new RuntimeException("Stub!"); } @NonNull public AlertDialog.Builder setView(@Nullable View view) { throw new RuntimeException("Stub!"); } public AlertDialog show() { throw new RuntimeException("Stub!"); } } }
7,374
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
FileEditorProviderManager.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/fileeditor-api/src/main/java/com/tyron/fileeditor/api/FileEditorProviderManager.java
package com.tyron.fileeditor.api; import androidx.annotation.NonNull; import java.io.File; public interface FileEditorProviderManager { FileEditorProvider[] getProviders(@NonNull File file); FileEditorProvider getProvider(@NonNull String typeId); void registerProvider(FileEditorProvider provider); }
312
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
FileEditorProvider.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/fileeditor-api/src/main/java/com/tyron/fileeditor/api/FileEditorProvider.java
package com.tyron.fileeditor.api; import androidx.annotation.NonNull; import java.io.File; public interface FileEditorProvider { /** * @param file file to be tested for acceptance, this parameter is never null * @return whether the provider can create a valid editor instance for the specified file. */ boolean accept(@NonNull File file); /** * Creates the editor for the specified file. This method is only called if the provider has * accepted this file in {@link #accept(File)} * * @return the created editor for this file, never null. */ @NonNull FileEditor createEditor(@NonNull File file); /** * @return a unique id representing this file editor among others */ @NonNull String getEditorTypeId(); }
756
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
FileEditorManager.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/fileeditor-api/src/main/java/com/tyron/fileeditor/api/FileEditorManager.java
package com.tyron.fileeditor.api; import android.content.Context; import androidx.annotation.NonNull; import java.io.File; import java.util.function.Consumer; public abstract class FileEditorManager { /** * Open an editor from a saved state * * @param state the saved state of the editor * @return the editor */ public FileEditor openFile(FileEditorSavedState state) { FileEditor[] fileEditors = getFileEditors(state.getFile()); for (FileEditor fileEditor : fileEditors) { if (state.getName().equals(fileEditor.getName())) { return fileEditor; } } // fallback to the first editor return fileEditors[0]; } /** * Convenience method to make the user select an editor in a list of file editors, typically shown * when there are more than one applicable editors to a file * * <p>this should be called on the main thread * * @param context the current context, must not be null * @param file the file to be opened * @param callback the callback after the user has selected an editor */ public abstract void openFile(@NonNull Context context, File file, Consumer<FileEditor> callback); /** * @param file file to open. Parameter cannot be null. File should be valid. * @return array of opened editors */ @NonNull public abstract FileEditor[] openFile( @NonNull Context context, @NonNull File file, boolean focus); public abstract FileEditor[] getFileEditors(@NonNull File file); public abstract void openFileEditor(@NonNull FileEditor fileEditor); /** * Closes all editors opened for the file. * * @param file file to be closed. Cannot be null. */ public abstract void closeFile(@NonNull File file); public abstract void openChooser( Context context, FileEditor[] fileEditors, Consumer<FileEditor> callback); }
1,854
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
FileEditorSavedState.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/fileeditor-api/src/main/java/com/tyron/fileeditor/api/FileEditorSavedState.java
package com.tyron.fileeditor.api; import androidx.annotation.Keep; import com.google.gson.annotations.SerializedName; import java.io.File; @Keep public class FileEditorSavedState { @SerializedName("name") private final String mName; @SerializedName("file") private final File mFile; public FileEditorSavedState(FileEditor editor) { this(editor.getName(), editor.getFile()); } public FileEditorSavedState(String mName, File mFile) { this.mName = mName; this.mFile = mFile; } public String getName() { return mName; } public File getFile() { return mFile; } }
610
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
FileEditor.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/fileeditor-api/src/main/java/com/tyron/fileeditor/api/FileEditor.java
package com.tyron.fileeditor.api; import android.view.View; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import java.io.File; /** Represents the Tab view and can contain different views based on it's function */ public interface FileEditor { /** * @return the fragment which represents the editor in UI */ Fragment getFragment(); /** * @return the view to be focused when this editor has been selected. */ View getPreferredFocusedView(); /** * @return The name of this editor to be distinguished from other editors. Note that this is not * the name displayed from UI */ @NonNull String getName(); /** * @return whether this editor has been modified in comparison with its file */ boolean isModified(); /** * @return whether this editor is valid or not. An editor may become invalid if the file it * represents have been deleted. */ boolean isValid(); /** * @return the file this editor is editing */ File getFile(); }
1,032
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
CardViewModule.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/cardview/src/main/java/com/tyron/layout/cardview/CardViewModule.java
package com.tyron.layout.cardview; import com.flipkart.android.proteus.ProteusBuilder; import com.tyron.layout.cardview.parser.CardViewParser; public class CardViewModule implements ProteusBuilder.Module { private CardViewModule() {} public static CardViewModule create() { return new CardViewModule(); } @Override public void registerWith(ProteusBuilder builder) { builder.register(new CardViewParser<>()); } }
437
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
CardViewParser.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/cardview/src/main/java/com/tyron/layout/cardview/parser/CardViewParser.java
package com.tyron.layout.cardview.parser; import android.content.res.ColorStateList; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.cardview.widget.CardView; import com.flipkart.android.proteus.ProteusContext; import com.flipkart.android.proteus.ProteusView; import com.flipkart.android.proteus.ViewTypeParser; import com.flipkart.android.proteus.processor.BooleanAttributeProcessor; import com.flipkart.android.proteus.processor.ColorResourceProcessor; import com.flipkart.android.proteus.processor.DimensionAttributeProcessor; import com.flipkart.android.proteus.value.Layout; import com.flipkart.android.proteus.value.ObjectValue; import com.tyron.layout.cardview.widget.ProteusCardView; public class CardViewParser<T extends View> extends ViewTypeParser<T> { @NonNull @Override public String getType() { return "androidx.cardview.widget.CardView"; } @Nullable @Override public String getParentType() { return "android.widget.FrameLayout"; } @NonNull @Override public ProteusView createView( @NonNull ProteusContext context, @NonNull Layout layout, @NonNull ObjectValue data, @Nullable ViewGroup parent, int dataIndex) { return new ProteusCardView(context); } @Override protected void addAttributeProcessors() { addAttributeProcessor( "app:cardBackgroundColor", new ColorResourceProcessor<T>() { @Override public void setColor(T view, int color) { if (view instanceof CardView) { ((CardView) view).setCardBackgroundColor(color); } } @Override public void setColor(T view, ColorStateList colors) { if (view instanceof CardView) { ((CardView) view).setCardBackgroundColor(colors); } } }); addAttributeProcessor( "app:cardCornerRadius", new DimensionAttributeProcessor<T>() { @Override public void setDimension(T view, float dimension) { if (view instanceof CardView) { ((CardView) view).setRadius(dimension); } } }); addAttributeProcessor( "app:cardElevation", new DimensionAttributeProcessor<T>() { @Override public void setDimension(T view, float dimension) { if (view instanceof CardView) { ((CardView) view).setCardElevation(dimension); } } }); addAttributeProcessor( "app:cardMaxElevation", new DimensionAttributeProcessor<T>() { @Override public void setDimension(T view, float dimension) { if (view instanceof CardView) { ((CardView) view).setMaxCardElevation(dimension); } } }); addAttributeProcessor( "app:cardPreventCornerOverlap", new BooleanAttributeProcessor<T>() { @Override public void setBoolean(T view, boolean value) { if (view instanceof CardView) { ((CardView) view).setPreventCornerOverlap(value); } } }); addAttributeProcessor( "app:cardUseCompatPadding", new BooleanAttributeProcessor<T>() { @Override public void setBoolean(T view, boolean value) { if (view instanceof CardView) { ((CardView) view).setUseCompatPadding(value); } } }); addAttributeProcessor( "app:contentPadding", new DimensionAttributeProcessor<T>() { @Override public void setDimension(T view, float d) { if (view instanceof CardView) { ((CardView) view).setContentPadding((int) d, (int) d, (int) d, (int) d); } } }); addAttributeProcessor( "app:contentPaddingBottom", new DimensionAttributeProcessor<T>() { @Override public void setDimension(T v, float dimension) { if (v instanceof CardView) { CardView view = (CardView) v; int t = view.getContentPaddingTop(); int r = view.getContentPaddingRight(); int l = view.getContentPaddingLeft(); view.setContentPadding(l, t, r, (int) dimension); } } }); addAttributeProcessor( "app:contentPaddingTop", new DimensionAttributeProcessor<T>() { @Override public void setDimension(T v, float dimension) { if (v instanceof CardView) { CardView view = (CardView) v; int r = view.getContentPaddingRight(); int l = view.getContentPaddingLeft(); int b = view.getContentPaddingBottom(); view.setContentPadding(l, (int) dimension, r, b); } } }); addAttributeProcessor( "app:contentPaddingLeft", new DimensionAttributeProcessor<T>() { @Override public void setDimension(T v, float dimension) { if (v instanceof CardView) { CardView view = (CardView) v; int r = view.getContentPaddingRight(); int b = view.getContentPaddingBottom(); int t = view.getContentPaddingTop(); view.setContentPadding((int) dimension, t, r, b); } } }); addAttributeProcessor( "app:contentPaddingRight", new DimensionAttributeProcessor<T>() { @Override public void setDimension(T v, float dimension) { if (v instanceof CardView) { CardView view = (CardView) v; int b = view.getContentPaddingBottom(); int t = view.getContentPaddingTop(); int l = view.getContentPaddingLeft(); view.setContentPadding(l, t, (int) dimension, b); } } }); } }
6,075
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z