try {
                        priority = Integer.valueOf(priorityString);
                    } catch (NumberFormatException e) {
                        String message = "Failed to parse issue category due to malformed priority string: \"" + priorityString + "\"" + " (origin: \"" + origin + "\", id: \"" + categoryID + "\")";
                        throw new WindupException(message);
                    }

package org.jboss.windup.reporting.category;

import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.jboss.windup.config.AbstractRuleProvider;
import org.jboss.windup.config.GraphRewrite;
import org.jboss.windup.config.loader.RuleLoaderContext;
import org.jboss.windup.config.metadata.RuleMetadata;
import org.jboss.windup.config.operation.GraphOperation;
import org.jboss.windup.config.phase.InitializationPhase;
import org.jboss.windup.util.exception.WindupException;
import org.ocpsoft.rewrite.config.Configuration;
import org.ocpsoft.rewrite.config.ConfigurationBuilder;
import org.ocpsoft.rewrite.context.EvaluationContext;

/**
 * Loads issue categories into the registry. Also, this is responsible for attaching them to the graph.
 *
 * @author Jesse Sightler
 */
@RuleMetadata(phase = InitializationPhase.class)
public class LoadIssueCategoriesRuleProvider extends AbstractRuleProvider {

    public static final String WINDUP_CATEGORIES_XML_SUFFIX = ".windup.categories.xml";

    @Override
    public Configuration getConfiguration(RuleLoaderContext ruleLoaderContext) {
        loadIssueCategories(ruleLoaderContext);
        return ConfigurationBuilder.begin().addRule().perform(new GraphOperation() {

            @Override
            public void perform(GraphRewrite event, EvaluationContext context) {
                IssueCategoryRegistry.instance(event.getRewriteContext()).attachToGraph(event.getGraphContext());
            }
        }).withId(LoadIssueCategoriesRuleProvider.class.getSimpleName() + "_attachToGraph");
    }

    private void loadIssueCategories(RuleLoaderContext ruleLoaderContext) {
        if (ruleLoaderContext.getRulePaths() == null)
            return;
        final List<Path> filePaths = new ArrayList<>();
        ruleLoaderContext.getRulePaths().forEach((path) -> {
            try {
                if (!Files.exists(path) || !Files.isReadable(path))
                    return;
                Files.walkFileTree(path, new SimpleFileVisitor<Path>() {

                    @Override
                    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                        if (Files.isReadable(file) && Files.isRegularFile(file) && file.getFileName().toString().toLowerCase().endsWith(WINDUP_CATEGORIES_XML_SUFFIX))
                            filePaths.add(file);
                        return FileVisitResult.CONTINUE;
                    }
                });
            } catch (IOException e) {
                throw new WindupException("I/O Error during search for issue category files, due to: " + e.getMessage(), e);
            }
        });
        filePaths.forEach((path) -> loadIssueCategory(ruleLoaderContext, path));
    }

    @SuppressWarnings("unchecked")
    private void loadIssueCategory(RuleLoaderContext ruleLoaderContext, Path path) {
        // @formatter:off
        /*
         * Sample xml format:
         *
         * <categories>
         *     <category id=”mandatory-for-ose3” priority=”100”>
         *         <name>Mandatory for OpenShift 3</name>
         *         <description>Items within this category must be addressed for a migration to an OpenShift 3 environment.</description>
         *     </category>
         * </categories>
         */
        // @formatter:on
        try {
            String origin = path.toAbsolutePath().normalize().toString();
            Document doc = new SAXReader().read(path.toFile());
            for (Element element : (List<Element>) doc.getRootElement().elements("category")) {
                String categoryID = element.attributeValue("id");
                String priorityString = element.attributeValue("priority");
                int priority = 0;
                if (StringUtils.isNotEmpty(priorityString)) {

                }
                String name = element.elementText("name");
                String description = element.elementText("description");
                IssueCategory issueCategory = new IssueCategory(categoryID, origin, name, description, priority);
                IssueCategoryRegistry.instance(ruleLoaderContext.getContext()).addCategory(issueCategory);
            }
        } catch (DocumentException e) {
            throw new WindupException("Failed to load due to: " + e.getMessage(), e);
        }
    }
}


public List<Server> getServers() {
        return servers;
    }

package com.consol.citrus.actions;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
import com.consol.citrus.AbstractTestActionBuilder;
import com.consol.citrus.context.TestContext;
import com.consol.citrus.server.Server;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Action stopping {@link Server} instances.
 *
 * @author Christoph Deppisch
 * @since 2006
 */
public class StopServerAction extends AbstractTestAction {

    /**
     * List of servers to stop
     */
    private final List<Server> servers;

    /**
     * Logger
     */
    private static Logger log = LoggerFactory.getLogger(StopServerAction.class);

    public StopServerAction(Builder builder) {
        super("stop-server", builder);
        this.servers = builder.servers;
    }

    @Override
    public void doExecute(TestContext context) {
        for (Server server : servers) {
            server.stop();
            log.info("Stopped server: " + server.getName());
        }
    }

    /**
     * Gets the list of servers to stop.
     * @return the list of servers to stop.
     */

    public static final class Builder extends AbstractTestActionBuilder<StopServerAction, Builder> {

        private List<Server> servers = new ArrayList<>();

        /**
         * Fluent API action building entry method used in Java DSL.
         * @param servers
         * @return
         */
        public static Builder stop(Server... servers) {
            Builder builder = new Builder();
            Stream.of(servers).forEach(builder::server);
            return builder;
        }

        /**
         * Fluent API action building entry method used in Java DSL.
         * @param server
         * @return
         */
        public static Builder stop(Server server) {
            Builder builder = new Builder();
            builder.server(server);
            return builder;
        }

        public Builder server(Server... server) {
            return server(Arrays.asList(server));
        }

        public Builder server(List<Server> servers) {
            this.servers.addAll(servers);
            return this;
        }

        @Override
        public StopServerAction build() {
            return new StopServerAction(this);
        }
    }
}


try {
            final IContainer folder = p.getParent();
            final List<WrappedFile> sub = new ArrayList<>();
            for (final IResource r : folder.members()) {
                if (r instanceof IFile && isSupport(p, (IFile) r)) {
                    sub.add((WrappedFile) getManager().findWrappedInstanceOf(r));
                }
            }
            return sub.toArray();
        } catch (final CoreException e) {
            e.printStackTrace();
        }

package ummisco.gama.ui.navigator.contents;

import static ummisco.gama.ui.metadata.FileMetaDataProvider.SHAPEFILE_CT_ID;
import static ummisco.gama.ui.metadata.FileMetaDataProvider.SHAPEFILE_SUPPORT_CT_ID;
import static ummisco.gama.ui.metadata.FileMetaDataProvider.getContentTypeId;
import static ummisco.gama.ui.metadata.FileMetaDataProvider.isSupport;
import static ummisco.gama.ui.metadata.FileMetaDataProvider.shapeFileSupportedBy;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Image;
import msi.gama.runtime.GAMA;
import msi.gama.util.file.IGamaFileMetaData;
import msi.gaml.compilation.kernel.GamaBundleLoader;
import ummisco.gama.ui.navigator.NavigatorContentProvider;
import ummisco.gama.ui.resources.GamaFonts;
import ummisco.gama.ui.resources.GamaIcons;
import ummisco.gama.ui.utils.PreferencesHelper;

public class WrappedFile extends WrappedResource<WrappedResource<?, ?>, IFile> {

    WrappedFile fileParent;

    boolean isShapeFile;

    boolean isShapeFileSupport;

    Image image;

    public WrappedFile(final WrappedContainer<?> root, final IFile wrapped) {
        super(root, wrapped);
        computeFileType();
        computeFileParent();
    }

    protected void computeFileImage() {
        final IFile f = getResource();
        if (GamaBundleLoader.HANDLED_FILE_EXTENSIONS.contains(f.getFileExtension())) {
            if (isShapeFileSupport) {
                image = GamaIcons.create("navigator/file.shapesupport2").image();
            } else {
                image = DEFAULT_LABEL_PROVIDER.getImage(f);
            }
        } else {
            image = GamaIcons.create("navigator/file.text2").image();
        }
    }

    protected void computeFileType() {
        final IFile f = getResource();
        isShapeFile = SHAPEFILE_CT_ID.equals(getContentTypeId(f));
        isShapeFileSupport = SHAPEFILE_SUPPORT_CT_ID.equals(getContentTypeId(f));
    }

    private void computeFileParent() {
        if (isShapeFileSupport) {
            final IResource shape = shapeFileSupportedBy(getResource());
            if (shape != null) {
                fileParent = (WrappedFile) getManager().findWrappedInstanceOf(shape);
            }
        }
    }

    @Override
    public WrappedResource<?, ?> getParent() {
        if (fileParent != null) {
            return fileParent;
        }
        return super.getParent();
    }

    @Override
    public boolean canBeDecorated() {
        return false;
    }

    @Override
    public boolean hasChildren() {
        return isShapeFile;
    }

    @Override
    public Object[] getNavigatorChildren() {
        if (NavigatorContentProvider.FILE_CHILDREN_ENABLED) {
            if (isGamaFile() || isShapeFile) {
                return getFileChildren();
            }
        }
        return EMPTY;
    }

    public Object[] getFileChildren() {
        final IFile p = getResource();

        return VirtualContent.EMPTY;
    }

    @Override
    public Font getFont() {
        return GamaFonts.getNavigFileFont();
    }

    @Override
    public Image getImage() {
        if (image == null) {
            computeFileImage();
        }
        return image;
    }

    @Override
    public Color getColor() {
        return null;
    }

