/** * {@inheritDoc} * <p> * Note that archive entries with absolute paths are ignored by this * method and are never returned. */ @Override @FsAssertion(atomic=YES, consistent=YES, isolated=YES, durable=NOT_APPLICABLE) public @Nullable TFile[] listFiles( final @CheckForNull FilenameFilter filter) { if (null != innerArchive) { final FsNode entry; try { entry = innerArchive.getController() .node(getAccessPreferences(), getNodeName()); } catch (IOException ex) { return null; } return filter(members(entry), filter); } else { return filter(list(file.list(filter)), (FilenameFilter) null); } }
@CheckForNull public ReportToken getReportAsToken(int reportId) { try { PreparedStatement statement = connection.prepareStatement(SELECT_REPORT); statement.setInt(1, reportId); ResultSet set = statement.executeQuery(); if (set.next()) { return new ReportToken(reportId, set.getString("reporterid"), set.getString("reportedid"), set.getString("channelid"), set.getString("reason"), set.getString("handleid"), set.getString("handlereason"), set.getInt("status")); } else { return null; } } catch (SQLException e) { e.printStackTrace(); return null; } }
/** * Constructs a new {@code TFile} instance which uses the given archive * detector to scan its path name for prospective archive files. * * @param file the file object to decorate. * If this is an instance of this class, most of its fields get * copied. * @param detector the archive detector to use for scanning the path name * for prospective archive files. * If this parameter is {@code null} and {@code file} is * an instance of this class, then its archive detector gets used. * If this parameter is {@code null} and {@code file} is <em>not</em> * an instance of this class, then the current archive detector gets * resolved by calling {@code TConfig.current().getArchiveDetector()}. */ @ExpertFeature(INJECTING_A_DIFFERENT_DETECTOR_FOR_THE_SAME_PATH_MAY_CORRUPT_DATA) @SuppressWarnings("AccessingNonPublicFieldOfAnotherObject") public TFile(final File file, final @CheckForNull TArchiveDetector detector) { super(file.getPath()); if (file instanceof TFile) { final TFile that = (TFile) file; this.file = that.file; this.detector = that.detector; if (null == detector || this.detector.equals(detector)) { this.enclArchive = that.getEnclArchive(); this.nodeName = that.nodeName; this.innerArchive = that.isArchive() ? this : that.innerArchive; this.controller = that.controller; } else { this.detector = detector; scan(null); } } else { this.file = file; this.detector = null != detector ? detector : TConfig.current().getArchiveDetector(); scan(null); } assert invariants(); }
/** * Returns a new {@link JarDriverEntry}, requesting that the data gets * {@code DEFLATED} if no template is provided. * This feature strengthens the security level of the authentication * process and inhibits the use of an unencrypted temporary I/O entry * (usually a temporary file) in case the sink is not copied from a file * system entry as its input. * <p> * Furthermore, the method {@link JarDriverEntry#clearEncryption()} is * called in order to prevent adding a redundant encryption layer for the * individual ZIP entry because this would confuse users, increase the size * of the resulting archive file and unecessarily heat the CPU. */ @Override public JarDriverEntry newEntry( final BitField<FsAccessOption> options, final String name, final Type type, final @CheckForNull Entry template) { final JarDriverEntry entry = super.newEntry(options.set(COMPRESS), name, type, template); // Fix for http://java.net/jira/browse/TRUEZIP-176 : // Entry level encryption is enabled if make.getKeyManager(ENCRYPTED) is true // OR template is an instance of ZipEntry // AND ((ZipEntry) template).isEncrypted() is true. // Now switch off entry level encryption because encryption is already // provided by the RAES wrapper file format. entry.clearEncryption(); return entry; }
private static <P extends RaesParameters> P parameters( final Class<P> type, @CheckForNull RaesParameters param) throws RaesParametersException { while (null != param) { // Order is important here to support multiple interface implementations! if (type.isInstance(param)) { return type.cast(param); } else if (param instanceof RaesParametersProvider) { param = ((RaesParametersProvider) param).get(type); } else { break; } } throw new RaesParametersException("No suitable RAES parameters available!"); }
private void retrieveMergeRequests(@CheckForNull SCMSourceCriteria criteria, @Nonnull SCMHeadObserver observer, @Nonnull TaskListener listener) throws IOException, InterruptedException { branchesWithMergeRequestsCache = new HashMap<>(); if (source.getProject().isMergeRequestsEnabled() && source.getSourceSettings().shouldMonitorMergeRequests()) { log(listener, Messages.GitLabSCMSource_retrievingMergeRequests()); GitLabMergeRequestFilter filter = source.getSourceSettings().createMergeRequestFilter(listener); for (GitLabMergeRequest mr : filter.filter(api().getMergeRequests(source.getProjectId()))) { checkInterrupt(); if (!source.isExcluded(mr.getTargetBranch())) { observe(criteria, observer, mr, listener); } } } }
@Nonnull private List<Action> retrieve(@Nonnull SCMRevisionImpl revision, @CheckForNull SCMHeadEvent event, @Nonnull TaskListener listener) throws IOException, InterruptedException { List<Action> actions = new ArrayList<>(); String hash = revision.getHash(); Action linkAction = GitLabLinkAction.toCommit(source.getProject(), hash); actions.add(linkAction); SCMHead head = revision.getHead(); if (head instanceof GitLabSCMMergeRequestHead) { actions.add(createHeadMetadataAction(head.getName(), ((GitLabSCMMergeRequestHead) head).getSource(), hash, linkAction.getUrlName())); } else if (head instanceof GitLabSCMHead) { actions.add(createHeadMetadataAction(head.getName(), (GitLabSCMHead) head, hash, linkAction.getUrlName())); } if (event instanceof GitLabSCMEvent) { actions.add(new GitLabSCMCauseAction(((GitLabSCMEvent) event).getCause())); } return actions; }
/** * Checks the parameter range. * * @param i The integer to check to be in the range of an unsigned short * integer ({@value SIZE} bits). * @param subject The subject of the exception message * - may be {@code null}. * This should not end with a punctuation character. * @param error First sentence of the exception message * - may be {@code null}. * This should not end with a punctuation character. * @return {@code true} * @throws IllegalArgumentException If {@code i} is less than * {@link #MIN_VALUE} or greater than {@link #MAX_VALUE}. */ public static boolean check( final int i, final @CheckForNull String subject, final @CheckForNull String error) { if (MIN_VALUE <= i && i <= MAX_VALUE) return true; final StringBuilder message = new StringBuilder(); if (null != subject) message.append(subject).append(": "); if (null != error) message.append(error).append(": "); throw new IllegalArgumentException(message .append(i) .append(" is not within ") .append(MIN_VALUE) .append(" and ") .append(MAX_VALUE) .append(" inclusive.") .toString()); }
@Nonnull public static Map<String, String> getPollingEnvVars(@Nonnull Job<?, ?> job, @CheckForNull Node node) throws EnvInjectException { final Run<?, ?> lastBuild = job.getLastBuild(); if (lastBuild != null) { if (EnvInjectPluginHelper.isEnvInjectPluginInstalled()) { return getEnVars(lastBuild); } } if (node == null) { return getFallBackMasterNode(job); } if (node.getRootPath() == null) { return getFallBackMasterNode(job); } return getDefaultEnvVarsJob(job, node); }
/** * Returns an output socket for the given file. * * @param file the file to write. * @param options the options for accessing the file. * @param template a nullable template from which file attributes shall * get copied. * @return An output socket for the given file. */ static OutputSocket<?> output( final BitField<FsAccessOption> options, final File file, final @CheckForNull Entry template) { if (file instanceof TFile) { final TFile tfile = (TFile) file; final TFile archive = tfile.getInnerArchive(); if (null != archive) return archive .getController() .output( options, tfile.getNodeName(), template); } final FsNodePath path = new FsNodePath(file); return TConfig .current() .getManager() .controller(detector(file), path.getMountPoint()) .output( options.clear(CREATE_PARENTS), path.getNodeName(), template); }
/** * Searches for {@code ZipParameters} of the given type starting from * the given parameters. * * @param <P> the type of the ZIP parameters to search for. * @param type the type of the ZIP parameters to search for. * @param param the parameters for starting the search. * @return The parameters of the given type. * @throws ZipParametersException if {@code param} is {@code null} or * no suitable parameters can get found. */ static <P extends ZipParameters> P parameters( final Class<P> type, @CheckForNull ZipParameters param) throws ZipParametersException { while (null != param) { // Order is important here to support multiple interface implementations! if (type.isInstance(param)) { return type.cast(param); } else if (param instanceof ZipParametersProvider) { param = ((ZipParametersProvider) param).get(type); } else { break; } } throw new ZipParametersException("No suitable ZIP parameters available!"); }
/** * Convert a text representation to an InetAddress * It supports IPV4 and IPV6 formats * * @param name the address * * @return the text converted to an InetAddress */ public static InetAddress getAddressForBan(@CheckForNull String hostname) throws InvalidInetAddressException { if (hostname == null) { throw new InvalidInetAddressException("null address", null); } String name = hostname.trim(); if (name.length() == 0) { throw new InvalidInetAddressException("empty address", null); } //TODO(mmarquez): should we validate address format ?? try { InetAddress address = InetAddress.getByName(name); if (address.isLoopbackAddress() || address.isAnyLocalAddress()) { throw new InvalidInetAddressException("local address: '" + name + "'", null); } return address; } catch (UnknownHostException ex) { throw new InvalidInetAddressException("unknown host: '" + name + "'", ex); } }
@SuppressWarnings("unchecked") static @CheckForNull Map<String, Object> delegateArguments(@CheckForNull Object delegate) { if (delegate instanceof UninstantiatedDescribable) { // TODO JENKINS-45101 getStepArgumentsAsString does not resolve its arguments // thus delegate.model == null and we cannot inspect DescribableModel.soleRequiredParameter // thus for, e.g., `junit testResults: '*.xml', keepLongStdio: true` we will get null return new HashMap<>(((UninstantiatedDescribable) delegate).getArguments()); } else if (delegate instanceof Map) { Map<String, Object> r = new HashMap<>(); r.putAll((Map) delegate); r.remove(DescribableModel.CLAZZ); return r; } else { return null; } }
@CheckForNull @SuppressWarnings(value = "deprecation") static String getTriggerName(Cause cause) { if (SCMTrigger.SCMTriggerCause.class.isInstance(cause)) { return "SCMTRIGGER"; } else if (TimerTrigger.TimerTriggerCause.class.isInstance(cause)) { return "TIMERTRIGGER"; } else if (Cause.UserIdCause.class.isInstance(cause)) { return "MANUALTRIGGER"; } else if (Cause.UserCause.class.isInstance(cause)) { return "MANUALTRIGGER"; } else if (Cause.UpstreamCause.class.isInstance(cause)) { return "UPSTREAMTRIGGER"; } else if (cause != null) { return cause.getClass().getSimpleName().toUpperCase(Locale.ENGLISH); } return null; }
@Override public FsController newController( final FsManager context, final FsModel model, final @CheckForNull FsController parent) { return new MockController(model, parent, null); }
@CheckForNull private static Node getMasterNode() { final Jenkins jenkins = Jenkins.getInstance(); if (jenkins == null) { return null; } Computer computer = jenkins.toComputer(); if (computer == null) { return null; //Master can have no executors } return computer.getNode(); }
/** * Constructs a new mock controller. * * @param model The file system model. * @param parent The parent file system controller. * @param config The mocking configuration. */ public MockController( final FsModel model, final @CheckForNull FsController parent, final @CheckForNull FsTestConfig config) { super(model); assert null == model.getParent() ? null == parent : model.getParent().equals(parent.getModel()); this.parent = parent; this.config = null != config ? config : FsTestConfig.get(); }
@CheckForNull protected RuntimeException getFirstError() { if (firstError != null) { // this call throws a RuntimeException return Throwables.propagate(firstError); } else { return null; } }
@CheckForNull public static AwsCredentials getCredentials(@Nullable String credentialsId) { if (StringUtils.isBlank(credentialsId)) { return null; } return CredentialsMatchers.firstOrNull( CredentialsProvider.lookupCredentials(AwsCredentials.class, (Item) null, ACL.SYSTEM, null, null), CredentialsMatchers.withId(credentialsId) ); }
@Override public MockArchiveDriverEntry newEntry( BitField<FsAccessOption> options, String name, Type type, @CheckForNull Entry template) { return new MockArchiveDriverEntry(normalize(name, type), type, template); }
boolean updateProperties( final E local, final @CheckForNull Entry peer) { boolean rdc = false; if (UNKNOWN == local.getTime()) local.setTime(System.currentTimeMillis()); if (null != peer) { if (UNKNOWN == local.getSize()) local.setSize(peer.getSize(DATA)); if (peer instanceof AbstractZipDriverEntry) { // Set up entry attributes for Raw Data Copying (RDC). final AbstractZipDriverEntry zpeer = (AbstractZipDriverEntry) peer; rdc = driver.rdc(this, local, zpeer); if (rdc) { local.setPlatform(zpeer.getPlatform()); local.setEncrypted(zpeer.isEncrypted()); local.setMethod(zpeer.getMethod()); local.setCrc(zpeer.getCrc()); local.setSize(zpeer.getSize()); local.setCompressedSize(zpeer.getCompressedSize()); local.setExtra(zpeer.getExtra()); } } } if (0 == local.getSize()) { rdc = false; local.clearEncryption(); local.setMethod(STORED); local.setCrc(0); local.setCompressedSize(0); } return rdc; }
@CreatesObligation public ThrowingInputStream( final @WillCloseWhenClosed InputStream in, final @CheckForNull FsThrowManager control) { super(in); this.control = null != control ? control : FsTestConfig.get().getThrowControl(); }
/** * Parse wire byte[] message into RLP elements * * @param msgData - raw RLP data * @return rlpList * - outcome of recursive RLP structure */ @Nonnull public static ArrayList<RLPElement> decode2(@CheckForNull byte[] msgData) { if (msgData == null) { return new ArrayList<>(); } return decode(ByteBuffer.wrap(msgData)); }
@Nonnull public static GitLabLinkAction create(@CheckForNull String displayName, @Nonnull String iconFileName, @Nonnull String url) { if (displayName == null) { return create("", iconFileName, url); } return new GitLabLinkAction(displayName, iconFileName, url); }
@CheckForNull private static MethodBehavior getMethodBehavior(BehaviorCache bc, @Nullable Tree syntaxTree) { if (syntaxTree == null || !syntaxTree.is(Tree.Kind.METHOD_INVOCATION)) { return null; } Symbol symbol = ((MethodInvocationTree) syntaxTree).symbol(); if (!symbol.isMethodSymbol()) { return null; } return bc.get((Symbol.MethodSymbol) symbol); }
/** * Akin to {@link JenkinsRule#createSlave(String, String, EnvVars)} but allows {@link Computer#getEnvironment} to be controlled rather than directly modifying launchers. * @param env variables to override in {@link Computer#getEnvironment}; null values will get unset even if defined in the test environment * @see <a href="https://github.com/jenkinsci/jenkins/pull/1553/files#r23784822">explanation in core PR 1553</a> */ public static Slave createSpecialEnvSlave(JenkinsRule rule, String nodeName, @CheckForNull String labels, Map<String,String> env) throws Exception { @SuppressWarnings("deprecation") // keep consistency with original signature rather than force the caller to pass in a TemporaryFolder rule File remoteFS = rule.createTmpDir(); SpecialEnvSlave slave = new SpecialEnvSlave(remoteFS, rule.createComputerLauncher(/* yes null */null), nodeName, labels != null ? labels : "", env); rule.jenkins.addNode(slave); return slave; }
@Nonnull private static GitLabLinkAction create(@CheckForNull String displayName, @Nonnull String iconName, @Nonnull GitlabProject project, String path) { return new GitLabLinkAction( displayName == null ? "" : displayName, iconName, project.getWebUrl() + "/" + path); }
/** * Returns {@code true} iff the given object is a mount point and its URI * {@link URI#equals(Object) equals} the URI of this mount point. * Note that this ignores the scheme and path. */ @Override public boolean equals(@CheckForNull Object that) { return this == that || that instanceof FsMountPoint && this.uri.equals(((FsMountPoint) that).uri); }
protected FsAbstractModel( final FsMountPoint mountPoint, final @CheckForNull FsModel parent) { if (!Objects.equals(mountPoint.getParent(), (null == parent ? null : parent.getMountPoint()))) throw new IllegalArgumentException("Parent/Member mismatch!"); this.mountPoint = mountPoint; this.parent = parent; }
@CreatesObligation @SuppressWarnings("LeakingThisInConstructor") BufferedEntryOutputStream( final OutputSocket<? extends E> output, final @CheckForNull InputSocket<? extends Entry> input) throws IOException { // HC SVNT DRACONES! final E local = (this.output = output).target(); final Entry _peer = null != input ? input.target() : null; final IoBuffer buffer = this.buffer = pool.allocate(); final Entry peer = null != _peer ? _peer : buffer; final class InputProxy extends DecoratingInputSocket<Entry> { InputProxy() { super(buffer.input()); } @Override public Entry target() { return peer; } } // InputProxy try { this.input = new InputProxy(); this.out = buffer.output().stream(null); } catch (final Throwable ex) { try { buffer.release(); } catch (final Throwable ex2) { ex.addSuppressed(ex2); } throw ex; } buffers.put(local.getName(), this); }
@Override public final OutputService<ZipDriverEntry> newOutput( FsModel model, BitField<FsAccessOption> options, FsController controller, FsNodeName name, @CheckForNull @WillNotClose InputService<ZipDriverEntry> input) throws IOException { throw new FsReadOnlyFileSystemException(model.getMountPoint()); }
@Override protected OutputService<JarDriverEntry> newOutput( final FsModel model, final FsOutputSocketSink sink, final @CheckForNull @WillNotClose InputService<JarDriverEntry> input) throws IOException { final ZipInputService<JarDriverEntry> zis = (ZipInputService<JarDriverEntry>) input; return new MultiplexingOutputService<>(getPool(), new ZipOutputService<>(model, new RaesSocketSink(model, sink), zis, this)); }
@Override public File getParentDirectory(File file) { final TFile tfile = wrap(file); if (tfile.isEntry()) return createFileObject(tfile.getParentFile()); final @CheckForNull File dir = fsv.getParentDirectory(unwrap(file)); return null == dir ? dir : createFileObject(dir); }
@CheckForNull public static AwsCredentials getCredentials(@NotNull String accessKey, @NotNull Secret secretKey) { if (StringUtils.isBlank(accessKey) || StringUtils.isBlank(secretKey.getPlainText())) { return null; } return CredentialsMatchers.firstOrNull( CredentialsProvider.lookupCredentials(AwsCredentials.class, (Item) null, ACL.SYSTEM, null, null), CredentialsMatchers.allOf( CredentialsMatchers.withProperty("accessKey", accessKey), CredentialsMatchers.withProperty("secretKey", secretKey) ) ); }
@Override public FsController newController( final FsManager manager, final FsModel model, final @CheckForNull FsController parent) { assert null == parent; assert null == model.getParent(); return new HttpController(this, model); }
@Nonnull List<Action> retrieve(@Nonnull SCMRevision revision, @CheckForNull SCMHeadEvent event, @Nonnull TaskListener listener) throws IOException, InterruptedException { if (revision instanceof SCMRevisionImpl) { return retrieve((SCMRevisionImpl) revision, event, listener); } return emptyList(); }
FileOutputSocket( final BitField<FsAccessOption> options, final FileNode node, final @CheckForNull Entry template) { assert null != node; this.node = node; if (options.get(EXCLUSIVE) && options.get(APPEND)) throw new IllegalArgumentException(); this.options = options; this.template = template; }
@Override protected OutputService<JarDriverEntry> newOutput( final FsModel model, final FsOutputSocketSink sink, final @CheckForNull @WillNotClose InputService<JarDriverEntry> input) throws IOException { final ZipInputService<JarDriverEntry> zis = (ZipInputService<JarDriverEntry>) input; final ZipOutputService<JarDriverEntry> zos = new ZipOutputService<>(model, sink, zis, this); final IoBufferPool pool = getPool(); return null != zis && sink.getOptions().get(GROW) ? new MultiplexingOutputService<>(pool, zos) : new OdfOutputService(pool, zos); }
/** * getBlockFromStoreOrBlockchain retrieves a block from the store if it's available, * or else from the blockchain. It should be part of BlockChainImpl but is here because * BlockChain is coupled with the old org.ethereum.db.BlockStore. */ @CheckForNull public Block getBlockFromStoreOrBlockchain(@Nonnull final byte[] hash) { final Block block = store.getBlockByHash(hash); if (block != null) { return block; } return blockchain.getBlockByHash(hash); }
private @CheckForNull IOException findKeyException(Throwable ex) { final Class<? extends IOException> clazz = getKeyExceptionType(); do { if (clazz.isInstance(ex)) return clazz.cast(ex); } while (null != (ex = ex.getCause())); return null; }