Showing posts with label URL. Show all posts
Showing posts with label URL. Show all posts

Friday, February 8, 2019

Getting url() in a Command returns http://localhost | URL generated in a queue - localhost returned | URL in jobs only return localhost | URL problem with queued jobs

First need to specify url to project/config/app.php as below:

<?php
return [
    'url' => 'http://localhost:81/my_laravel_project/'
];

Now need to modify project/app/Providers/RouteServiceProvider.php as below:


<?php
namespace App\Providers;

use Illuminate\Routing\Router;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;

class RouteServiceProvider extends ServiceProvider
{
    /**
     * This namespace is applied to the controller routes in your routes file.
     *
     * In addition, it is set as the URL generator's root namespace.
     *
     * @var string
     */
    protected $namespace = 'App\Http\Controllers';

    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @param  \Illuminate\Routing\Router  $router
     * @return void
     */
    public function boot(Router $router)
    {
        parent::boot($router);

        $url = $this->app['url'];
        $url->forceRootUrl(config('app.url'));
    }

    /**
     * Define the routes for the application.
     *
     * @param  \Illuminate\Routing\Router  $router
     * @return void
     */
    public function map(Router $router)
    {
        $router->group(['namespace' => $this->namespace], function ($router) {
            require app_path('Http/routes.php');
        });
    }
}

Monday, June 26, 2017

Validating a URL in PHP

Check if the variable $url is a valid URL:

The FILTER_VALIDATE_URL filter validates a URL.

Possible  flags:

FILTER_FLAG_SCHEME_REQUIRED - URL must be RFC compliant.
Like http://example

FILTER_FLAG_HOST_REQUIRED - URL must include host name.
Like http://www.example.com

FILTER_FLAG_PATH_REQUIRED - URL must have a path after domain.
Like www.example.com/example1/

FILTER_FLAG_QUERY_REQUIRED - URL must have a query string.
Like "example.php?name=Peter&age=37"

filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED)
filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED)
filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED)
filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_QUERY_REQUIRED)


Friday, April 21, 2017

Get the Referer URL in CakePHP 3.X

Get Refer URL is not a big task in CakePHP now.

Just do the following to get Refer URL:

echo "Referrer URL=" . $this->referer('/') . "<BR>";

echo "Referrer URL=" . $this->referer('/', true) . "<BR>";

Which will output:

Referrer URL=http://localhost/cake/pages/database_check

Referrer URL=/pages/database_check

How to get complete current URL for Cakephp 3.x

Below are few steps described to get URL inside Cakephp 3.x controller as well as view file. You can get full URL and base URL and current URL inside Controller.

The very first thing is to include Router in your Controller as below:

use Cake\Routing\Router;


public function urls()
{
    echo "<div style=''>";
    echo "Current URL=" . Router::url(null, true);
    echo "<BR>Current URL=" . Router::url(null, false);
    echo "<BR>Current URL=" . $this->request->getUri();
    echo "<BR>Current URL=" . $this->request->getUri()->getPath();
    echo "<BR>Current URL=" . $this->request->getRequestTarget();
    echo "<BR>Full URL=" . Router::url("/", true);
    echo "<BR>Base URL=" . Router::url("/", false);
    die("</div>");
}


And output would like this:

Current URL=http://localhost/cake/pages/urls
Current URL=/cake/pages/urls
Current URL=http://localhost/pages/urls?id=20&name=Pritom
Current URL=/pages/urls
Current URL=/pages/urls?id=20&name=Pritom
Full URL=http://localhost/cake/
Base URL=/cake/

Friday, February 24, 2017

Get Current URL Using Laravel

Laravel is a strong php based framework today. We frequently coding on this platform. And who coded its important for him to know / get current working url sometimes. Its easy to get current url inside an Controller/Service class. Just need to use Request attribute to get desired output at Laravel. 

First need to import Request class to Controller/Service class:
use Illuminate\Http\Request;

And then need to pass Request as parameter as follows:
public function someAction(Request $request)

And finally use following method to get current full url:
$request->fullUrl();

You have different options when you use Laravel Request class as follows:

Get the request method
$request->method();

Get the root URL for the application
$request->root();

Get the URL (no query string) for the request
$request->url();

Get the full URL for the request
$request->fullUrl();

Get the current path info for the request
$request->path();

Determine if the request is the result of an AJAX call
$request->ajax(); 


There is another way around to get URL from Laravel Controller
At first you have to import following component:
use Illuminate\Routing\UrlGenerator;