    @Override
    public void getSuffix(final StringBuilder sb) {
        if (PreferencesHelper.NAVIGATOR_METADATA.getValue()) {
            final IGamaFileMetaData data = GAMA.getGui().getMetaDataProvider().getMetaData(getResource(), false, true);
            if (data != null) {
                data.appendSuffix(sb);
            }
        }
    }

    @Override
    public int countModels() {
        return 0;
    }

    public boolean isGamaFile() {
        return false;
    }

    @Override
    public VirtualContentType getType() {
        return VirtualContentType.FILE;
    }
}


try {
                    _server.getValueMap().flush(valueStream);
                } catch (IOException e) {
                    LOG.error("Failed to Flush Value Map to OutputStream:" + valuesPath);
                    _server.getFileSystem().delete(valuesPath, false);
                    throw e;
                } finally {
                    if (valueStream != null)
                        valueStream.close();
                }

package org.commoncrawl.service.pagerank.slave;

import java.io.IOException;
import java.io.OutputStream;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.fs.Path;
import org.commoncrawl.async.CallbackWithResult;
import org.commoncrawl.crawl.common.internal.CrawlEnvironment;
import org.commoncrawl.service.crawler.filters.SuperDomainFilter;
import org.commoncrawl.service.pagerank.Constants;
import org.commoncrawl.service.pagerank.IterationInfo;
import org.commoncrawl.util.CCStringUtils;

/**
 * @author rana
 */
public class CalculateRankTask extends PageRankTask<CalculateRankTask.CalculateRankTaskResult> {

    private static final Log LOG = LogFactory.getLog(CalculateRankTask.class);

    public CalculateRankTask(PageRankSlaveServer server, CallbackWithResult<CalculateRankTaskResult> completionCallback) {
        super(server, CalculateRankTask.CalculateRankTaskResult.class, completionCallback);
    }

    public static class CalculateRankTaskResult extends PageRankTask.PageRankTaskResult {

        public boolean done = false;

        public CalculateRankTaskResult() {
        }

        public CalculateRankTaskResult(boolean done) {
            this.done = done;
        }

        public boolean isDone() {
            return done;
        }
    }

    @Override
    protected void cancelTask() {
    }

    @Override
    public String getDescription() {
        return "Calculate Rank Task";
    }

    @Override
    protected CalculateRankTaskResult runTask() throws IOException {
        // construct checkpoint filename
        Path checkpointFilePath = PageRankUtils.getCheckpointFilePath(new Path(_server.getActiveJobConfig().getJobWorkPath()), IterationInfo.Phase.CALCULATE, _server.getActiveJobConfig().getIterationNumber(), _server.getNodeIndex());
        // check to see if checkpoint file exists ...
        if (_server.getFileSystem().exists(checkpointFilePath)) {
            LOG.info("Checkpoint File Found.Skipping Task.");
            return new CalculateRankTaskResult(true);
        } else {
            // load super domain filter
            LOG.info("Initializing SuperDomain Filter");
            SuperDomainFilter superDomainFilter = new SuperDomainFilter();
            superDomainFilter.loadFromPath(_server.getDirectoryServiceAddress(), CrawlEnvironment.ROOT_SUPER_DOMAIN_PATH, false);
            LOG.info("Starting Calculate Task - Iteration Number:" + _server.getActiveJobConfig().getIterationNumber());
            // take value map and distribute it
            if (_server.getValueMap() == null) {
                throw new IOException("Value Map NULL! Operation Failed");
            }
            // first zero value map values ...
            _server.getValueMap().zeroValues();
            try {
                PageRankUtils.calculateRank(_server.getConfig(), _server.getFileSystem(), _server.getValueMap(), _server.getActiveJobLocalPath(), _server.getActiveJobConfig().getJobWorkPath(), _server.getNodeIndex(), _server.getBaseConfig().getSlaveCount(), _server.getActiveJobConfig().getIterationNumber(), superDomainFilter, new PageRankUtils.ProgressAndCancelCheckCallback() {

                    @Override
                    public boolean updateProgress(float percentComplete) {
                        synchronized (CalculateRankTask.this) {
                            _percentComplete = percentComplete;
                        }
                        return false;
                    }
                });
                // and write out value map back to disk ...
                Path valuesPath = new Path(_server.getActiveJobConfig().getJobWorkPath(), PageRankUtils.makeUniqueFileName(Constants.PR_VALUE_FILE_PREFIX, _server.getActiveJobConfig().getIterationNumber(), _server.getNodeIndex()));
                LOG.info("Serializing Values to Path:" + valuesPath + " for Iteration:" + _server.getActiveJobConfig().getIterationNumber());
                _server.getFileSystem().delete(valuesPath, true);
                OutputStream valueStream = null;
                valueStream = _server.getFileSystem().create(valuesPath);

                // construct checkpoint filename
                LOG.info("Creating Checkpoint File:" + checkpointFilePath);
                return new CalculateRankTaskResult(_server.getFileSystem().createNewFile(checkpointFilePath));
            } catch (IOException e) {
                // calculate failed
                LOG.error("Calculate Rank Failed with Error:" + CCStringUtils.stringifyException(e));
                throw e;
            }
        }
    }
}


for (int i = 0; classDesc.interfaces != null && i < classDesc.interfaces.length; i++) {
            if ("javax/servlet/Filter".equals(classDesc.interfaces[i])) {
                return new HttpServiceCV(cv, className);
            }
        }

package scouter.agent.asm;

import org.objectweb.asm.*;
import org.objectweb.asm.commons.LocalVariablesSorter;
import scouter.agent.ClassDesc;
import scouter.agent.Configure;
import scouter.agent.Logger;
import scouter.agent.trace.TraceMain;
import java.util.HashSet;

public class HttpServiceASM implements IASM, Opcodes {

    public HashSet<String> servlets = new HashSet<String>();

    public HttpServiceASM() {
        servlets.add("javax/servlet/http/HttpServlet");
        servlets.add("weblogic/servlet/jsp/JspBase");
    }

    public ClassVisitor transform(ClassVisitor cv, String className, ClassDesc classDesc) {
        if (Configure.getInstance()._hook_serivce_enabled == false) {
            return cv;
        }
        if (servlets.contains(className)) {
            return new HttpServiceCV(cv, className);
        }

        return cv;
    }
}

class HttpServiceCV extends ClassVisitor implements Opcodes {

    private static String TARGET_SERVICE = "service";

    private static String TARGET_DOFILTER = "doFilter";

    private static String TARGET_SIGNATURE = "(Ljavax/servlet/ServletRequest;Ljavax/servlet/ServletResponse;";

    private String className;

    public HttpServiceCV(ClassVisitor cv, String className) {
        super(ASM9, cv);
        this.className = className;
    }

    @Override
    public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
        MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions);
        if (mv == null) {
            return mv;
        }
        if (desc.startsWith(TARGET_SIGNATURE)) {
            if (TARGET_SERVICE.equals(name)) {
                Logger.println("A103", "HTTP " + className);
                return new HttpServiceMV(access, desc, mv, true);
            } else if (TARGET_DOFILTER.equals(name)) {
                Logger.println("A104", "FILTER " + className);
                return new HttpServiceMV(access, desc, mv, false);
            }
        }
        return mv;
    }
}

class HttpServiceMV extends LocalVariablesSorter implements Opcodes {

    private static final String TRACEMAIN = TraceMain.class.getName().replace('.', '/');

    private final static String START_SERVICE = "startHttpService";

    private final static String START_FILTER = "startHttpFilter";

    private static final String START_SIGNATURE = "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;";

    private final static String END_METHOD = "endHttpService";

    private static final String END_SIGNATURE = "(Ljava/lang/Object;Ljava/lang/Throwable;)V";

    private final static String REJECT = "reject";

    private static final String REJECT_SIGNATURE = "(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;";

    private Label startFinally = new Label();

    private boolean httpservlet;

    public HttpServiceMV(int access, String desc, MethodVisitor mv, boolean httpservlet) {
        super(ASM9, access, desc, mv);
        this.httpservlet = httpservlet;
    }

    private int statIdx;

    @Override
    public void visitCode() {
        mv.visitVarInsn(Opcodes.ALOAD, 1);
        mv.visitVarInsn(Opcodes.ALOAD, 2);
        if (httpservlet) {
            mv.visitMethodInsn(Opcodes.INVOKESTATIC, TRACEMAIN, START_SERVICE, START_SIGNATURE, false);
        } else {
            mv.visitMethodInsn(Opcodes.INVOKESTATIC, TRACEMAIN, START_FILTER, START_SIGNATURE, false);
        }
        statIdx = newLocal(Type.getType(Object.class));
        mv.visitVarInsn(Opcodes.ASTORE, statIdx);
        mv.visitLabel(startFinally);
        mv.visitVarInsn(Opcodes.ALOAD, statIdx);
        mv.visitVarInsn(Opcodes.ALOAD, 1);
        mv.visitVarInsn(Opcodes.ALOAD, 2);
        mv.visitMethodInsn(Opcodes.INVOKESTATIC, TRACEMAIN, REJECT, REJECT_SIGNATURE, false);
        Label end = new Label();
        mv.visitJumpInsn(IFNULL, end);
        mv.visitInsn(Opcodes.RETURN);
        mv.visitLabel(end);
        mv.visitCode();
    }

    @Override
    public void visitInsn(int opcode) {
        if ((opcode >= IRETURN && opcode <= RETURN)) {
            mv.visitVarInsn(Opcodes.ALOAD, statIdx);
            mv.visitInsn(Opcodes.ACONST_NULL);
            mv.visitMethodInsn(Opcodes.INVOKESTATIC, TRACEMAIN, END_METHOD, END_SIGNATURE, false);
        }
        mv.visitInsn(opcode);
    }

