Java Code Examples for java.text.MessageFormat

The following are top voted examples for showing how to use java.text.MessageFormat. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: ramus   File: JNLPSeasonInternetServlet.java   View source code 7 votes vote down vote up
private void accept(HttpServletRequest req, HttpServletResponse resp) {
    try {
        String localAddr = req.getLocalAddr();
        Properties properties = EngineFactory.getPropeties();
        if (properties.getProperty("hostname") != null) {
            localAddr = properties.getProperty("hostname");
        }
        String path = "http://" + localAddr + ":" + req.getLocalPort()
                + req.getContextPath();
        InputStream is = getClass().getResourceAsStream(
                "/com/ramussoft/jnlp/season-internet-client.jnlp");
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int r;
        while ((r = is.read()) >= 0)
            out.write(r);
        String string = MessageFormat.format(new String(out.toByteArray(),
                "UTF8"), path);
        resp.setContentType("application/x-java-jnlp-file");
        OutputStream o = resp.getOutputStream();
        o.write(string.getBytes("UTF8"));
        o.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}
 
Example 2
Project: pgcodekeeper   File: ModelExporter.java   View source code 7 votes vote down vote up
private File mkdirObjects(File parentOutDir, String outDirName)
        throws NotDirectoryException, DirectoryException {
    File objectDir = new File(parentOutDir, outDirName);

    if(objectDir.exists()) {
        if(!objectDir.isDirectory()) {
            throw new NotDirectoryException(objectDir.getAbsolutePath());
        }
    } else {
        if(!objectDir.mkdir()) {
            throw new DirectoryException(MessageFormat.format(
                    "Could not create objects directory: {0}",
                    objectDir.getAbsolutePath()));
        }
    }
    return objectDir;
}
 
Example 3
Project: alfresco-remote-api   File: TestRemovePermissions.java   View source code 6 votes vote down vote up
protected Session getBROWSER_11_Session()
{
    try
    {
        Map<String, String> parameter = new HashMap<String, String>();
        int port = getTestFixture().getJettyComponent().getPort();

        parameter.put(SessionParameter.BINDING_TYPE, BindingType.BROWSER.value());
        parameter.put(SessionParameter.BROWSER_URL, MessageFormat.format(BROWSE_URL_11, DEFAULT_HOSTNAME, String.valueOf(port)));
        parameter.put(SessionParameter.COOKIES, "true");

        parameter.put(SessionParameter.USER, ADMIN_USER);
        parameter.put(SessionParameter.PASSWORD, ADMIN_PASSWORD);

        SessionFactory sessionFactory = SessionFactoryImpl.newInstance();

        parameter.put(SessionParameter.REPOSITORY_ID, sessionFactory.getRepositories(parameter).get(0).getId());
        return sessionFactory.createSession(parameter);
    }
    catch (Exception ex)
    {
        logger.error(ex);

    }
    return null;
}
 
Example 4
Project: Open-DM   File: ConfigurationHelper.java   View source code 6 votes vote down vote up
public static int getIntegerProperty(String key, int defaultVal) {
    String propertyValue;
    Integer retval;
    propertyValue = getStringProperty(key, null);

    if (propertyValue == null || propertyValue.trim().length() < 1) {
        retval = defaultVal;

    } else {
        try {
            retval = Integer.parseInt(propertyValue);
        } catch (NumberFormatException e) {
            String msg = "Read configuration property {0} = {1}, but could not convert it to type {2}.";
            Object[] objs = new Object[] {
                    key,
                    propertyValue,
                    Integer.class.getName(),
            };
            LOG.log(Level.WARNING, MessageFormat.format(msg, objs), e);
            throw e;
        }
    }
    return retval;
}
 
Example 5
Project: Transwarp-Sample-Code   File: KerberosWebHDFSConnection2.java   View source code 6 votes vote down vote up
/**
 * <b>CREATESYMLINK</b>
 *
 * curl -i -X PUT "http://<HOST>:<PORT>/<PATH>?op=CREATESYMLINK
 * &destination=<PATH>[&createParent=<true|false>]"
 *
 * @param srcPath
 * @param destPath
 * @return
 * @throws AuthenticationException
 * @throws IOException
 * @throws MalformedURLException
 */
public String createSymLink(String srcPath, String destPath)
        throws MalformedURLException, IOException, AuthenticationException {
    String resp = null;
    ensureValidToken();

    HttpURLConnection conn = authenticatedURL.openConnection(
            new URL(new URL(httpfsUrl), MessageFormat.format(
                    "/webhdfs/v1/{0}?op=CREATESYMLINK&destination={1}",
                    URLUtil.encodePath(srcPath),
                    URLUtil.encodePath(destPath))), token);
    conn.setRequestMethod("PUT");
    conn.connect();
    resp = result(conn, true);
    conn.disconnect();

    return resp;
}
 
Example 6
Project: parabuild-ci   File: FindBugsFrame.java   View source code 6 votes vote down vote up
public String toString() {
	try {
		BugInstance bugInstance = (BugInstance) getUserObject();
		StringBuffer result = new StringBuffer();

		if (count >= 0) {
			result.append(count);
			result.append(": ");
		}

		if (bugInstance.isExperimental())
			result.append(L10N.getLocalString("msg.exp_txt", "EXP: "));

		result.append(fullDescriptionsItem.isSelected() ? bugInstance.getMessage() : bugInstance.toString());

		return result.toString();
	} catch (Exception e) {
		return MessageFormat.format(L10N.getLocalString("msg.errorformatting_txt", "Error formatting message for bug: "), new Object[]{e.toString()});
	}
}
 
Example 7
Project: apache-tomcat-7.0.73-with-comment   File: JNDIRealm.java   View source code 6 votes vote down vote up
/**
 * Set the message format pattern for selecting users in this Realm.
 * This may be one simple pattern, or multiple patterns to be tried,
 * separated by parentheses. (for example, either "cn={0}", or
 * "(cn={0})(cn={0},o=myorg)" Full LDAP search strings are also supported,
 * but only the "OR", "|" syntax, so "(|(cn={0})(cn={0},o=myorg))" is
 * also valid. Complex search strings with &, etc are NOT supported.
 *
 * @param userPattern The new user pattern
 */
public void setUserPattern(String userPattern) {

    this.userPattern = userPattern;
    if (userPattern == null)
        userPatternArray = null;
    else {
        userPatternArray = parseUserPatternString(userPattern);
        int len = this.userPatternArray.length;
        userPatternFormatArray = new MessageFormat[len];
        for (int i=0; i < len; i++) {
            userPatternFormatArray[i] =
                new MessageFormat(userPatternArray[i]);
        }
    }
}
 
Example 8
Project: jwala   File: GroupServiceImpl.java   View source code 6 votes vote down vote up
@Override
@Transactional
public Group createGroup(final CreateGroupRequest createGroupRequest,
                         final User aCreatingUser) {
    createGroupRequest.validate();
    try {
        groupPersistenceService.getGroup(createGroupRequest.getGroupName());
        String message = MessageFormat.format("Group Name already exists: {0} ", createGroupRequest.getGroupName());
        LOGGER.error(message);
        throw new EntityExistsException(message);
    } catch (NotFoundException e) {
        LOGGER.debug("No group name conflict, ignoring not found exception for creating group ", e);
    }

    return groupPersistenceService.createGroup(createGroupRequest);
}
 
Example 9
Project: ramus   File: ReportEditorView.java   View source code 6 votes vote down vote up
protected String getHTMLText() {
    String page;
    try {
        HashMap<String, Object> map = new HashMap<String, Object>();
        Query query = queryView.getQuery();
        if (query != null)
            map.put("query", query);
        page = ((ReportQuery) framework.getEngine()).getHTMLReport(element,
                map);
    } catch (Exception e1) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        PrintStream s = new PrintStream(stream);
        e1.printStackTrace();
        if (e1 instanceof DataException)
            s.println(((DataException) e1)
                    .getMessage(new MessageFormatter() {

                        @Override
                        public String getString(String key,
                                                Object[] arguments) {
                            return MessageFormat.format(
                                    ReportResourceManager.getString(key),
                                    arguments);
                        }
                    }));
        else {
            e1.printStackTrace(s);
        }

        s.flush();

        page = new String(stream.toByteArray());
    }
    return page;
}
 
