com.sqewd.os.maracache.mdfs.VersionUtils.java Source code

Java tutorial

Introduction

Here is the source code for com.sqewd.os.maracache.mdfs.VersionUtils.java

Source

/*
 * Copyright 2014, Subhabrata Ghosh
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.sqewd.os.maracache.mdfs;

import com.sqewd.os.maracache.api.utils.NetUtils;
import org.apache.commons.lang.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.Inet4Address;
import java.net.SocketException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

/**
 * Utility functions for generating and managing data versions.
 *
 * @author Subho Ghosh (subho dot ghosh at outlook.com)
 * @created 22/05/14
 */
public class VersionUtils {
    private static long iphash = 0;

    static {
        try {
            Inet4Address ia = NetUtils.address();
            if (ia != null) {
                String v = ia.getHostAddress();
                if (!StringUtils.isEmpty(v)) {
                    String[] parts = v.split("\\.");
                    if (parts != null && parts.length > 0) {
                        for (int ii = 0; ii < parts.length; ii++) {
                            String p = parts[parts.length - 1 - ii];
                            iphash += Math.pow(10, ii) * Integer.parseInt(p);
                        }
                    }
                }
            }
        } catch (SocketException se) {
            se.printStackTrace();
        }
    }

    public static long next(long current) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        while (true) {
            UUID uuid = UUID.randomUUID();

            char[] buff = uuid.toString().toCharArray();
            long v = System.currentTimeMillis();

            for (int ii = 0; ii < buff.length; ii++) {
                v += (buff[ii] * (ii + iphash));
            }

            if (v != current) {
                return v;
            }
        }
    }
}