    @Override
    public void visitMaxs(int maxStack, int maxLocals) {
        Label endFinally = new Label();
        mv.visitTryCatchBlock(startFinally, endFinally, endFinally, null);
        mv.visitLabel(endFinally);
        mv.visitInsn(DUP);
        int errIdx = newLocal(Type.getType(Throwable.class));
        mv.visitVarInsn(Opcodes.ASTORE, errIdx);
        mv.visitVarInsn(Opcodes.ALOAD, statIdx);
        mv.visitVarInsn(Opcodes.ALOAD, errIdx);
        mv.visitMethodInsn(Opcodes.INVOKESTATIC, TRACEMAIN, END_METHOD, END_SIGNATURE, false);
        mv.visitInsn(ATHROW);
        mv.visitMaxs(maxStack + 8, maxLocals + 2);
    }
}


while (!(node instanceof TSLAction)) {
                if (node instanceof TSLPredicate) {
                    node = ((TSLPredicate) node).getNext();
                } else {
                    // Not possible
                    continue nodeLoop;
                }
            }

package net.programmer.igoodie.twitchspawn.tslanguage.event;

import net.programmer.igoodie.twitchspawn.tslanguage.TSLFlowNode;
import net.programmer.igoodie.twitchspawn.tslanguage.action.TSLAction;
import net.programmer.igoodie.twitchspawn.tslanguage.predicate.TSLPredicate;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class TSLEvent implements TSLFlowNode {

    protected String name;

    protected List<TSLFlowNode> nextNodes;

    public TSLEvent(String name) {
        this.name = name;
        this.nextNodes = new LinkedList<>();
    }

    public List<TSLFlowNode> getNextNodes() {
        return nextNodes;
    }

    public String getName() {
        return name;
    }

    public List<TSLAction> getActions() {
        List<TSLAction> actions = new LinkedList<>();
        nodeLoop: for (TSLFlowNode nextNode : nextNodes) {
            TSLFlowNode node = nextNode;

            actions.add((TSLAction) node);
        }
        return actions;
    }

    @Override
    public TSLFlowNode chain(TSLFlowNode next) {
        nextNodes.add(next);
        return next;
    }

    @Override
    public boolean process(EventArguments args) {
        Iterator<TSLFlowNode> iterator = nextNodes.iterator();
        boolean success = false;
        while (iterator.hasNext()) {
            success = iterator.next().process(args);
            // Stop if handled once
            if (success)
                break;
        }
        return success;
    }

    @Override
    public boolean willPerform(EventArguments args) {
        if (!args.eventName.equalsIgnoreCase(this.name))
            return false;
        for (TSLFlowNode nextNode : nextNodes) {
            if (nextNode.willPerform(args))
                return true;
        }
        return false;
    }
}


@Nullable
    public Method resolveMethodByExceptionType(Class<? extends Throwable> exceptionType) {
        Method method = this.exceptionLookupCache.get(exceptionType);
        if (method == null) {
            method = getMappedMethod(exceptionType);
            this.exceptionLookupCache.put(exceptionType, method);
        }
        return method;
    }

package org.springframework.web.method.annotation;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.core.ExceptionDepthComparator;
import org.springframework.core.MethodIntrospector;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ConcurrentReferenceHashMap;
import org.springframework.util.ReflectionUtils.MethodFilter;
import org.springframework.web.bind.annotation.ExceptionHandler;

/**
 * Discovers {@linkplain ExceptionHandler @ExceptionHandler} methods in a given class,
 * including all of its superclasses, and helps to resolve a given {@link Exception}
 * to the exception types supported by a given {@link Method}.
 *
 * @author Rossen Stoyanchev
 * @author Juergen Hoeller
 * @since 3.1
 */
public class ExceptionHandlerMethodResolver {

    /**
     * A filter for selecting {@code @ExceptionHandler} methods.
     */
    public static final MethodFilter EXCEPTION_HANDLER_METHODS = method -> (AnnotationUtils.findAnnotation(method, ExceptionHandler.class) != null);

    private final Map<Class<? extends Throwable>, Method> mappedMethods = new HashMap<>(16);

    private final Map<Class<? extends Throwable>, Method> exceptionLookupCache = new ConcurrentReferenceHashMap<>(16);

    /**
     * A constructor that finds {@link ExceptionHandler} methods in the given type.
     * @param handlerType the type to introspect
     */
    public ExceptionHandlerMethodResolver(Class<?> handlerType) {
        for (Method method : MethodIntrospector.selectMethods(handlerType, EXCEPTION_HANDLER_METHODS)) {
            for (Class<? extends Throwable> exceptionType : detectExceptionMappings(method)) {
                addExceptionMapping(exceptionType, method);
            }
        }
    }

    /**
     * Extract exception mappings from the {@code @ExceptionHandler} annotation first,
     * and then as a fallback from the method signature itself.
     */
    @SuppressWarnings("unchecked")
    private List<Class<? extends Throwable>> detectExceptionMappings(Method method) {
        List<Class<? extends Throwable>> result = new ArrayList<>();
        detectAnnotationExceptionMappings(method, result);
        if (result.isEmpty()) {
            for (Class<?> paramType : method.getParameterTypes()) {
                if (Throwable.class.isAssignableFrom(paramType)) {
                    result.add((Class<? extends Throwable>) paramType);
                }
            }
        }
        if (result.isEmpty()) {
            throw new IllegalStateException("No exception types mapped to " + method);
        }
        return result;
    }

    protected void detectAnnotationExceptionMappings(Method method, List<Class<? extends Throwable>> result) {
        ExceptionHandler ann = AnnotationUtils.findAnnotation(method, ExceptionHandler.class);
        Assert.state(ann != null, "No ExceptionHandler annotation");
        result.addAll(Arrays.asList(ann.value()));
    }

    private void addExceptionMapping(Class<? extends Throwable> exceptionType, Method method) {
        Method oldMethod = this.mappedMethods.put(exceptionType, method);
        if (oldMethod != null && !oldMethod.equals(method)) {
            throw new IllegalStateException("Ambiguous @ExceptionHandler method mapped for [" + exceptionType + "]: {" + oldMethod + ", " + method + "}");
        }
    }

    /**
     * Whether the contained type has any exception mappings.
     */
    public boolean hasExceptionMappings() {
        return !this.mappedMethods.isEmpty();
    }

    /**
     * Find a {@link Method} to handle the given exception.
     * Use {@link ExceptionDepthComparator} if more than one match is found.
     * @param exception the exception
     * @return a Method to handle the exception, or {@code null} if none found
     */
    @Nullable
    public Method resolveMethod(Exception exception) {
        return resolveMethodByThrowable(exception);
    }

    /**
     * Find a {@link Method} to handle the given Throwable.
     * Use {@link ExceptionDepthComparator} if more than one match is found.
     * @param exception the exception
     * @return a Method to handle the exception, or {@code null} if none found
     * @since 5.0
     */
    @Nullable
    public Method resolveMethodByThrowable(Throwable exception) {
        Method method = resolveMethodByExceptionType(exception.getClass());
        if (method == null) {
            Throwable cause = exception.getCause();
            if (cause != null) {
                method = resolveMethodByExceptionType(cause.getClass());
            }
        }
        return method;
    }

    /**
     * Find a {@link Method} to handle the given exception type. This can be
     * useful if an {@link Exception} instance is not available (e.g. for tools).
     * @param exceptionType the exception type
     * @return a Method to handle the exception, or {@code null} if none found
     */

    /**
     * Return the {@link Method} mapped to the given exception type, or {@code null} if none.
     */
    @Nullable
    private Method getMappedMethod(Class<? extends Throwable> exceptionType) {
        List<Class<? extends Throwable>> matches = new ArrayList<>();
        for (Class<? extends Throwable> mappedException : this.mappedMethods.keySet()) {
            if (mappedException.isAssignableFrom(exceptionType)) {
                matches.add(mappedException);
            }
        }
        if (!matches.isEmpty()) {
            matches.sort(new ExceptionDepthComparator(exceptionType));
            return this.mappedMethods.get(matches.get(0));
        } else {
            return null;
        }
    }
}


void drawAppStatement(Canvas canvas, float fraction, String statement, int colorOfStatement, WidthAndHeightOfView widthAndHeightOfView);

package site.gemus.openingstartanimation;

import android.graphics.Canvas;
import android.graphics.drawable.Drawable;

/**
 * @author Jackdow
 * @version 1.0
 *          FancyView
 */
public interface DrawStrategy {

    /**
     * 绘制app名称文字
     * @param canvas 画布
     * @param fraction 完成时间百分比
     * @param colorOfAppName 字体颜色
     * @param name 文字
     * @param widthAndHeightOfView view的宽和高
     */
    void drawAppName(Canvas canvas, float fraction, String name, int colorOfAppName, WidthAndHeightOfView widthAndHeightOfView);

    /**
     * 绘制app图标
     * @param canvas 画布
     * @param fraction 完成时间百分比
     * @param colorOfIcon 绘制图标颜色
     * @param icon 图标
     * @param widthAndHeightOfView view的宽和高
     */
    void drawAppIcon(Canvas canvas, float fraction, Drawable icon, int colorOfIcon, WidthAndHeightOfView widthAndHeightOfView);

    /**
     * 绘制app一句话描述
     * @param canvas 画布
     * @param fraction 完成时间百分比
     * @param statement 一句话描述
     * @param colorOfStatement 字体颜色
     * @param widthAndHeightOfView view的宽和高
     */


public final static long hash(final byte[] array) {
        return hash(array, 0, array.length);
    }

package it.unimi.di.law.bubing.util;

import it.unimi.dsi.fastutil.bytes.ByteArrayList;

// RELEASE-STATUS: DIST
/**
 * A 64-bit implementation of MurmurHash3 for byte-array fragments.
 */
public class MurmurHash3 {