Example 10
Project: incubator-servicecomb-java-chassis   File: TracingConfiguration.java   View source code 6 votes vote down vote up
@Bean
Sender sender(DynamicProperties dynamicProperties) {
  apiVersion = dynamicProperties.getStringProperty(CONFIG_TRACING_COLLECTOR_API_VERSION,
      CONFIG_TRACING_COLLECTOR_API_V2).toLowerCase();
  // use default value if the user set value is invalid
  if (apiVersion.compareTo(CONFIG_TRACING_COLLECTOR_API_V1) != 0){
    apiVersion = CONFIG_TRACING_COLLECTOR_API_V2;
  }

  String path = MessageFormat.format(CONFIG_TRACING_COLLECTOR_PATH, apiVersion);
  return OkHttpSender.create(
      dynamicProperties.getStringProperty(
          CONFIG_TRACING_COLLECTOR_ADDRESS,
          DEFAULT_TRACING_COLLECTOR_ADDRESS)
          .trim()
          .replaceAll("/+$", "")
          .concat(path));
}
 
Example 11
Project: cloud-ariba-partner-flow-extension-ext   File: EcmServiceProvider.java   View source code 6 votes vote down vote up
private static EcmService initEcmService() {
	LOGGER.debug(DEBUG_INITIALIZING_ECM_SERVICE);

	EcmService ecmService;
	try {
		InitialContext initialContext = new InitialContext();
		ecmService = (EcmService) initialContext.lookup(ECM_SERVICE_NAME);
	} catch (NamingException e) {
		String errorMessage = MessageFormat.format(ERROR_LOOKING_UP_THE_ECM_SERVICE_FAILED, ECM_SERVICE_NAME);
		LOGGER.error(errorMessage, e);
		throw new RuntimeException(errorMessage, e);
	}

	LOGGER.debug(DEBUG_ECM_SERVICE_INITIALIZED);
	return ecmService;
}
 