Then need to initialize it on construct on controller as follows:
private $UrlGenerator;
public function __construct(UrlGenerator $UrlGenerator)
{
    $this->UrlGenerator = $UrlGenerator;
}

And then use below line of code get Laravel base URL:
$urlGenerator->to("/");

You can get all available method details of UrlGenerator from below link:
https://laravel.com/api/5.0/Illuminate/Routing/UrlGenerator.html
  

Wednesday, June 3, 2015

Validate URL Using Java & Regex


class UrlValidator {
    public static void main (String[] args) {
        check("http://google.com");
        check("http://google.com?a=b#99");
        check("http://google.com?a=b#99#sty");
        check("http://www.google.com?a=1&b=2 / 3");
        check("http://www.google.com?a=1&orderRate=orderRateUUID");
    }

    public static void check(String url) {
        String Regex = "^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";

        Boolean matches = url.matches(Regex);

        if(matches) {
            System.out.println("URL (YES): " + url);
        }
        else {
            System.out.println("URL (NOT): " + url);
        }
    }
}


URL (YES): http://google.com
URL (YES): http://google.com?a=b#99
URL (YES): http://google.com?a=b#99#sty
URL (NOT): http://www.google.com?a=1&b=2 / 3
URL (YES): http://www.google.com?a=1&orderRate=orderRateUUID

Sunday, October 6, 2013

Grails and dynamic controller names in UrlMappings

I was creating some REST web services and I needed to map a URL like “/api/1.0/recipes” to a controller called RecipesRestController. It took me a while to work out how to generate a dynamic controller name from the request path. The trick is not to use $controller, it doesn’t seem to work, so instead I renamed it $aController.


class UrlMappings {
    static mappings = {
        "/$controller/$action?/$id?"{
            constraints {
                // apply constraints here
            }
        }
        "/"(view:"/index")
        "500"(view:'/error')
        "/api/1.0/$aController"{
            controller={"${params.aController}Rest"}
            action=[GET:"list", POST:"save"]
        }
        "/api/1.0/$aController/$id"{
            controller={"${params.aController}Rest"}
            action=[GET:"show",  PUT:"update", DELETE:"delete"]
        }
    }
}

 

OR

 
import org.codehaus.groovy.grails.commons.ApplicationHolder

class UrlMappings {
  static mappings = {        
    for( controllerClass in ApplicationHolder.application.controllerClasses) {
      // Admin Controllers first
      if( controllerClass.name.startsWith("Admin")){
        // note... fixes the case so that AdminUserController maps to /admin/user
        "/admin/${controllerClass.name[5].toLowerCase() + controllerClass.name[6..-1]}/$action?/$id?" {
          controller = "admin${controllerClass.name[5..-1]}".toString()
        }
      }
    }
  }
}
 

OR


    "/admin/$controller/$action?/$id?"{
        controller = {
            def controllerName = (request.requestURI - request.contextPath).split('/')[2]

            // or
            //def controllerName = request.servletPath.split('/')[2]

            "${controllerName}Admin"
        }
    }

Wednesday, September 11, 2013

HTTP RAW URL Address Encode in Java as application/x-www-form-urlencoded


package com.pritom.kumar;

import java.net.URLDecoder;
import java.net.URLEncoder;

public class RawUrlEncodeDecode {
    public static void main(String[] args) throws Exception{
        String toEncode = "a & b+c_d+e / é <p>Hello</p><?xml version='1.0'><name>Pritom K Mondal</name>";
        String encoded = URLEncoder.encode(toEncode, "UTF-8");
        System.out.println("Encoded: " + encoded);
        String decoded = URLDecoder.decode(encoded, "UTF-8");
        System.out.println("Decoded: " + decoded);
    }
}

Output

Encoded: a+%26+b%2Bc_d%2Be+%2F+%C3%A9+%3Cp%3EHello%3C%2Fp%3E%3C%3Fxml+version%3D%271.0%27%3E%3Cname%3EPritom+K+Mondal%3C%2Fname%3E

Decoded: a & b+c_d+e / é <p>Hello</p><?xml version='1.0'><name>Pritom K Mondal</name>

Tuesday, July 30, 2013

Java - Call URL And Sending HTTP Parameters Via GET POST PUT PATCH DELETE Method Easily Execute

Its very easy to invoke URL using Java, We can now send GET, POST, PUT, PATCH And Delete method easily. Invoking URL in Java is easy now. Call URL and get response from that URL is can be done using Java code.

package common;

import java.io.*;
import java.lang.reflect.Field;
import java.net.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;

/**
 * Created by pritom on 11/07/2016.
 */