    private static final long getblock(final byte[] key, final int i) {
        return ((key[i + 0] & 0x00000000000000FFL) << 0) | ((key[i + 1] & 0x00000000000000FFL) << 8) | ((key[i + 2] & 0x00000000000000FFL) << 16) | ((key[i + 3] & 0x00000000000000FFL) << 24) | ((key[i + 4] & 0x00000000000000FFL) << 32) | ((key[i + 5] & 0x00000000000000FFL) << 40) | ((key[i + 6] & 0x00000000000000FFL) << 48) | ((key[i + 7] & 0x00000000000000FFL) << 56);
    }

    private static final long fmix(long k) {
        k ^= k >>> 33;
        k *= 0xff51afd7ed558ccdL;
        k ^= k >>> 33;
        k *= 0xc4ceb9fe1a85ec53L;
        k ^= k >>> 33;
        return k;
    }

    /**
     * Hashes a {@link ByteArrayList} using MurmurHash3 with seed zero.
     *
     * @param list a byte-array list
     * @return a 64-bit MurmurHash3 zero-seed hash for the specified fragment.
     */
    public final static long hash(final ByteArrayList list) {
        return hash(list.elements(), 0, list.size());
    }

    /**
     * Hashes a byte array using MurmurHash3 with seed zero.
     *
     * @param array a byte array.
     * @return a 64-bit MurmurHash3 zero-seed hash for the specified fragment.
     */

    /**
     * Hashes a byte-array fragment using MurmurHash3 with seed zero.
     *
     * @param array a byte array.
     * @param offset the first valid byte in {@code array}.
     * @param length the number of valid elements in {@code array}.
     * @return a 64-bit MurmurHash3 zero-seed hash for the specified fragment.
     */
    public final static long hash(final byte[] array, final int offset, final int length) {
        return hash(array, offset, length, 0);
    }

    /**
     * Hashes a byte-array fragment using MurmurHash3.
     *
     * @param array a byte array.
     * @param offset the first valid byte in {@code array}.
     * @param length the number of valid elements in {@code array}.
     * @param seed a seed.
     * @return a 64-bit MurmurHash3 hash for the specified fragment.
     */
    public final static long hash(final byte[] array, final int offset, final int length, final long seed) {
        long h1 = 0x9368e53c2f6af274L ^ seed;
        long h2 = 0x586dcd208f7cd3fdL ^ seed;
        long c1 = 0x87c37b91114253d5L;
        long c2 = 0x4cf5ad432745937fL;
        long k1 = 0;
        long k2 = 0;
        for (int i = 0; i < length / 16; i++) {
            k1 = getblock(array, offset + i * 2 * 8);
            k2 = getblock(array, offset + (i * 2 + 1) * 8);
            k1 *= c1;
            k1 = (k1 << 23) | (k1 >>> 64 - 23);
            k1 *= c2;
            h1 ^= k1;
            h1 += h2;
            h2 = (h2 << 41) | (h2 >>> 64 - 41);
            k2 *= c2;
            k2 = (k2 << 23) | (k2 >>> 64 - 23);
            k2 *= c1;
            h2 ^= k2;
            h2 += h1;
            h1 = h1 * 3 + 0x52dce729;
            h2 = h2 * 3 + 0x38495ab5;
            c1 = c1 * 5 + 0x7b7d159c;
            c2 = c2 * 5 + 0x6bce6396;
        }
        k1 = 0;
        k2 = 0;
        final int tail = offset + ((length >>> 4) << 4);
        switch(length & 15) {
            case 15:
                k2 ^= (long) array[tail + 14] << 48;
            case 14:
                k2 ^= (long) array[tail + 13] << 40;
            case 13:
                k2 ^= (long) array[tail + 12] << 32;
            case 12:
                k2 ^= (long) array[tail + 11] << 24;
            case 11:
                k2 ^= (long) array[tail + 10] << 16;
            case 10:
                k2 ^= (long) array[tail + 9] << 8;
            case 9:
                k2 ^= (long) array[tail + 8] << 0;
            case 8:
                k1 ^= (long) array[tail + 7] << 56;
            case 7:
                k1 ^= (long) array[tail + 6] << 48;
            case 6:
                k1 ^= (long) array[tail + 5] << 40;
            case 5:
                k1 ^= (long) array[tail + 4] << 32;
            case 4:
                k1 ^= (long) array[tail + 3] << 24;
            case 3:
                k1 ^= (long) array[tail + 2] << 16;
            case 2:
                k1 ^= (long) array[tail + 1] << 8;
            case 1:
                k1 ^= (long) array[tail + 0] << 0;
                k1 *= c1;
                k1 = (k1 << 23) | (k1 >>> 64 - 23);
                k1 *= c2;
                h1 ^= k1;
                h1 += h2;
                h2 = (h2 << 41) | (h2 >>> 64 - 41);
                k2 *= c2;
                k2 = (k2 << 23) | (k2 >>> 64 - 23);
                k2 *= c1;
                h2 ^= k2;
                h2 += h1;
                h1 = h1 * 3 + 0x52dce729;
                h2 = h2 * 3 + 0x38495ab5;
                c1 = c1 * 5 + 0x7b7d159c;
                c2 = c2 * 5 + 0x6bce6396;
        }
        h2 ^= length;
        h1 += h2;
        h2 += h1;
        h1 = fmix(h1);
        h2 = fmix(h2);
        h1 += h2;
        return h1;
    }
}


@Override
    public String read(String id) {
        return this.map.get(id);
    }

/**
 *  MapTable
 *  Copyright 16.01.2017 by Michael Peter Christen, @0rb1t3r
 */
package net.yacy.grid.io.db;

import java.io.IOException;
import java.util.Iterator;

/**
 * Table implementation based on Maps
 */
public class MapTable implements Table {

    private CloseableMap<String, String> map;

    /**
     * Initialize a table using a back-up map. All changes will be
     * reflected in the backedMap
     * @param backedMap the storage location for the table
     */
    public MapTable(CloseableMap<String, String> backedMap) {
        this.map = backedMap;
    }

    @Override
    public void close() {
        try {
            this.map.close();
        } catch (IOException e) {
        }
    }

    /**
     * get the size of the table
     * @return the number of entries in the table
     */
    @Override
    public long size() {
        return this.map.size();
    }

    /**
     * Write a key-value pair to the table
     * @param id the id of the entry
     * @param value the value of the entry
     */
    @Override
    public void write(String id, String value) {
        this.map.put(id, value);
    }

    /**
     * read an entry from the table
     * @param id the id of the entry
     * @return the value or null if the entry does not exist
     */

    /**
     * check if an entry exists
     * @param id the id of the entry
     * @return true if the entry exist and is non-empty, false otherwise
     */
    @Override
    public boolean exist(String id) {
        return this.map.containsKey(id);
    }

    /**
     * delete an entry from the table
     * @param id the id of the entry
     * @return true if the entry existed and was deleted, fals otherwise
     */
    @Override
    public boolean delete(String id) {
        return this.map.remove(id) != null;
    }

    @Override
    public Iterator<String> iterator() {
        return this.map.keySet().iterator();
    }
}


try {
            this.map.close();
        } catch (IOException e) {
        }

/**
 *  MapTable
 *  Copyright 16.01.2017 by Michael Peter Christen, @0rb1t3r
 */
package net.yacy.grid.io.db;

import java.io.IOException;
import java.util.Iterator;

/**
 * Table implementation based on Maps
 */
public class MapTable implements Table {

    private CloseableMap<String, String> map;

    /**
     * Initialize a table using a back-up map. All changes will be
     * reflected in the backedMap
     * @param backedMap the storage location for the table
     */
    public MapTable(CloseableMap<String, String> backedMap) {
        this.map = backedMap;
    }

    @Override
    public void close() {

    }

    /**
     * get the size of the table
     * @return the number of entries in the table
     */
    @Override
    public long size() {
        return this.map.size();
    }

    /**
     * Write a key-value pair to the table
     * @param id the id of the entry
     * @param value the value of the entry
     */
    @Override
    public void write(String id, String value) {
        this.map.put(id, value);
    }

    /**
     * read an entry from the table
     * @param id the id of the entry
     * @return the value or null if the entry does not exist
     */
    @Override
    public String read(String id) {
        return this.map.get(id);
    }

    /**
     * check if an entry exists
     * @param id the id of the entry
     * @return true if the entry exist and is non-empty, false otherwise
     */
    @Override
    public boolean exist(String id) {
        return this.map.containsKey(id);
    }

    /**
     * delete an entry from the table
     * @param id the id of the entry
     * @return true if the entry existed and was deleted, fals otherwise
     */
    @Override
    public boolean delete(String id) {
        return this.map.remove(id) != null;
    }

    @Override
    public Iterator<String> iterator() {
        return this.map.keySet().iterator();
    }
}


package org.apache.nifi.controller.queue;

import java.util.List;

public interface ListFlowFileStatus {

    /**
     * @return the maximum number of FlowFile Summary objects that should be returned
     */
    int getMaxResults();

    /**
     * @return the identifier of the request to drop FlowFiles from the queue
     */

/**
     * @return the date/time (in milliseconds since epoch) at which the request to
     *         drop the FlowFiles from a queue was submitted
     */
    long getRequestSubmissionTime();

    /**
     * @return the date/time (in milliseconds since epoch) at which the status of the
     *         request was last updated
     */
    long getLastUpdated();