Example 12
Project: CalendarFX   File: SearchResultViewSkin.java   View source code 6 votes vote down vote up
private String getTimeText(Entry<?> entry) {
    if (entry.isFullDay()) {
        return "all-day"; //$NON-NLS-1$
    }

    LocalDate startDate = entry.getStartDate();
    LocalDate endDate = entry.getEndDate();

    String text;
    if (startDate.equals(endDate)) {
        text = MessageFormat.format(Messages.getString("SearchResultViewSkin.FROM_UNTIL"), //$NON-NLS-1$
                timeFormatter.format(entry.getStartTime()),
                timeFormatter.format(entry.getEndTime()));
    } else {
        text = MessageFormat.format(Messages.getString("SearchResultViewSkin.FROM_UNTIL_WITH_DATE"), //$NON-NLS-1$
                timeFormatter.format(entry.getStartTime()),
                dateFormatter.format(entry.getStartDate()),
                timeFormatter.format(entry.getEndTime()),
                dateFormatter.format(entry.getEndDate()));
    }

    return text;
}
 
Example 13
Project: hepek-classycle   File: XMLAtomicVertexRenderer.java   View source code 6 votes vote down vote up
/**
 * Renderes the specified vertex. It is assumed that the vertex attributes are of the type
 * {@link classycle.ClassAttributes}.
 *
 * @return the rendered vertex.
 */
@Override
public String render(AtomicVertex vertex, StrongComponent cycle, int layerIndex) {
    final StringBuilder result = new StringBuilder();
    result.append(getVertexRenderer().render(vertex, cycle, layerIndex));
    final MessageFormat format = new MessageFormat(
            "      <" + getRefElement() + " name=\"{0}\"" + " type=\"{1}\"/>\n");
    final String[] values = new String[2];
    for (int i = 0, n = vertex.getNumberOfIncomingArcs(); i < n; i++) {
        values[0] = ((NameAttributes) vertex.getTailVertex(i).getAttributes()).getName();
        values[1] = "usedBy";
        result.append(format.format(values));
    }
    for (int i = 0, n = vertex.getNumberOfOutgoingArcs(); i < n; i++) {
        values[0] = ((NameAttributes) vertex.getHeadVertex(i).getAttributes()).getName();
        values[1] = ((AtomicVertex) vertex.getHeadVertex(i)).isGraphVertex() ? "usesInternal" : "usesExternal";
        result.append(format.format(values));
    }
    result.append("    </").append(getElement()).append(">\n");
    return result.toString();
}
 
Example 14
Project: incubator-netbeans   File: OptionsExportModel.java   View source code 6 votes vote down vote up
/** Adds build.info file with product, os, java version to zip file. */
private static void createProductInfo(ZipOutputStream out) throws IOException {
    String productVersion = MessageFormat.format(
            NbBundle.getBundle("org.netbeans.core.startup.Bundle").getString("currentVersion"), //NOI18N
            new Object[]{System.getProperty("netbeans.buildnumber")}); //NOI18N
    String os = System.getProperty("os.name", "unknown") + ", " + //NOI18N
            System.getProperty("os.version", "unknown") + ", " + //NOI18N
            System.getProperty("os.arch", "unknown"); //NOI18N
    String java = System.getProperty("java.version", "unknown") + ", " + //NOI18N
            System.getProperty("java.vm.name", "unknown") + ", " + //NOI18N
            System.getProperty("java.vm.version", ""); //NOI18N
    out.putNextEntry(new ZipEntry("build.info"));  //NOI18N
    PrintWriter writer = new PrintWriter(out);
    writer.println("NetbeansBuildnumber=" + System.getProperty("netbeans.buildnumber")); //NOI18N
    writer.println("ProductVersion=" + productVersion); //NOI18N
    writer.println("OS=" + os); //NOI18N
    writer.println("Java=" + java); //NOI18Nv
    writer.println("Userdir=" + System.getProperty("netbeans.user")); //NOI18N
    writer.flush();
    // Complete the entry
    out.closeEntry();
}
 
Example 15
Project: SKIL_Examples   File: Model.java   View source code 6 votes vote down vote up
public JSONObject addModel(String name, String fileLocation, int scale, String uri) {
    JSONObject model = new JSONObject();

    try {
        List<String> uriList = new ArrayList<String>();
        uriList.add(uri);

        model =
                Unirest.post(MessageFormat.format("http://{0}:{1}/deployment/{2}/model", host, port, deploymentID))
                        .header("accept", "application/json")
                        .header("Content-Type", "application/json")
                        .body(new JSONObject()
                                .put("name", name)
                                .put("modelType", "model")
                                .put("fileLocation", fileLocation)
                                .put("scale", scale)
                                .put("uri", uriList)
                                .toString())
                        .asJson()
                        .getBody().getObject();
    } catch (UnirestException e) {
        e.printStackTrace();
    }

    return model;
}
 
Example 16
Project: Equella   File: Version.java   View source code 6 votes vote down vote up
public WebVersion getDeployedVersion()
{
	WebVersion version = new WebVersion();
	File versionFile = new File(getVersionPropertiesDirectory(), "version.properties");
	try( FileInputStream in = new FileInputStream(versionFile) )
	{
		Properties p = new Properties();
		p.load(in);
		version.setDisplayName(p.getProperty("version.display"));
		version.setMmr(p.getProperty("version.mmr"));
		version.setFilename(MessageFormat.format("tle-upgrade-{0} ({1}).zip", p.getProperty("version.mmr"),
			p.getProperty("version.display")));
	}
	catch( IOException ex )
	{
		version.setDisplayName(Utils.UNKNOWN_VERSION);
	}
	return version;
}
 
