net.yatomiya.nicherry.ui.handlers.SearchWebHandler.java Source code

Java tutorial

Introduction

Here is the source code for net.yatomiya.nicherry.ui.handlers.SearchWebHandler.java

Source

/*******************************************************************************
 * Copyright (c) 2014,2015 Hideki Yatomi
 * All rights reserved. This program and the accompanying materials are made
 * available under the terms of the Eclipse Public License v1.0 which
 * accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 ******************************************************************************/
package net.yatomiya.nicherry.ui.handlers;

import javax.inject.*;
import org.eclipse.e4.core.di.annotations.*;
import org.eclipse.e4.ui.services.*;
import org.eclipse.jface.text.*;
import org.eclipse.swt.program.*;
import com.squareup.okhttp.*;
import net.yatomiya.e4.util.*;
import net.yatomiya.nicherry.*;

public class SearchWebHandler {
    static final int MAX_QUERY_SIZE = 1024;
    static final String QUERY_REPLACE = "{$query}";

    @Execute
    public void execute(@Optional @Named(IServiceConstants.ACTIVE_SELECTION) TextSelection selection) {
        String query = selection.getText();
        query = HttpUtils.urlEncode(query);
        String searchUrl = NUtils.getPreference(NPreferences.WEB_SEARCH_URL);
        searchUrl = searchUrl.replace(QUERY_REPLACE, query);
        HttpUrl url = HttpUrl.parse(searchUrl);

        Program.launch(url.toString());
    }

    @CanExecute
    public boolean canExecute(@Optional @Named(IServiceConstants.ACTIVE_SELECTION) TextSelection selection) {
        return selection != null && !selection.isEmpty() && (selection.getLength() < MAX_QUERY_SIZE)

                && !JUtils.isEmpty(NUtils.getPreference(NPreferences.WEB_SEARCH_URL));
    }
}