    /**
     * @return the current state of the operation
     */
    ListFlowFileState getState();

    /**
     * @return the reason that the state is set to a Failure state, or null if the state is not {@link ListFlowFileStatus#FAILURE}.
     */
    String getFailureReason();

    /**
     * @return the current size of the queue
     */
    QueueSize getQueueSize();

    /**
     * @return a List of FlowFileSummary objects
     */
    List<FlowFileSummary> getFlowFileSummaries();

    /**
     * @return the percentage (an integer between 0 and 100, inclusive) of how close the request is to being completed
     */
    int getCompletionPercentage();
}


public BaseSliderView enableSaveImageByLongClick(FragmentManager mfmg) {
        mLongClickSaveImage = true;
        mDefaultLongClickListener = null;
        this.fmg = new WeakReference<FragmentManager>(mfmg);
        return this;
    }

package com.hkm.slider.SliderTypes;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.DrawableRes;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.RequestManager;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.hkm.slider.CapturePhotoUtils;
import com.hkm.slider.LoyalUtil;
import com.hkm.slider.R;
import com.hkm.slider.SliderLayout;
import com.squareup.picasso.Callback;
import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.RequestCreator;
import com.squareup.picasso.Target;
import java.io.File;
import java.lang.ref.WeakReference;

/**
 * When you want to make your own slider view, you must extends from this class.
 * BaseSliderView provides some useful methods.
 * I provide two example: {@link com.hkm.slider.SliderTypes.DefaultSliderView} and
 * {@link com.hkm.slider.SliderTypes.TextSliderView}
 * if you want to show progressbar, you just need to set a progressbar id as @+id/loading_bar.
 */
public abstract class BaseSliderView {

    protected Object current_image_holder;

    protected Context mContext;

    protected boolean imageLoaded = false;

    private RequestCreator rq = null;

    private final Bundle mBundle;

    protected int mTargetWidth, mTargetHeight;

    /**
     * Error place holder image.
     */
    private int mErrorPlaceHolderRes;

    /**
     * Empty imageView placeholder.
     */
    private int mEmptyPlaceHolderRes;

    private String mUrl;

    private File mFile;

    private int mRes;

    private int mSlideNumber;

    protected OnSliderClickListener mOnSliderClickListener;

    protected boolean mErrorDisappear, mLongClickSaveImage;

    protected boolean mImageLocalStorageEnable;

    private ImageLoadListener mLoadListener;

    private String mDescription;

    private Uri touch_information;

    /**
     * Scale type of the image.
     */
    protected ScaleType mScaleType = ScaleType.Fit;

    /**
     * reference of the parent
     */
    protected WeakReference<SliderLayout> sliderContainer;

    protected Typeface mTypeface;

    public void setSliderContainerInternal(SliderLayout b) {
        this.sliderContainer = new WeakReference<SliderLayout>(b);
    }

    public enum ScaleType {

        CenterCrop, CenterInside, Fit, FitCenterCrop
    }

    protected BaseSliderView(Context context) {
        mContext = context;
        this.mBundle = new Bundle();
        mLongClickSaveImage = false;
        mImageLocalStorageEnable = false;
    }

    public final void setSlideOrderNumber(final int order) {
        mSlideNumber = order;
    }

    public final int getSliderOrderNumber() {
        return mSlideNumber;
    }

    /**
     * the placeholder image when loading image from url or file.
     *
     * @param resId Image resource id
     * @return BaseSliderView
     */
    public BaseSliderView empty(int resId) {
        mEmptyPlaceHolderRes = resId;
        return this;
    }

    public BaseSliderView descriptionTypeface(Typeface typeface) {
        mTypeface = typeface;
        return this;
    }

    protected void setupDescription(TextView descTextView) {
        descTextView.setText(mDescription);
        if (mTypeface != null) {
            descTextView.setTypeface(mTypeface);
        }
    }

    /**
     * determine whether remove the image which failed to download or load from file
     *
     * @param disappear boolean
     * @return BaseSliderView
     */
    public BaseSliderView errorDisappear(boolean disappear) {
        mErrorDisappear = disappear;
        return this;
    }

    /**
     * if you set errorDisappear false, this will set a error placeholder image.
     *
     * @param resId image resource id
     * @return BaseSliderView
     */
    public BaseSliderView error(int resId) {
        mErrorPlaceHolderRes = resId;
        return this;
    }

    /**
     * the description of a slider image.
     *
     * @param description String
     * @return BaseSliderView
     */
    public BaseSliderView description(String description) {
        mDescription = description;
        return this;
    }

    /**
     * the url of the link or something related when the touch happens.
     *
     * @param info Uri
     * @return BaseSliderView
     */
    public BaseSliderView setUri(Uri info) {
        touch_information = info;
        return this;
    }

    /**
     * set a url as a image that preparing to load
     *
     * @param url String
     * @return BaseSliderView
     */
    public BaseSliderView image(String url) {
        if (mFile != null || mRes != 0) {
            throw new IllegalStateException("Call multi image function," + "you only have permission to call it once");
        }
        mUrl = url;
        return this;
    }

    /**
     * set a file as a image that will to load
     *
     * @param file java.io.File
     * @return BaseSliderView
     */
    public BaseSliderView image(File file) {
        if (mUrl != null || mRes != 0) {
            throw new IllegalStateException("Call multi image function," + "you only have permission to call it once");
        }
        mFile = file;
        return this;
    }

    public BaseSliderView image(@DrawableRes int res) {
        if (mUrl != null || mFile != null) {
            throw new IllegalStateException("Call multi image function," + "you only have permission to call it once");
        }
        mRes = res;
        return this;
    }

    /**
     * get the url of the image path
     *
     * @return the path in string
     */
    public String getUrl() {
        return mUrl;
    }

    /**
     * get the url from the touch event
     *
     * @return the touch event URI
     */
    public Uri getTouchURI() {
        return touch_information;
    }

    public boolean isErrorDisappear() {
        return mErrorDisappear;
    }

    public int getEmpty() {
        return mEmptyPlaceHolderRes;
    }

    public int getError() {
        return mErrorPlaceHolderRes;
    }

    public String getDescription() {
        return mDescription;
    }

    public Context getContext() {
        return mContext;
    }

    /**
     * set a slider image click listener
     *
     * @param l the listener
     * @return the base slider
     */
    public BaseSliderView setOnSliderClickListener(OnSliderClickListener l) {
        mOnSliderClickListener = l;
        return this;
    }

    protected View.OnLongClickListener mDefaultLongClickListener = null;

    protected WeakReference<FragmentManager> fmg;

    /**
     * to enable the slider for saving images
     *
     * @param mfmg FragmentManager
     * @return this thing
     */

    /**
     * to set custom listener for long click event
     *
     * @param listen the listener
     * @return thos thomg
     */
    public BaseSliderView setSliderLongClickListener(View.OnLongClickListener listen) {
        mDefaultLongClickListener = listen;
        mLongClickSaveImage = false;
        return this;
    }

    public BaseSliderView setSliderLongClickListener(View.OnLongClickListener listen, FragmentManager mfmg) {
        mDefaultLongClickListener = listen;
        mLongClickSaveImage = false;
        this.fmg = new WeakReference<FragmentManager>(mfmg);
        return this;
    }

    public BaseSliderView resize(int targetWidth, int targetHeight) {
        if (targetWidth < 0) {
            throw new IllegalArgumentException("Width must be positive number or 0.");
        }
        if (targetHeight < 0) {
            throw new IllegalArgumentException("Height must be positive number or 0.");
        }
        if (targetHeight == 0 && targetWidth == 0) {
            throw new IllegalArgumentException("At least one dimension has to be positive number.");
        }
        mTargetWidth = targetWidth;
        mTargetHeight = targetHeight;
        return this;
    }

    public BaseSliderView enableImageLocalStorage() {
        mImageLocalStorageEnable = true;
        return this;
    }

    protected void hideLoadingProgress(View mView) {
        if (mView.findViewById(R.id.ns_loading_progress) != null) {
            hideoutView(mView.findViewById(R.id.ns_loading_progress));
        }
    }

    /**
     * when {@link #mLongClickSaveImage} is true and this function will be triggered to watch the long action run
     *
     * @param mView the slider view object
     */
    private void triggerOnLongClick(View mView) {
        if (mLongClickSaveImage && fmg != null) {
            if (mDefaultLongClickListener == null) {
                mDefaultLongClickListener = new View.OnLongClickListener() {

                    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
                    @Override
                    public boolean onLongClick(View v) {
                        final saveImageDialog saveImageDial = new saveImageDialog();
                        saveImageDial.show(fmg.get(), mDescription);
                        return false;
                    }
                };
            }
            mView.setOnLongClickListener(mDefaultLongClickListener);
        }
    }