Example 17
Project: pgcodekeeper   File: IPgObjectPage.java   View source code 6 votes vote down vote up
static IFolder createSchema(String name, boolean open, IProject project) throws CoreException {
    IFolder projectFolder = project.getFolder(DbObjType.SCHEMA.name());
    if (!projectFolder.exists()) {
        projectFolder.create(false, true, null);
    }
    IFolder schemaFolder = projectFolder.getFolder(name);
    if (!schemaFolder.exists()) {
        schemaFolder.create(false, true, null);
    }
    IFile file = projectFolder.getFile(name + POSTFIX);
    if (!file.exists()) {
        StringBuilder sb = new StringBuilder();
        sb.append(MessageFormat.format(PATTERN, DbObjType.SCHEMA, name));
        sb.append(MessageFormat.format(OWNER_TO, DbObjType.SCHEMA, name));
        file.create(new ByteArrayInputStream(sb.toString().getBytes()), false, null);
    }
    if (open) {
        openFileInEditor(file);
    }
    return schemaFolder;
}
 
Example 18
Project: hadoop-oss   File: TestJarFinder.java   View source code 6 votes vote down vote up
private static void delete(File file) throws IOException {
  if (file.getAbsolutePath().length() < 5) {
    throw new IllegalArgumentException(
      MessageFormat.format("Path [{0}] is too short, not deleting",
                           file.getAbsolutePath()));
  }
  if (file.exists()) {
    if (file.isDirectory()) {
      File[] children = file.listFiles();
      if (children != null) {
        for (File child : children) {
          delete(child);
        }
      }
    }
    if (!file.delete()) {
      throw new RuntimeException(
        MessageFormat.format("Could not delete path [{0}]",
                             file.getAbsolutePath()));
    }
  }
}
 
Example 19
Project: jwala   File: JvmServiceImpl.java   View source code 6 votes vote down vote up
@Override
public Jvm generateAndDeployFile(String jvmName, String fileName, User user) {
    Jvm jvm = getJvm(jvmName);
    // only one at a time per jvm
    binaryDistributionLockManager.writeLock(jvmName + "-" + jvm.getId().getId().toString());
    try {
        ResourceIdentifier resourceIdentifier = new ResourceIdentifier.Builder()
                .setResourceName(fileName)
                .setJvmName(jvmName)
                .build();
        checkJvmStateBeforeDeploy(jvm, resourceIdentifier);

        resourceService.validateSingleResourceForGeneration(resourceIdentifier);
        resourceService.generateAndDeployFile(resourceIdentifier, jvm.getJvmName(), fileName, jvm.getHostName());
    } catch (IOException e) {
        String errorMsg = MessageFormat.format("Failed to retrieve meta data when generating and deploying file {0} for JVM {1}", fileName, jvmName);
        LOGGER.error(errorMsg, e);
        throw new JvmServiceException(errorMsg);
    } finally {
        binaryDistributionLockManager.writeUnlock(jvmName + "-" + jvm.getId().getId().toString());
        LOGGER.debug("End generateAndDeployFile for {} by user {}", jvmName, user.getId());
    }
    return jvm;
}
 
Example 20
Project: SKIL_Examples   File: Model.java   View source code 6 votes vote down vote up
public JSONObject deleteModel(int modelID) {
    JSONObject model = new JSONObject();

    try {
        model =
                Unirest.delete(MessageFormat.format("http://{0}:{1}/deployment/{2}/model/{3}", host, port, deploymentID, modelID))
                        .header("accept", "application/json")
                        .header("Content-Type", "application/json")
                        .asJson()
                        .getBody().getObject();
    } catch (UnirestException e) {
        e.printStackTrace();
    }

    return model;
}
 
Example 21
Project: task-app   File: TaskAppServiceImpl.java   View source code 6 votes vote down vote up
@Override
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public Long createTask(String type, String name, String actor, String creator) {
    JmdTask task = new JmdTask();
    task.setType(type);
    task.setCreator(creator);
    task.setCreated(taskDao.getCurrentDate());
    task.setActor(actor);
    task.setName(name);
    task.setNameScdf(ScDf.toScDf(name));
    task.setStatus(TaskStatus.BOOKED.name());
    task.setInterruptEnabled(true);
    task.setInterruptFlag(false);
    task.setStopEnabled(true);
    task.setStopFlag(false);
    task.setKillFlag(false);
    task.setTotalStep(Integer.MAX_VALUE);
    task.setActualStep(0);
    task.setLastUpdate(task.getCreated());
    long taskId = taskDao.addTask(task);
    if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.fine(MessageFormat.format("Task with id {0} created.", taskId));
    }
    return taskId;
}
 