public abstract class HttpJavaClient {    
    public static enum Method {
        GET, POST, PUT, PATCH, DELETE
    }

    public static enum Type {
        XML, JSON, URL_ENCODED;
    }
    ;

    public static void main(String[] args) throws Exception {
        Response response = doGet("https://pritomkumar.blogspot.com");
        println("Get_Result:\n" + lengthString(response.toString().replace("\n", ""), 400) + "...");

        Map params = new HashMap();
        params.put("param1", "Param1 value");
        params.put("param2", "Param2 value");

        response = doPost("https://pritomkumar.blogspot.com", buildParameters(params), Type.URL_ENCODED);
        println("Post_Result:\n" + lengthString(response.toString().replace("\n", ""), 400) + "...");
    }

    public static Response doGet(String url) {
        return execute(url, Method.GET, "", Type.URL_ENCODED);
    }

    public static Response doGet(String url, Map headers) {
        return execute(url, Method.GET, "", Type.URL_ENCODED, headers, null);
    }

    public static Response doPost(String url, String data, Type type) {
        return execute(url, Method.POST, data, type);
    }

    public static Response doPost(String url, String data, Type type, Map headers) {
        return execute(url, Method.POST, data, type, headers, null);
    }

    public static Response doPut(String url, String data, Type type) {
        return execute(url, Method.PUT, data, type);
    }

    public static Response doPut(String url, String data, Type type, Map headers) {
        return execute(url, Method.PUT, data, type, headers, null);
    }

    public static Response doPatch(String url, String data, Type type) {
        return execute(url, Method.PATCH, data, type);
    }

    public static Response doPatch(String url, String data, Type type, Map headers) {
        return execute(url, Method.PATCH, data, type, headers, null);
    }

    public static Response doDelete(String url) {
        return execute(url, Method.DELETE, "", Type.URL_ENCODED);
    }

    public static Response doDelete(String url, Map headers) {
        return execute(url, Method.DELETE, "", Type.URL_ENCODED, headers, null);
    }

    public static Response execute(String url, Method method, String data, Type type) {
        return execute(url, method, data, type, null, null);
    }

    private static Response execute(String requestURL, Method requestMethod, String requestData, Type dataType, Map headers, Integer timeOutMilli) {
        Long started = System.currentTimeMillis();
        String httpResponse = "", responseMessage = "";
        Integer httpCode = 0;
        timeOutMilli = timeOutMilli == null ? 1000 * 30 : timeOutMilli; /* Default read & write timeout */

        HttpsURLConnection connection = null;
        try {
            String contentType = "", accept = "", contentLength = "" + requestData.length();
            switch (dataType) {
                case XML:
                    contentType = "text/xml; charset=utf-8";
                    accept = "text/xml";
                    break;
                case JSON:
                    contentType = "application/json";
                    break;
                case URL_ENCODED:
                    contentType = "application/x-www-form-urlencoded";
                    break;
            }

            connection = (HttpsURLConnection) new URL(requestURL).openConnection();
            setRequestMethod(connection, requestMethod.name());
            connection.setDoOutput(true);
            connection.setConnectTimeout(timeOutMilli);
            connection.setReadTimeout(timeOutMilli);
            connection.setRequestProperty("Pragma", "no-cache");

            if (headers != null && headers.size() > 0) {
                for (Object name : headers.keySet().toArray()) {
                    if (name.toString().endsWith("tls")) {
                        //headers.put("tls", "TLSv1.2");
                        //headers.put("tls", "TLSv1");
                        SSLContext sc = SSLContext.getInstance(headers.get(name.toString()).toString());
                        sc.init(null, null, new java.security.SecureRandom()); 
                        connection.setSSLSocketFactory(sc.getSocketFactory());
                    }
                    else {
                        connection.setRequestProperty(name.toString(), headers.get(name.toString()).toString());
                    }
                }
            }

            if (requestData.length() > 0) {
                connection.setDoInput(true);

                if (accept.length() > 0) {
                    connection.setRequestProperty("Accept", accept);
                }
                if (contentType.length() > 0) {
                    connection.setRequestProperty("Content-Type", contentType);
                }

                connection.setRequestProperty("Content_length", contentLength);
                OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
                writer.write(requestData);
                writer.flush();
                writer.close();
            }

            httpCode = connection.getResponseCode();
            responseMessage = connection.getResponseMessage();
            InputStream is = null;

            if (httpCode >= 200 && httpCode <= 299) {
                is = connection.getInputStream();
            }
            else {
                is = connection.getErrorStream();
            }

            Writer writer5 = new StringWriter();
            char[] buffer = new char[1024];
            try {
                Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                int n;
                while ((n = reader.read(buffer)) != -1) {
                    writer5.write(buffer, 0, n);
                }
                httpResponse = writer5.toString();
            }
            catch (Exception ex) {
                httpResponse = "";
                responseMessage = ex.getMessage();
            }
        }
        catch (Exception ex) {
            httpResponse = "";
            responseMessage = ex.getMessage();
        }
        finally {
            try {
                connection.disconnect();
            }
            catch (Exception ex10) {
            }
        }

        return new Response(requestURL, httpCode, responseMessage, httpResponse, (System.currentTimeMillis() - started));
    }