    private final View.OnClickListener click_triggered = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (mOnSliderClickListener != null) {
                mOnSliderClickListener.onSliderClick(BaseSliderView.this);
            }
        }
    };

    /**
     * When you want to implement your own slider view, please call this method in the end in `getView()` method
     *
     * @param v               the whole view
     * @param targetImageView where to place image
     */
    protected void bindEventAndShowPicasso(final View v, final ImageView targetImageView) {
        current_image_holder = targetImageView;
        v.setOnClickListener(click_triggered);
        mLoadListener.onStart(this);
        final Picasso p = Picasso.with(mContext);
        rq = null;
        if (mUrl != null) {
            rq = p.load(mUrl);
        } else if (mFile != null) {
            rq = p.load(mFile);
        } else if (mRes != 0) {
            rq = p.load(mRes);
        } else {
            return;
        }
        if (rq == null) {
            return;
        }
        if (getEmpty() != 0) {
            rq.placeholder(getEmpty());
        }
        if (getError() != 0) {
            rq.error(getError());
        }
        if (mTargetWidth > 0 || mTargetHeight > 0) {
            rq.resize(mTargetWidth, mTargetHeight);
        }
        if (mImageLocalStorageEnable) {
            rq.memoryPolicy(MemoryPolicy.NO_STORE, MemoryPolicy.NO_CACHE);
        }
        switch(mScaleType) {
            case Fit:
                rq.fit();
                break;
            case CenterCrop:
                rq.fit().centerCrop();
                break;
            case CenterInside:
                rq.fit().centerInside();
                break;
        }
        rq.into(targetImageView, new Callback() {

            @Override
            public void onSuccess() {
                imageLoaded = true;
                hideLoadingProgress(v);
                triggerOnLongClick(v);
                reportStatusEnd(true);
            }

            @Override
            public void onError() {
                reportStatusEnd(false);
            }
        });
    }

    protected void bindEventShowGlide(final View v, final ImageView targetImageView) {
        RequestOptions requestOptions = new RequestOptions();
        v.setOnClickListener(click_triggered);
        final RequestManager glideRM = Glide.with(mContext);
        RequestBuilder rq;
        if (mUrl != null) {
            rq = glideRM.load(mUrl);
        } else if (mFile != null) {
            rq = glideRM.load(mFile);
        } else if (mRes != 0) {
            rq = glideRM.load(mRes);
        } else {
            return;
        }
        if (getEmpty() != 0) {
            requestOptions.placeholder(getEmpty());
        }
        if (getError() != 0) {
            requestOptions.error(getError());
        }
        switch(mScaleType) {
            case Fit:
                requestOptions.fitCenter();
                break;
            case CenterCrop:
                requestOptions.centerCrop();
                break;
            case CenterInside:
                requestOptions.fitCenter();
                break;
        }
        requestOptions.diskCacheStrategy(DiskCacheStrategy.ALL);
        if (mTargetWidth > 0 || mTargetHeight > 0) {
            requestOptions.override(mTargetWidth, mTargetHeight);
        }
        rq.apply(requestOptions);
        rq.listener(new RequestListener() {

            @Override
            public boolean onLoadFailed(@Nullable GlideException e, Object model, com.bumptech.glide.request.target.Target target, boolean isFirstResource) {
                reportStatusEnd(false);
                return false;
            }

            @Override
            public boolean onResourceReady(Object resource, Object model, com.bumptech.glide.request.target.Target target, DataSource dataSource, boolean isFirstResource) {
                hideLoadingProgress(v);
                triggerOnLongClick(v);
                reportStatusEnd(true);
                return false;
            }
        });
        rq.transition(DrawableTransitionOptions.withCrossFade());
        additionalGlideModifier(rq);
        rq.into(targetImageView);
    }

    protected void additionalGlideModifier(RequestBuilder requestBuilder) {
    }

    protected void applyImageWithGlide(View v, final ImageView targetImageView) {
        current_image_holder = targetImageView;
        LoyalUtil.glideImplementation(getUrl(), targetImageView, getContext());
        hideLoadingProgress(v);
        triggerOnLongClick(v);
        reportStatusEnd(true);
        imageLoaded = true;
    }

    protected void applyImageWithPicasso(View v, final ImageView targetImageView) {
        current_image_holder = targetImageView;
        LoyalUtil.picassoImplementation(getUrl(), targetImageView, getContext());
        hideLoadingProgress(v);
        triggerOnLongClick(v);
        imageLoaded = true;
        reportStatusEnd(true);
    }

    protected void applyImageWithSmartBoth(View v, final ImageView target) {
        current_image_holder = target;
        LoyalUtil.hybridImplementation(getUrl(), target, getContext());
        hideLoadingProgress(v);
        triggerOnLongClick(v);
        imageLoaded = true;
        reportStatusEnd(true);
    }

    protected void applyImageWithSmartBothAndNotifyHeight(View v, final ImageView target) {
        current_image_holder = target;
        LoyalUtil.hybridImplementation(getUrl(), target, getContext(), new Runnable() {

            @Override
            public void run() {
                imageLoaded = true;
                if (sliderContainer == null)
                    return;
                if (sliderContainer.get().getCurrentPosition() == getSliderOrderNumber()) {
                    sliderContainer.get().setFitToCurrentImageHeight();
                }
            }
        });
        hideLoadingProgress(v);
        triggerOnLongClick(v);
        reportStatusEnd(true);
    }

    private void reportStatusEnd(boolean b) {
        if (mLoadListener != null) {
            mLoadListener.onEnd(b, this);
        }
    }

    final android.os.Handler nh = new android.os.Handler();

    private int notice_save_image_success = R.string.success_save_image;

    public final void setMessageSaveImageSuccess(@StringRes final int t) {
        notice_save_image_success = t;
    }

    protected void workAroundGetImagePicasso() {
        final Target target = new Target() {

            @Override
            public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
            }

            @Override
            public void onBitmapFailed(Drawable errorDrawable) {
            }

            @Override
            public void onPrepareLoad(Drawable placeHolderDrawable) {
            }
        };
    }

    protected void workGetImage(ImageView imageView) {
        imageView.setDrawingCacheEnabled(true);
        imageView.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        imageView.layout(0, 0, imageView.getMeasuredWidth(), imageView.getMeasuredHeight());
        imageView.buildDrawingCache(true);
        output_bitmap = Bitmap.createBitmap(imageView.getDrawingCache());
        imageView.setDrawingCacheEnabled(false);
    }

    private Bitmap output_bitmap = null;

    private class getImageTask extends AsyncTask<Void, Void, Integer> {

        private ImageView imageView;

        public getImageTask(ImageView taskTarget) {
            imageView = taskTarget;
        }

        @Override
        protected Integer doInBackground(Void... params) {
            int tried = 0;
            while (tried < 5) {
                try {
                    workGetImage(imageView);
                    return 1;
                } catch (Exception e) {
                    tried++;
                }
            }
            return 0;
        }

        @Override
        protected void onPostExecute(Integer result) {
            super.onPostExecute(result);
            if (result == 1) {
                CapturePhotoUtils.insertImage(mContext, output_bitmap, mDescription, new CapturePhotoUtils.Callback() {

                    @Override
                    public void complete() {
                        nh.post(new Runnable() {

                            @Override
                            public void run() {
                                if (fmg == null)
                                    return;
                                String note = mContext.getString(notice_save_image_success);
                                final SMessage sm = SMessage.message(note);
                                sm.show(fmg.get(), "done");
                            }
                        });
                    }
                });
            } else {
                String m = mContext.getString(R.string.image_not_read);
                final SMessage sm = SMessage.message(m);
                sm.show(fmg.get(), "try again");
            }
        }
    }

    /**
     * should use OnImageSavedListener instead or other listener for dialogs
     */
    @Deprecated
    @SuppressLint("ValidFragment")
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public static class SMessage extends DialogFragment {

        public static SMessage message(final String mes) {
            Bundle h = new Bundle();
            h.putString("message", mes);
            SMessage e = new SMessage();
            e.setArguments(h);
            return e;
        }

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            // Use the Builder class for convenient dialog construction
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setMessage(getArguments().getString("message")).setNeutralButton(R.string.okay_now, new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int id) {
                    dialog.dismiss();
                }
            });
            return builder.create();
        }
    }

    @SuppressLint("ValidFragment")
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public class saveImageDialog extends DialogFragment {

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            if (mContext == null)
                return null;
            // Use the Builder class for convenient dialog construction
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
            builder.setMessage(R.string.save_image).setPositiveButton(R.string.yes_save, new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int id) {
                    saveImageActionTrigger();
                }
            }).setNegativeButton(R.string.no_keep, new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int id) {
                    dialog.dismiss();
                }
            });
            // Create the AlertDialog object and return it
            return builder.create();
        }
    }

    protected void saveImageActionTrigger() {
        if (current_image_holder == null)
            return;
        if (current_image_holder instanceof ImageView) {
            ImageView fast = (ImageView) current_image_holder;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (mContext.getApplicationContext().checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                } else {
                    getImageTask t = new getImageTask(fast);
                    t.execute();
                }
            } else {
                getImageTask t = new getImageTask(fast);
                t.execute();
            }
        }
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    final protected void hideoutView(@Nullable final View view) {
        if (view == null)
            return;
        view.animate().alpha(0f).withEndAction(new Runnable() {

            @Override
            public void run() {
                view.setVisibility(View.INVISIBLE);
            }
        });
    }

    public BaseSliderView setScaleType(ScaleType type) {
        mScaleType = type;
        return this;
    }

    public ScaleType getScaleType() {
        return mScaleType;
    }

    /**
     * the extended class have to implement getView(), which is called by the adapter,
     * every extended class response to render their own view.
     *
     * @return View
     */
    public abstract View getView();

    /**
     * set a listener to get a message , if load error.
     *
     * @param l ImageLoadListener
     */
    public void setOnImageLoadListener(ImageLoadListener l) {
        mLoadListener = l;
    }

    public interface OnSliderClickListener {

        void onSliderClick(BaseSliderView coreSlider);
    }

    /**
     * when you have some extra information, please put it in this bundle.
     *
     * @return Bundle
     */
    public Bundle getBundle() {
        return mBundle;
    }

    public interface ImageLoadListener {

        void onStart(BaseSliderView target);

        void onEnd(boolean result, BaseSliderView target);
    }

    public Object getImageView() {
        return current_image_holder;
    }

    public interface OnImageSavedListener {

        void onImageSaved(String description);

        void onImageSaveFailed();
    }

    protected OnImageSavedListener onImageSavedListener = null;

    public OnImageSavedListener getOnImageSavedListener() {
        return onImageSavedListener;
    }

    public void setOnImageSavedListener(OnImageSavedListener onImageSavedListener) {
        this.onImageSavedListener = onImageSavedListener;
    }
}