Example 22
Project: monarch   File: LauncherLifecycleCommandsDUnitTest.java   View source code 6 votes vote down vote up
@Test
public void test004StartServerFailsFastOnMissingGemFirePropertiesFile() throws IOException {
  String gemfirePropertiesFile = "/path/to/missing/gemfire.properties";

  CommandStringBuilder command = new CommandStringBuilder(CliStrings.START_SERVER);

  String pathName = getClass().getSimpleName().concat("_").concat(getTestMethodName());
  final File workingDirectory = temporaryFolder.newFolder(pathName);

  command.addOption(CliStrings.START_SERVER__NAME, pathName);
  command.addOption(CliStrings.START_SERVER__DIR, workingDirectory.getCanonicalPath());
  command.addOption(CliStrings.START_SERVER__PROPERTIES, gemfirePropertiesFile);

  CommandResult result = executeCommand(command.toString());

  assertNotNull(result);
  assertEquals(Result.Status.ERROR, result.getStatus());

  String resultString = toString(result);

  assertTrue(resultString,
      resultString
          .contains(MessageFormat.format(CliStrings.GEODE_0_PROPERTIES_1_NOT_FOUND_MESSAGE,
              StringUtils.EMPTY_STRING, gemfirePropertiesFile)));
}
 
Example 23
Project: Equella   File: ZookeeperServiceImpl.java   View source code 6 votes vote down vote up
@PostConstruct
private void setupNodeId()
{
	String randomUuid = UUID.randomUUID().toString();
	if( Check.isEmpty(zooKeeperNodeId) )
	{
		try
		{
			String hostname = InetAddress.getLocalHost().getHostName();
			zooKeeperNodeId = !Check.isEmpty(hostname) ? MessageFormat.format("{0}-{1}", hostname, randomUuid)
				: randomUuid;
		}
		catch( UnknownHostException e )
		{
			LOGGER.warn("Unable to retrieve hostname to generate node ID. Using random ID");
			zooKeeperNodeId = randomUuid;
		}
	}
	else
	{
		zooKeeperNodeId = MessageFormat.format("{0}-{1}", zooKeeperNodeId, randomUuid);
	}
}
 
Example 24
Project: openjdk-jdk10   File: SchemaWriter.java   View source code 6 votes vote down vote up
public void attributeUse( XSAttributeUse use ) {
    XSAttributeDecl decl = use.getDecl();

    String additionalAtts="";

    if(use.isRequired())
        additionalAtts += " use=\"required\"";
    if(use.getFixedValue()!=null && use.getDecl().getFixedValue()==null)
        additionalAtts += " fixed=\""+use.getFixedValue()+'\"';
    if(use.getDefaultValue()!=null && use.getDecl().getDefaultValue()==null)
        additionalAtts += " default=\""+use.getDefaultValue()+'\"';

    if(decl.isLocal()) {
        // this is anonymous attribute use
        dump(decl,additionalAtts);
    } else {
        // reference to a global one
        println(MessageFormat.format("<attribute ref=\"'{'{0}'}'{1}{2}\"/>",
            decl.getTargetNamespace(), decl.getName(), additionalAtts));
    }
}
 
Example 25
Project: incubator-netbeans   File: LogHandler.java   View source code 6 votes vote down vote up
@Override
public void publish(LogRecord record) {
    if(!done) {
        String message = record.getMessage();
        if(message == null) {
            return;
        }
        message = MessageFormat.format(message, record.getParameters());
        boolean intercepted = false;
        switch (compare) {
            case STARTS_WITH :
                intercepted = message.startsWith(messageToWaitFor);
                break;
            case ENDS_WITH :
                intercepted = message.endsWith(messageToWaitFor);
                break;
            default:
                throw new IllegalStateException("wrong value " + compare);
        }
        if(intercepted) {
            interceptedCount++;
            interceptedMessage = message;
        }
        done = intercepted && interceptedCount >= expectedCount;
    }
}
 
Example 26
Project: cyberduck   File: RenameExistingFilter.java   View source code 6 votes vote down vote up
/**
 * Rename existing file on server if there is a conflict.
 */
@Override
public void apply(final Path file, final Local local, final TransferStatus status,
                  final ProgressListener listener) throws BackgroundException {
    // Rename existing file before putting new file in place
    if(status.isExists()) {
        Path rename;
        do {
            final String proposal = MessageFormat.format(PreferencesFactory.get().getProperty("queue.upload.file.rename.format"),
                    FilenameUtils.getBaseName(file.getName()),
                    UserDateFormatterFactory.get().getMediumFormat(System.currentTimeMillis(), false).replace(Path.DELIMITER, '-').replace(':', '-'),
                    StringUtils.isNotBlank(file.getExtension()) ? String.format(".%s", file.getExtension()) : StringUtils.EMPTY);
            rename = new Path(file.getParent(), proposal, file.getType());
        }
        while(find.find(rename));
        if(log.isInfoEnabled()) {
            log.info(String.format("Rename existing file %s to %s", file, rename));
        }
        move.move(file, rename, new TransferStatus().exists(false), new Delete.DisabledCallback(), new DisabledConnectionCallback());
        if(log.isDebugEnabled()) {
            log.debug(String.format("Clear exist flag for file %s", file));
        }
        status.setExists(false);
    }
    super.apply(file, local, status, listener);
}
 