    /* JAVA - HttpURLConnection Invalid HTTP method such as 'PATCH' */
    private static void setRequestMethod(final HttpsURLConnection httpURLConnection, final String method) throws Exception {
        try {
            httpURLConnection.setRequestMethod(method);
        }
        catch (final ProtocolException pe) {
            Class<?> connectionClass = httpURLConnection.getClass();
            Field delegateField = null;
            try {
                delegateField = connectionClass.getDeclaredField("delegate");
                delegateField.setAccessible(true);
                HttpsURLConnection delegateConnection = (HttpsURLConnection) delegateField.get(httpURLConnection);
                setRequestMethod(delegateConnection, method);
            }
            catch (NoSuchFieldException e) {
                // Ignore for now, keep going
            }
            catch (IllegalArgumentException e) {
                throw new RuntimeException(e);
            }
            catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
            try {
                Field methodField;
                while (connectionClass != null) {
                    try {
                        methodField = connectionClass.getDeclaredField("method");
                    }
                    catch (NoSuchFieldException e) {
                        connectionClass = connectionClass.getSuperclass();
                        continue;
                    }
                    methodField.setAccessible(true);
                    methodField.set(httpURLConnection, method);
                    break;
                }
            }
            catch (final Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static String buildParameters(Map parametersMap) {
        Iterator nameIterator = parametersMap.keySet().iterator();
        StringBuffer buf = new StringBuffer();

        while (nameIterator.hasNext()) {
            Object key = nameIterator.next();
            Object value = parametersMap.get(key);
            if (value == null) {
                value = "";
            }

            if (!(key instanceof String)) {
                throw new IllegalArgumentException("Expected a string key in parametersMap but found " + key);
            }

            if (!(value instanceof String)) {
                throw new IllegalArgumentException("Expected a string value in parametersMap but found " + value);
            }

            String parameterName = (String) key;
            String parameterValue = (String) value;
            if (buf.length() > 0) {
                buf.append('&');
            }

            try {
                buf.append(parameterName);
                buf.append('=');
                buf.append(URLEncoder.encode(parameterValue, "UTF-8"));
            }
            catch (Exception var9) {
                var9.printStackTrace();
            }
        }

        return buf.toString();
    }

    public static void parseParameters(String s, String enc, Map parameters) {
        if (s != null) {
            int start = 0;
            int end = s.length();
            boolean amp = true;

            do {
                int amp1 = s.indexOf(38, start);
                if (amp1 == -1) {
                    amp1 = end;
                }

                int eq = s.indexOf(61, start);
                if (eq == -1 || eq > amp1) {
                    eq = amp1;
                }

                String name = s.substring(start, eq);
                String value = eq == amp1 ? "" : s.substring(eq + 1, amp1);

                try {
                    parameters.put(URLDecoder.decode(name, enc), URLDecoder.decode(value, enc));
                }
                catch (Exception var11) {
                    var11.printStackTrace();
                }

                start = amp1 + 1;
            } while (start < end);
        }
    }

    public static class Response {
        private String url;
        private Integer code;
        private String message;
        private String body;
        private Long time;

        public Response(String url, Integer code, String message, String body, Long time) {
            this.url = url;
            this.code = code;
            this.message = message;
            this.body = body;
            this.time = time;
        }

        @Override
        public String toString() {
            return "{URL=" + this.url + ",Code=" + this.code + ", Message=" + this.message + ", Time=" + this.time + " Millis, Body=" + this.body + "}";
        }

        public Integer getCode() {
            return this.code;
        }

        public String getMessage() {
            return this.message;
        }

        public String getBody() {
            return this.body;
        }

        public Long getTime() {
            return this.time;
        }
    }

    public static void println(Object o) {
        System.out.println("" + o);
    }

    public static String lengthString(String s, Integer m) {
        return s.length() > m ? s.substring(0, m) : s;
    }
}