switch(mScaleType) {
            case Fit:
                requestOptions.fitCenter();
                break;
            case CenterCrop:
                requestOptions.centerCrop();
                break;
            case CenterInside:
                requestOptions.fitCenter();
                break;
        }

package com.hkm.slider.SliderTypes;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.DrawableRes;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.RequestManager;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.hkm.slider.CapturePhotoUtils;
import com.hkm.slider.LoyalUtil;
import com.hkm.slider.R;
import com.hkm.slider.SliderLayout;
import com.squareup.picasso.Callback;
import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.RequestCreator;
import com.squareup.picasso.Target;
import java.io.File;
import java.lang.ref.WeakReference;

/**
 * When you want to make your own slider view, you must extends from this class.
 * BaseSliderView provides some useful methods.
 * I provide two example: {@link com.hkm.slider.SliderTypes.DefaultSliderView} and
 * {@link com.hkm.slider.SliderTypes.TextSliderView}
 * if you want to show progressbar, you just need to set a progressbar id as @+id/loading_bar.
 */
public abstract class BaseSliderView {

    protected Object current_image_holder;

    protected Context mContext;

    protected boolean imageLoaded = false;

    private RequestCreator rq = null;

    private final Bundle mBundle;

    protected int mTargetWidth, mTargetHeight;

    /**
     * Error place holder image.
     */
    private int mErrorPlaceHolderRes;

    /**
     * Empty imageView placeholder.
     */
    private int mEmptyPlaceHolderRes;

    private String mUrl;

    private File mFile;

    private int mRes;

    private int mSlideNumber;

    protected OnSliderClickListener mOnSliderClickListener;

    protected boolean mErrorDisappear, mLongClickSaveImage;

    protected boolean mImageLocalStorageEnable;

    private ImageLoadListener mLoadListener;

    private String mDescription;

    private Uri touch_information;

    /**
     * Scale type of the image.
     */
    protected ScaleType mScaleType = ScaleType.Fit;

    /**
     * reference of the parent
     */
    protected WeakReference<SliderLayout> sliderContainer;

    protected Typeface mTypeface;

    public void setSliderContainerInternal(SliderLayout b) {
        this.sliderContainer = new WeakReference<SliderLayout>(b);
    }

    public enum ScaleType {

        CenterCrop, CenterInside, Fit, FitCenterCrop
    }

    protected BaseSliderView(Context context) {
        mContext = context;
        this.mBundle = new Bundle();
        mLongClickSaveImage = false;
        mImageLocalStorageEnable = false;
    }

    public final void setSlideOrderNumber(final int order) {
        mSlideNumber = order;
    }

    public final int getSliderOrderNumber() {
        return mSlideNumber;
    }

    /**
     * the placeholder image when loading image from url or file.
     *
     * @param resId Image resource id
     * @return BaseSliderView
     */
    public BaseSliderView empty(int resId) {
        mEmptyPlaceHolderRes = resId;
        return this;
    }

    public BaseSliderView descriptionTypeface(Typeface typeface) {
        mTypeface = typeface;
        return this;
    }

    protected void setupDescription(TextView descTextView) {
        descTextView.setText(mDescription);
        if (mTypeface != null) {
            descTextView.setTypeface(mTypeface);
        }
    }

    /**
     * determine whether remove the image which failed to download or load from file
     *
     * @param disappear boolean
     * @return BaseSliderView
     */
    public BaseSliderView errorDisappear(boolean disappear) {
        mErrorDisappear = disappear;
        return this;
    }

    /**
     * if you set errorDisappear false, this will set a error placeholder image.
     *
     * @param resId image resource id
     * @return BaseSliderView
     */
    public BaseSliderView error(int resId) {
        mErrorPlaceHolderRes = resId;
        return this;
    }

    /**
     * the description of a slider image.
     *
     * @param description String
     * @return BaseSliderView
     */
    public BaseSliderView description(String description) {
        mDescription = description;
        return this;
    }

    /**
     * the url of the link or something related when the touch happens.
     *
     * @param info Uri
     * @return BaseSliderView
     */
    public BaseSliderView setUri(Uri info) {
        touch_information = info;
        return this;
    }

    /**
     * set a url as a image that preparing to load
     *
     * @param url String
     * @return BaseSliderView
     */
    public BaseSliderView image(String url) {
        if (mFile != null || mRes != 0) {
            throw new IllegalStateException("Call multi image function," + "you only have permission to call it once");
        }
        mUrl = url;
        return this;
    }

    /**
     * set a file as a image that will to load
     *
     * @param file java.io.File
     * @return BaseSliderView
     */
    public BaseSliderView image(File file) {
        if (mUrl != null || mRes != 0) {
            throw new IllegalStateException("Call multi image function," + "you only have permission to call it once");
        }
        mFile = file;
        return this;
    }

    public BaseSliderView image(@DrawableRes int res) {
        if (mUrl != null || mFile != null) {
            throw new IllegalStateException("Call multi image function," + "you only have permission to call it once");
        }
        mRes = res;
        return this;
    }

    /**
     * get the url of the image path
     *
     * @return the path in string
     */
    public String getUrl() {
        return mUrl;
    }

    /**
     * get the url from the touch event
     *
     * @return the touch event URI
     */
    public Uri getTouchURI() {
        return touch_information;
    }

    public boolean isErrorDisappear() {
        return mErrorDisappear;
    }

    public int getEmpty() {
        return mEmptyPlaceHolderRes;
    }

    public int getError() {
        return mErrorPlaceHolderRes;
    }

    public String getDescription() {
        return mDescription;
    }

    public Context getContext() {
        return mContext;
    }

    /**
     * set a slider image click listener
     *
     * @param l the listener
     * @return the base slider
     */
    public BaseSliderView setOnSliderClickListener(OnSliderClickListener l) {
        mOnSliderClickListener = l;
        return this;
    }

    protected View.OnLongClickListener mDefaultLongClickListener = null;

    protected WeakReference<FragmentManager> fmg;

    /**
     * to enable the slider for saving images
     *
     * @param mfmg FragmentManager
     * @return this thing
     */
    public BaseSliderView enableSaveImageByLongClick(FragmentManager mfmg) {
        mLongClickSaveImage = true;
        mDefaultLongClickListener = null;
        this.fmg = new WeakReference<FragmentManager>(mfmg);
        return this;
    }

    /**
     * to set custom listener for long click event
     *
     * @param listen the listener
     * @return thos thomg
     */
    public BaseSliderView setSliderLongClickListener(View.OnLongClickListener listen) {
        mDefaultLongClickListener = listen;
        mLongClickSaveImage = false;
        return this;
    }

    public BaseSliderView setSliderLongClickListener(View.OnLongClickListener listen, FragmentManager mfmg) {
        mDefaultLongClickListener = listen;
        mLongClickSaveImage = false;
        this.fmg = new WeakReference<FragmentManager>(mfmg);
        return this;
    }

    public BaseSliderView resize(int targetWidth, int targetHeight) {
        if (targetWidth < 0) {
            throw new IllegalArgumentException("Width must be positive number or 0.");
        }
        if (targetHeight < 0) {
            throw new IllegalArgumentException("Height must be positive number or 0.");
        }
        if (targetHeight == 0 && targetWidth == 0) {
            throw new IllegalArgumentException("At least one dimension has to be positive number.");
        }
        mTargetWidth = targetWidth;
        mTargetHeight = targetHeight;
        return this;
    }

    public BaseSliderView enableImageLocalStorage() {
        mImageLocalStorageEnable = true;
        return this;
    }

    protected void hideLoadingProgress(View mView) {
        if (mView.findViewById(R.id.ns_loading_progress) != null) {
            hideoutView(mView.findViewById(R.id.ns_loading_progress));
        }
    }

    /**
     * when {@link #mLongClickSaveImage} is true and this function will be triggered to watch the long action run
     *
     * @param mView the slider view object
     */
    private void triggerOnLongClick(View mView) {
        if (mLongClickSaveImage && fmg != null) {
            if (mDefaultLongClickListener == null) {
                mDefaultLongClickListener = new View.OnLongClickListener() {

                    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
                    @Override
                    public boolean onLongClick(View v) {
                        final saveImageDialog saveImageDial = new saveImageDialog();
                        saveImageDial.show(fmg.get(), mDescription);
                        return false;
                    }
                };
            }
            mView.setOnLongClickListener(mDefaultLongClickListener);
        }
    }