Example 27
Project: saluki   File: MapTypeBuilder.java   View source code 6 votes vote down vote up
@Override
public TypeDefinition build(Type type, Class<?> clazz, Map<Class<?>, TypeDefinition> typeCache) {
    if (!(type instanceof ParameterizedType)) {
        throw new IllegalArgumentException(MessageFormat.format("[Jaket] Unexpected type {0}.",
                new Object[]{type}));
    }

    ParameterizedType parameterizedType = (ParameterizedType) type;
    Type[] actualTypeArgs = parameterizedType.getActualTypeArguments();
    if (actualTypeArgs == null || actualTypeArgs.length != 2) {
        throw new IllegalArgumentException(MessageFormat.format(
                "[Jaket] Map type [{0}] with unexpected amount of arguments [{1}]." + actualTypeArgs, new Object[] {
                        type, actualTypeArgs }));
    }

    for (Type actualType : actualTypeArgs) {
        if (actualType instanceof ParameterizedType) {
            // Nested collection or map.
            Class<?> rawType = (Class<?>) ((ParameterizedType) actualType).getRawType();
            JaketTypeBuilder.build(actualType, rawType, typeCache);
        } else if (actualType instanceof Class<?>) {
            Class<?> actualClass = (Class<?>) actualType;
            if (actualClass.isArray() || actualClass.isEnum()) {
                JaketTypeBuilder.build(null, actualClass, typeCache);
            } else {
                DefaultTypeBuilder.build(actualClass, typeCache);
            }
        }
    }

    TypeDefinition td = new TypeDefinition(type.toString());
    return td;
}
 
Example 28
Project: open-rmbt   File: RMBTLoopService.java   View source code 6 votes vote down vote up
private void setNotificationText(NotificationCompat.Builder builder)
{
    final Resources res = getResources();
    
    final long now = SystemClock.elapsedRealtime();
    final long lastTestDelta = loopModeResults.getLastTestTime() == 0 ? 0 : now - loopModeResults.getLastTestTime();
    
    final String elapsedTimeString = LoopModeTriggerItem.formatSeconds(Math.round(lastTestDelta / 1000), 1);
    
    final CharSequence textTemplate = res.getText(R.string.loop_notification_text_without_stop);
    final CharSequence text = MessageFormat.format(textTemplate.toString(), 
    		loopModeResults.getNumberOfTests(), elapsedTimeString, Math.round(loopModeResults.getLastDistance()));
    builder.setContentText(text);
    
    if (bigTextStyle == null)
    {
        bigTextStyle = (new NotificationCompat.BigTextStyle());
        builder.setStyle(bigTextStyle);
    }
    
    bigTextStyle.bigText(text);
}
 
Example 29
Project: asura   File: LoggingJobHistoryPlugin.java   View source code 6 votes vote down vote up
/** 
 * @see org.quartz.JobListener#jobWasExecuted(JobExecutionContext, JobExecutionException)
 */
public void jobWasExecuted(JobExecutionContext context,
        JobExecutionException jobException) {

    Trigger trigger = context.getTrigger();
    
    Object[] args = null;
    
    if (jobException != null) {
        if (!getLog().isWarnEnabled()) {
            return;
        } 
        
        String errMsg = jobException.getMessage();
        args = 
            new Object[] {
                context.getJobDetail().getName(),
                context.getJobDetail().getGroup(), new java.util.Date(),
                trigger.getName(), trigger.getGroup(),
                trigger.getPreviousFireTime(), trigger.getNextFireTime(),
                new Integer(context.getRefireCount()), errMsg
            };
        
        getLog().warn(MessageFormat.format(getJobFailedMessage(), args), jobException); 
    } else {
        if (!getLog().isInfoEnabled()) {
            return;
        } 
        
        String result = String.valueOf(context.getResult());
        args =
            new Object[] {
                context.getJobDetail().getName(),
                context.getJobDetail().getGroup(), new java.util.Date(),
                trigger.getName(), trigger.getGroup(),
                trigger.getPreviousFireTime(), trigger.getNextFireTime(),
                new Integer(context.getRefireCount()), result
            };
        
        getLog().info(MessageFormat.format(getJobSuccessMessage(), args));
    }
}
 
Example 30
Project: neoscada   File: DefaultMavenMapping.java   View source code 6 votes vote down vote up
private List<MavenReference> fromValue ( final IInstallableUnit iu, final String value ) throws Exception
{
    final String[] segs = value.split ( "," );

    final List<MavenReference> result = new ArrayList<> ( segs.length );

    for ( final String seg : segs )
    {
        final String[] toks = seg.split ( "\\:" );
        if ( toks.length == 3 )
        {
            final String version = MessageFormat.format ( toks[2], getSegments ( iu.getVersion () ) );
            result.add ( new MavenReference ( toks[0], toks[1], version ) );
        }
        else if ( toks.length == 2 )
        {
            // automatic version
            result.add ( new MavenReference ( toks[0], toks[1], makeVersion ( iu, false ) ) );
        }
        else
        {
            throw new IllegalArgumentException ( String.format ( "Maven reference has invalid syntax: %s", value ) );
        }
    }
    return result;
}
 
Example 31
Project: Transwarp-Sample-Code   File: KerberosWebHDFSConnection2.java   View source code 6 votes vote down vote up
/**
 * <b>GETFILESTATUS</b>
 *
 * curl -i "http://<HOST>:<PORT>/webhdfs/v1/<PATH>?op=GETFILESTATUS"
 *
 * @param path
 * @return
 * @throws MalformedURLException
 * @throws IOException
 * @throws AuthenticationException
 */