    private final View.OnClickListener click_triggered = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (mOnSliderClickListener != null) {
                mOnSliderClickListener.onSliderClick(BaseSliderView.this);
            }
        }
    };

    /**
     * When you want to implement your own slider view, please call this method in the end in `getView()` method
     *
     * @param v               the whole view
     * @param targetImageView where to place image
     */
    protected void bindEventAndShowPicasso(final View v, final ImageView targetImageView) {
        current_image_holder = targetImageView;
        v.setOnClickListener(click_triggered);
        mLoadListener.onStart(this);
        final Picasso p = Picasso.with(mContext);
        rq = null;
        if (mUrl != null) {
            rq = p.load(mUrl);
        } else if (mFile != null) {
            rq = p.load(mFile);
        } else if (mRes != 0) {
            rq = p.load(mRes);
        } else {
            return;
        }
        if (rq == null) {
            return;
        }
        if (getEmpty() != 0) {
            rq.placeholder(getEmpty());
        }
        if (getError() != 0) {
            rq.error(getError());
        }
        if (mTargetWidth > 0 || mTargetHeight > 0) {
            rq.resize(mTargetWidth, mTargetHeight);
        }
        if (mImageLocalStorageEnable) {
            rq.memoryPolicy(MemoryPolicy.NO_STORE, MemoryPolicy.NO_CACHE);
        }
        switch(mScaleType) {
            case Fit:
                rq.fit();
                break;
            case CenterCrop:
                rq.fit().centerCrop();
                break;
            case CenterInside:
                rq.fit().centerInside();
                break;
        }
        rq.into(targetImageView, new Callback() {

            @Override
            public void onSuccess() {
                imageLoaded = true;
                hideLoadingProgress(v);
                triggerOnLongClick(v);
                reportStatusEnd(true);
            }

            @Override
            public void onError() {
                reportStatusEnd(false);
            }
        });
    }

    protected void bindEventShowGlide(final View v, final ImageView targetImageView) {
        RequestOptions requestOptions = new RequestOptions();
        v.setOnClickListener(click_triggered);
        final RequestManager glideRM = Glide.with(mContext);
        RequestBuilder rq;
        if (mUrl != null) {
            rq = glideRM.load(mUrl);
        } else if (mFile != null) {
            rq = glideRM.load(mFile);
        } else if (mRes != 0) {
            rq = glideRM.load(mRes);
        } else {
            return;
        }
        if (getEmpty() != 0) {
            requestOptions.placeholder(getEmpty());
        }
        if (getError() != 0) {
            requestOptions.error(getError());
        }

        requestOptions.diskCacheStrategy(DiskCacheStrategy.ALL);
        if (mTargetWidth > 0 || mTargetHeight > 0) {
            requestOptions.override(mTargetWidth, mTargetHeight);
        }
        rq.apply(requestOptions);
        rq.listener(new RequestListener() {

            @Override
            public boolean onLoadFailed(@Nullable GlideException e, Object model, com.bumptech.glide.request.target.Target target, boolean isFirstResource) {
                reportStatusEnd(false);
                return false;
            }

            @Override
            public boolean onResourceReady(Object resource, Object model, com.bumptech.glide.request.target.Target target, DataSource dataSource, boolean isFirstResource) {
                hideLoadingProgress(v);
                triggerOnLongClick(v);
                reportStatusEnd(true);
                return false;
            }
        });
        rq.transition(DrawableTransitionOptions.withCrossFade());
        additionalGlideModifier(rq);
        rq.into(targetImageView);
    }

    protected void additionalGlideModifier(RequestBuilder requestBuilder) {
    }

    protected void applyImageWithGlide(View v, final ImageView targetImageView) {
        current_image_holder = targetImageView;
        LoyalUtil.glideImplementation(getUrl(), targetImageView, getContext());
        hideLoadingProgress(v);
        triggerOnLongClick(v);
        reportStatusEnd(true);
        imageLoaded = true;
    }

    protected void applyImageWithPicasso(View v, final ImageView targetImageView) {
        current_image_holder = targetImageView;
        LoyalUtil.picassoImplementation(getUrl(), targetImageView, getContext());
        hideLoadingProgress(v);
        triggerOnLongClick(v);
        imageLoaded = true;
        reportStatusEnd(true);
    }

    protected void applyImageWithSmartBoth(View v, final ImageView target) {
        current_image_holder = target;
        LoyalUtil.hybridImplementation(getUrl(), target, getContext());
        hideLoadingProgress(v);
        triggerOnLongClick(v);
        imageLoaded = true;
        reportStatusEnd(true);
    }

    protected void applyImageWithSmartBothAndNotifyHeight(View v, final ImageView target) {
        current_image_holder = target;
        LoyalUtil.hybridImplementation(getUrl(), target, getContext(), new Runnable() {

            @Override
            public void run() {
                imageLoaded = true;
                if (sliderContainer == null)
                    return;
                if (sliderContainer.get().getCurrentPosition() == getSliderOrderNumber()) {
                    sliderContainer.get().setFitToCurrentImageHeight();
                }
            }
        });
        hideLoadingProgress(v);
        triggerOnLongClick(v);
        reportStatusEnd(true);
    }

    private void reportStatusEnd(boolean b) {
        if (mLoadListener != null) {
            mLoadListener.onEnd(b, this);
        }
    }

    final android.os.Handler nh = new android.os.Handler();

    private int notice_save_image_success = R.string.success_save_image;

    public final void setMessageSaveImageSuccess(@StringRes final int t) {
        notice_save_image_success = t;
    }

    protected void workAroundGetImagePicasso() {
        final Target target = new Target() {

            @Override
            public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
            }

            @Override
            public void onBitmapFailed(Drawable errorDrawable) {
            }

            @Override
            public void onPrepareLoad(Drawable placeHolderDrawable) {
            }
        };
    }

    protected void workGetImage(ImageView imageView) {
        imageView.setDrawingCacheEnabled(true);
        imageView.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        imageView.layout(0, 0, imageView.getMeasuredWidth(), imageView.getMeasuredHeight());
        imageView.buildDrawingCache(true);
        output_bitmap = Bitmap.createBitmap(imageView.getDrawingCache());
        imageView.setDrawingCacheEnabled(false);
    }

    private Bitmap output_bitmap = null;

    private class getImageTask extends AsyncTask<Void, Void, Integer> {

        private ImageView imageView;

        public getImageTask(ImageView taskTarget) {
            imageView = taskTarget;
        }

        @Override
        protected Integer doInBackground(Void... params) {
            int tried = 0;
            while (tried < 5) {
                try {
                    workGetImage(imageView);
                    return 1;
                } catch (Exception e) {
                    tried++;
                }
            }
            return 0;
        }

        @Override
        protected void onPostExecute(Integer result) {
            super.onPostExecute(result);
            if (result == 1) {
                CapturePhotoUtils.insertImage(mContext, output_bitmap, mDescription, new CapturePhotoUtils.Callback() {

                    @Override
                    public void complete() {
                        nh.post(new Runnable() {

                            @Override
                            public void run() {
                                if (fmg == null)
                                    return;
                                String note = mContext.getString(notice_save_image_success);
                                final SMessage sm = SMessage.message(note);
                                sm.show(fmg.get(), "done");
                            }
                        });
                    }
                });
            } else {
                String m = mContext.getString(R.string.image_not_read);
                final SMessage sm = SMessage.message(m);
                sm.show(fmg.get(), "try again");
            }
        }
    }

    /**
     * should use OnImageSavedListener instead or other listener for dialogs
     */
    @Deprecated
    @SuppressLint("ValidFragment")
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public static class SMessage extends DialogFragment {

        public static SMessage message(final String mes) {
            Bundle h = new Bundle();
            h.putString("message", mes);
            SMessage e = new SMessage();
            e.setArguments(h);
            return e;
        }

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            // Use the Builder class for convenient dialog construction
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setMessage(getArguments().getString("message")).setNeutralButton(R.string.okay_now, new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int id) {
                    dialog.dismiss();
                }
            });
            return builder.create();
        }
    }

    @SuppressLint("ValidFragment")
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public class saveImageDialog extends DialogFragment {

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            if (mContext == null)
                return null;
            // Use the Builder class for convenient dialog construction
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
            builder.setMessage(R.string.save_image).setPositiveButton(R.string.yes_save, new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int id) {
                    saveImageActionTrigger();
                }
            }).setNegativeButton(R.string.no_keep, new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int id) {
                    dialog.dismiss();
                }
            });
            // Create the AlertDialog object and return it
            return builder.create();
        }
    }

    protected void saveImageActionTrigger() {
        if (current_image_holder == null)
            return;
        if (current_image_holder instanceof ImageView) {
            ImageView fast = (ImageView) current_image_holder;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (mContext.getApplicationContext().checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                } else {
                    getImageTask t = new getImageTask(fast);
                    t.execute();
                }
            } else {
                getImageTask t = new getImageTask(fast);
                t.execute();
            }
        }
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    final protected void hideoutView(@Nullable final View view) {
        if (view == null)
            return;
        view.animate().alpha(0f).withEndAction(new Runnable() {

            @Override
            public void run() {
                view.setVisibility(View.INVISIBLE);
            }
        });
    }

    public BaseSliderView setScaleType(ScaleType type) {
        mScaleType = type;
        return this;
    }

    public ScaleType getScaleType() {
        return mScaleType;
    }

    /**
     * the extended class have to implement getView(), which is called by the adapter,
     * every extended class response to render their own view.
     *
     * @return View
     */
    public abstract View getView();

    /**
     * set a listener to get a message , if load error.
     *
     * @param l ImageLoadListener
     */
    public void setOnImageLoadListener(ImageLoadListener l) {
        mLoadListener = l;
    }

    public interface OnSliderClickListener {

        void onSliderClick(BaseSliderView coreSlider);
    }

    /**
     * when you have some extra information, please put it in this bundle.
     *
     * @return Bundle
     */
    public Bundle getBundle() {
        return mBundle;
    }

    public interface ImageLoadListener {

        void onStart(BaseSliderView target);

        void onEnd(boolean result, BaseSliderView target);
    }

    public Object getImageView() {
        return current_image_holder;
    }

    public interface OnImageSavedListener {

        void onImageSaved(String description);

        void onImageSaveFailed();
    }

    protected OnImageSavedListener onImageSavedListener = null;

    public OnImageSavedListener getOnImageSavedListener() {
        return onImageSavedListener;
    }

    public void setOnImageSavedListener(OnImageSavedListener onImageSavedListener) {
        this.onImageSavedListener = onImageSavedListener;
    }
}