public String getFileStatus(String path) throws MalformedURLException,
        IOException, AuthenticationException {
    ensureValidToken();

    HttpURLConnection conn = authenticatedURL.openConnection(
            new URL(new URL(httpfsUrl), MessageFormat.format(
                    "/webhdfs/v1/{0}?op=GETFILESTATUS",
                    URLUtil.encodePath(path))), token);
    conn.setRequestMethod("GET");
    conn.connect();
    String resp = result(conn, true);
    conn.disconnect();

    return resp;
}
 
Example 32
Project: ProjectAres   File: MessageTemplate.java   View source code 6 votes vote down vote up
/**
 * Create a localized {@link MessageTemplate} from the given message key.
 */
public MessageTemplate fromKey(String key) {
    if(!translator.hasKey(key)) {
        throw new IllegalArgumentException("Missing translation key '" + key + "'");
    }
    return new MessageTemplate() {
        @Override
        public boolean isLocalized() {
            return true;
        }

        @Override
        public MessageFormat format(Locale locale) {
            return translator.pattern(key, locale).get();
        }

        @Override
        public String toString() {
            return MessageTemplate.class.getSimpleName() + "{key=" + key + "}";
        }
    };
}
 
Example 33
Project: cyberduck   File: S3UrlProvider.java   View source code 6 votes vote down vote up
/**
 * Properly URI encode and prepend the bucket name.
 *
 * @param scheme Protocol
 * @return URL to be displayed in browser
 */
protected DescriptiveUrl toUrl(final Path file, final Scheme scheme) {
    final StringBuilder url = new StringBuilder(scheme.name());
    url.append("://");
    if(file.isRoot()) {
        url.append(session.getHost().getHostname());
    }
    else {
        final String hostname = this.getHostnameForContainer(containerService.getContainer(file));
        if(hostname.startsWith(containerService.getContainer(file).getName())) {
            url.append(hostname);
            if(!containerService.isContainer(file)) {
                url.append(Path.DELIMITER);
                url.append(URIEncoder.encode(containerService.getKey(file)));
            }
        }
        else {
            url.append(session.getHost().getHostname());
            url.append(URIEncoder.encode(file.getAbsolute()));
        }
    }
    return new DescriptiveUrl(URI.create(url.toString()), DescriptiveUrl.Type.http,
            MessageFormat.format(LocaleFactory.localizedString("{0} URL"), scheme.name().toUpperCase(Locale.ROOT)));
}
 
Example 34
Project: rapidminer   File: I18N.java   View source code 6 votes vote down vote up
/**
 * Returns a message if found or the key if not found. Arguments <b>can</b> be specified which
 * will be used to format the String. In the {@link ResourceBundle} the String '{0}' (without ')
 * will be replaced by the first argument, '{1}' with the second and so on.
 *
 * Catches the exception thrown by ResourceBundle in the latter case.
 **/
public static String getMessage(ResourceBundle bundle, String key, Object... arguments) {
	try {

		if (arguments == null || arguments.length == 0) {
			return bundle.getString(key);
		} else {
			String message = bundle.getString(key);
			if (message != null) {
				return MessageFormat.format(message, arguments);
			} else {
				return key;
			}
		}

	} catch (MissingResourceException e) {
		LogService.getRoot().log(Level.FINE, "com.rapidminer.tools.I18N.missing_key", key);
		return key;
	}
}
 
Example 35
Project: vxrifa   File: PublisherGenerator.java   View source code 5 votes vote down vote up
PublisherGenerator generateInitializing() {

        tsb = TypeSpec.classBuilder(MessageFormat.format("{0}{1}", interfaceElement.getSimpleName(), VXRIFA_PUBLISHER_SUFFIX)).addModifiers(Modifier.PUBLIC);

        tsb.addSuperinterface(TypeName.get(interfaceElement.asType()));

        vertxField = FieldSpec.builder(io.vertx.core.Vertx.class, "vertx", Modifier.PRIVATE, Modifier.FINAL).build();
        tsb.addField(vertxField);

        eventBusAddressField = FieldSpec.builder(java.lang.String.class, "eventBusAddress", Modifier.PRIVATE, Modifier.FINAL).build();
        tsb.addField(eventBusAddressField);

        tsb.addMethod(
                MethodSpec.constructorBuilder()
                        .addModifiers(Modifier.PUBLIC)
                        .addParameter(io.vertx.core.Vertx.class, vertxField.name)
                        .addStatement("this.$N = $N", vertxField, vertxField)
                        .addStatement("this.$N = $S", eventBusAddressField, interfaceElement.getQualifiedName().toString())
                        .build()
        );

        tsb.addMethod(
                MethodSpec.constructorBuilder()
                        .addModifiers(Modifier.PUBLIC)
                        .addParameter(io.vertx.core.Vertx.class, vertxField.name)
                        .addParameter(java.lang.String.class, eventBusAddressField.name)
                        .addStatement("this.$N = $N", vertxField, vertxField)
                        .addStatement("this.$N = $N", eventBusAddressField, eventBusAddressField)
                        .build()
        );

        return this;

    }
 
Example 36
Project: cf-mta-deploy-service   File: GitRepoCloner.java   View source code 5 votes vote down vote up
public void cloneRepo(final String gitUri, final Path repoDir) throws InvalidRemoteException, GitAPIException, IOException {
    if (Files.exists(repoDir)) {
        LOGGER.debug("Deleting left-over repo dir" + repoDir.toAbsolutePath().toString());
        com.sap.cloud.lm.sl.cf.core.util.FileUtils.deleteDirectory(repoDir);
    }

    configureGitSslValidation();
    if (shoudlUseToken(gitServiceUrlString, gitUri)) {
        cloneCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider(userName, token));
    }
    if (refName != null && !refName.isEmpty()) {
        String fullRefName = refName.startsWith("refs/") ? refName : "refs/heads/" + refName;
        cloneCommand.setBranchesToClone(Arrays.asList(new String[] { fullRefName }));
        cloneCommand.setBranch(fullRefName);
    }
    cloneCommand.setTimeout(290);
    cloneCommand.setDirectory(repoDir.toAbsolutePath().toFile());
    cloneCommand.setURI(gitUri);
    LOGGER.debug(
        MessageFormat.format("cloning repo with url {0} in repo dir {1} ref '{2}'", gitUri, repoDir.toAbsolutePath().toString()));
    try (Git callInstance = cloneCommand.call()) {
        Repository repo = callInstance.getRepository();
        repo.close();
    } catch (TransportException e) {
        Throwable cause1 = e.getCause();
        if (cause1 != null && cause1.getCause() instanceof SSLHandshakeException) {
            throw new SLException(cause1.getCause(), "Failed to establish ssl connection"); // NOSONAR
        }
        throw e;
    }
}
 
Example 37
Project: incubator-netbeans   File: CopyClassesRefactoringPlugin.java   View source code 5 votes vote down vote up
@Override
public Problem fastCheckParameters() {
    URL target = refactoring.getTarget().lookup(URL.class);
    try {
        target.toURI();
    } catch (URISyntaxException ex) {
        return createProblem(null, true, NbBundle.getMessage(CopyClassesRefactoringPlugin.class, "ERR_InvalidPackage", RefactoringUtils.getPackageName(target)));
    }
    FileObject fo = target != null ? URLMapper.findFileObject(target) : null;
    if (fo == null) {
        return createProblem(null, true, NbBundle.getMessage(CopyClassesRefactoringPlugin.class, "ERR_TargetFolderNotSet"));
    }
    if (!JavaRefactoringUtils.isOnSourceClasspath(fo)) {
        return createProblem(null, true, NbBundle.getMessage(CopyClassesRefactoringPlugin.class, "ERR_TargetFolderNotJavaPackage"));
    }
    String targetPackageName = RefactoringUtils.getPackageName(target);
    if (!RefactoringUtils.isValidPackageName(targetPackageName)) {
        String msg = new MessageFormat(NbBundle.getMessage(CopyClassesRefactoringPlugin.class, "ERR_InvalidPackage")).format(
                new Object[]{targetPackageName});
        return createProblem(null, true, msg);
    }
    Collection<? extends FileObject> sources = refactoring.getRefactoringSource().lookupAll(FileObject.class);
    Problem p = null;
    for (FileObject fileObject : sources) {
        if (fo.getFileObject(fileObject.getName(), fileObject.getExt()) != null) {
            p = createProblem(p, false, NbBundle.getMessage(CopyClassesRefactoringPlugin.class, "ERR_ClassesToCopyClashes"));
            break;
        }
    }
    return p;
}
 
Example 38
Project: cyberduck   File: DistributionUrlProvider.java   View source code 5 votes vote down vote up
/**
 * @param file File in origin container
 * @return CNAME to distribution
 */
private List<DescriptiveUrl> toCnameUrl(final Path file) {
    final List<DescriptiveUrl> urls = new ArrayList<DescriptiveUrl>();
    for(String cname : distribution.getCNAMEs()) {
        final StringBuilder b = new StringBuilder();
        b.append(String.format("%s://%s", distribution.getMethod().getScheme(), cname)).append(distribution.getMethod().getContext());
        if(StringUtils.isNotEmpty(containerService.getKey(file))) {
            b.append(Path.DELIMITER).append(URIEncoder.encode(containerService.getKey(file)));
        }
        urls.add(new DescriptiveUrl(URI.create(b.toString()).normalize(), DescriptiveUrl.Type.cname,
                MessageFormat.format(LocaleFactory.localizedString("{0} URL"), LocaleFactory.localizedString(distribution.getMethod().toString(), "S3"))));
    }
    return urls;
}
 
Example 39
Project: aws-photosharing-example   File: Share.java   View source code 5 votes vote down vote up
@Transient
public String getShareUrl() {
	if (getAlbum() != null)
		return MessageFormat.format(Configuration.SHARE_ALBUM_PUBLIC_URL_FORMAT.toString(), getHash());
	else
		return MessageFormat.format(Configuration.SHARE_MEDIA_PUBLIC_URL_FORMAT.toString(), getHash());
}
 
Example 40
Project: otter-G   File: MessageDumper.java   View source code 5 votes vote down vote up
public static String dumpMessageInfo(Message<EventData> message, String startPosition, String endPosition, int total) {
    Date now = new Date();
    SimpleDateFormat format = new SimpleDateFormat(TIMESTAMP_FORMAT);
    int normal = message.getDatas().size();
    return MessageFormat.format(context_format, String.valueOf(message.getId()), total, normal, total - normal,
                                format.format(now), startPosition, endPosition);
}